karuppayya commented on code in PR #4519:
URL: https://github.com/apache/datafusion-comet/pull/4519#discussion_r3350783651


##########
spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.comet.{CometColumnarToRowExec, CometExec, 
CometNativeColumnarToRowExec, CometSparkToColumnarExec}
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.{ColumnarToRowExec, 
ColumnarToRowTransition, RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, 
ShuffleExchangeLike}
+
+import org.apache.comet.CometConf
+
+/**
+ * Reverts a query stage to Spark row-based execution when it has too many 
columnar-to-row (C2R)
+ * transitions. Each C2R indicates Comet could not keep execution columnar and 
had to fall back.
+ * With columnar shuffle enabled, each C2R implies a corresponding R2C 
round-trip.
+ */
+case class RevertNativeForTransitionHeavyStages(session: SparkSession)
+    extends Rule[SparkPlan]
+    with Logging {
+
+  private lazy val enabled = 
CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.get()
+  private lazy val maxTransitions = 
CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.get()
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!enabled) return plan
+
+    if (session.sessionState.conf.adaptiveExecutionEnabled) {
+      applyForAQE(plan)
+    } else {
+      applyForNonAQE(plan)
+    }
+  }
+
+  private def applyForAQE(plan: SparkPlan): SparkPlan = {
+    plan match {
+      case _: BroadcastExchangeLike => plan
+      case exchange: ShuffleExchangeLike =>
+        revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+          .map(reverted => exchange.withNewChildren(Seq(reverted)))
+          .getOrElse(plan)
+      case _ =>
+        revertStageIfNeeded(plan, outputColumnar = false).getOrElse(plan)
+    }
+  }
+
+  private def applyForNonAQE(plan: SparkPlan): SparkPlan = {
+    plan.transformUp { case exchange: ShuffleExchangeLike =>
+      revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+        .map(reverted => exchange.withNewChildren(Seq(reverted)))
+        .getOrElse(exchange)
+    }
+  }
+
+  /**
+   * Reverts the stage if C2R count exceeds threshold. Wraps in R2C if 
exchange needs columnar.
+   */
+  private def revertStageIfNeeded(
+      stagePlan: SparkPlan,
+      outputColumnar: Boolean): Option[SparkPlan] = {
+    val transitionCount = countTransitions(stagePlan)
+    if (transitionCount <= maxTransitions) return None
+
+    logInfo(
+      s"Reverting Comet native execution for stage with $transitionCount C2R 
transitions " +
+        s"(threshold: $maxTransitions).")
+
+    val reverted = revertToSpark(stagePlan)
+    val result = if (outputColumnar && !reverted.supportsColumnar) {
+      RowToColumnarExec(reverted)
+    } else {
+      reverted
+    }
+    Some(result)
+  }
+
+  /** Counts C2R transitions within this stage, stopping at stage boundaries. 
*/
+  private[rules] def countTransitions(plan: SparkPlan): Int = {
+    var count = 0
+    def visit(node: SparkPlan): Unit = node match {
+      case _: QueryStageExec | _: ShuffleExchangeLike => ()
+      case _: ColumnarToRowTransition =>
+        count += 1
+        node.children.foreach(visit)
+      case _ =>
+        node.children.foreach(visit)
+    }
+    visit(plan)
+    count
+  }
+
+  // Three passes:
+  // 1. Strip existing transitions (they assert child.supportsColumnar in 
constructors)
+  // 2. Revert Comet operators to row-based Spark equivalents
+  // 3. Re-insert ColumnarToRowExec where a columnar child feeds a row-based 
parent
+  //    (e.g. QueryStageExec from a prior CometShuffleExchangeExec stage)
+  private[rules] def revertToSpark(plan: SparkPlan): SparkPlan = {
+    val stripped = plan.transformDown {
+      case CometNativeColumnarToRowExec(child) => child
+      case CometColumnarToRowExec(child) => child
+      case ColumnarToRowExec(child) => child
+      case sparkToColumnar: CometSparkToColumnarExec => sparkToColumnar.child
+      case RowToColumnarExec(child) => child
+    }
+    val reverted = stripped.transformUp {
+      case cometShuffle: CometShuffleExchangeExec =>
+        cometShuffle.originalPlan.withNewChildren(Seq(cometShuffle.child))
+      case cometExec: CometExec =>
+        if (cometExec.originalPlan.children.size == cometExec.children.size) {
+          cometExec.originalPlan.withNewChildren(cometExec.children)
+        } else {

Review Comment:
   Added a warnign



##########
spark/src/main/scala/org/apache/comet/CometConf.scala:
##########
@@ -442,6 +442,35 @@ object CometConf extends ShimCometConf {
       .booleanConf
       .createWithDefault(true)
 
+  val COMET_EXEC_TRANSITION_REVERT_ENABLED: ConfigEntry[Boolean] =
+    conf(s"$COMET_EXEC_CONFIG_PREFIX.transitionRevert.enabled")
+      .category(CATEGORY_EXEC)
+      .doc(
+        "When enabled, Comet reverts a query stage to Spark row-based 
execution if the number " +
+          "of columnar-to-row and row-to-columnar transition pairs exceeds the 
configured " +
+          "threshold. This avoids the overhead of repeated format conversions 
in stages where " +
+          "many operators fall back to row-based execution.")
+      .booleanConf
+      .createWithDefault(true)
+
+  val COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS: ConfigEntry[Int] =
+    conf(s"$COMET_EXEC_CONFIG_PREFIX.transitionRevert.maxTransitions")
+      .category(CATEGORY_EXEC)
+      .doc(
+        "The maximum number of columnar-to-row (C2R) transitions allowed in a 
single query " +
+          "stage before Comet reverts the entire stage to Spark row-based 
execution. When " +
+          "columnar shuffle is enabled, each C2R has a corresponding 
row-to-columnar (R2C) " +
+          "conversion to feed back into the columnar shuffle, so the count 
reflects full " +
+          "round-trips. Minimum value is 2 because reverting a stage that 
feeds a columnar " +
+          "shuffle still requires at least one R2C at the shuffle boundary. " +
+          "Only effective when spark.comet.exec.transitionRevert.enabled is 
true.")
+      .intConf
+      .checkValue(
+        _ >= 2,
+        "Must be >= 2. A reverted stage still requires at least one " +
+          "R2C at the columnar shuffle boundary.")
+      .createWithDefault(2)

Review Comment:
    I'd like to keep the threshold at 2 eventually since more than 2 
transitions means significant overhead. But for now I've bumped it to 5 for CI 
to pass. Once we've reviewed the logic , we can iterate on the default and fix 
test failures than came with it?. 
   



##########
spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.comet.{CometColumnarToRowExec, CometExec, 
CometNativeColumnarToRowExec, CometSparkToColumnarExec}
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.{ColumnarToRowExec, 
ColumnarToRowTransition, RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, 
ShuffleExchangeLike}
+
+import org.apache.comet.CometConf
+
+/**
+ * Reverts a query stage to Spark row-based execution when it has too many 
columnar-to-row (C2R)
+ * transitions. Each C2R indicates Comet could not keep execution columnar and 
had to fall back.
+ * With columnar shuffle enabled, each C2R implies a corresponding R2C 
round-trip.
+ */
+case class RevertNativeForTransitionHeavyStages(session: SparkSession)
+    extends Rule[SparkPlan]
+    with Logging {
+
+  private lazy val enabled = 
CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.get()
+  private lazy val maxTransitions = 
CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.get()
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!enabled) return plan
+
+    if (session.sessionState.conf.adaptiveExecutionEnabled) {
+      applyForAQE(plan)
+    } else {
+      applyForNonAQE(plan)
+    }
+  }
+
+  private def applyForAQE(plan: SparkPlan): SparkPlan = {
+    plan match {
+      case _: BroadcastExchangeLike => plan
+      case exchange: ShuffleExchangeLike =>
+        revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+          .map(reverted => exchange.withNewChildren(Seq(reverted)))
+          .getOrElse(plan)
+      case _ =>
+        revertStageIfNeeded(plan, outputColumnar = false).getOrElse(plan)
+    }
+  }
+
+  private def applyForNonAQE(plan: SparkPlan): SparkPlan = {
+    plan.transformUp { case exchange: ShuffleExchangeLike =>
+      revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+        .map(reverted => exchange.withNewChildren(Seq(reverted)))
+        .getOrElse(exchange)
+    }
+  }
+
+  /**
+   * Reverts the stage if C2R count exceeds threshold. Wraps in R2C if 
exchange needs columnar.
+   */
+  private def revertStageIfNeeded(
+      stagePlan: SparkPlan,
+      outputColumnar: Boolean): Option[SparkPlan] = {
+    val transitionCount = countTransitions(stagePlan)
+    if (transitionCount <= maxTransitions) return None
+
+    logInfo(
+      s"Reverting Comet native execution for stage with $transitionCount C2R 
transitions " +
+        s"(threshold: $maxTransitions).")
+
+    val reverted = revertToSpark(stagePlan)
+    val result = if (outputColumnar && !reverted.supportsColumnar) {
+      RowToColumnarExec(reverted)
+    } else {
+      reverted
+    }
+    Some(result)
+  }
+
+  /** Counts C2R transitions within this stage, stopping at stage boundaries. 
*/
+  private[rules] def countTransitions(plan: SparkPlan): Int = {
+    var count = 0
+    def visit(node: SparkPlan): Unit = node match {
+      case _: QueryStageExec | _: ShuffleExchangeLike => ()
+      case _: ColumnarToRowTransition =>
+        count += 1
+        node.children.foreach(visit)
+      case _ =>
+        node.children.foreach(visit)
+    }
+    visit(plan)
+    count
+  }
+
+  // Three passes:
+  // 1. Strip existing transitions (they assert child.supportsColumnar in 
constructors)
+  // 2. Revert Comet operators to row-based Spark equivalents
+  // 3. Re-insert ColumnarToRowExec where a columnar child feeds a row-based 
parent
+  //    (e.g. QueryStageExec from a prior CometShuffleExchangeExec stage)
+  private[rules] def revertToSpark(plan: SparkPlan): SparkPlan = {
+    val stripped = plan.transformDown {
+      case CometNativeColumnarToRowExec(child) => child
+      case CometColumnarToRowExec(child) => child
+      case ColumnarToRowExec(child) => child
+      case sparkToColumnar: CometSparkToColumnarExec => sparkToColumnar.child
+      case RowToColumnarExec(child) => child
+    }
+    val reverted = stripped.transformUp {
+      case cometShuffle: CometShuffleExchangeExec =>

Review Comment:
    In AQE this is already handled — the broadcast exchange is wrapped in 
`BroadcastQueryStageExec` (which extends `QueryStageExec`), and 
`countTransitions` stops at `QueryStageExec`.
    For non-AQE, I've added `BroadcastExchangeLike` to the stop condition in 
countTransitions to treat it as an execution boundary.(as broadcast runs as a 
separate job independentof the parent stage).



##########
spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.comet.{CometColumnarToRowExec, CometExec, 
CometNativeColumnarToRowExec, CometSparkToColumnarExec}
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.{ColumnarToRowExec, 
ColumnarToRowTransition, RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, 
ShuffleExchangeLike}
+
+import org.apache.comet.CometConf
+
+/**
+ * Reverts a query stage to Spark row-based execution when it has too many 
columnar-to-row (C2R)
+ * transitions. Each C2R indicates Comet could not keep execution columnar and 
had to fall back.
+ * With columnar shuffle enabled, each C2R implies a corresponding R2C 
round-trip.
+ */
+case class RevertNativeForTransitionHeavyStages(session: SparkSession)
+    extends Rule[SparkPlan]
+    with Logging {
+
+  private lazy val enabled = 
CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.get()
+  private lazy val maxTransitions = 
CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.get()
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!enabled) return plan
+
+    if (session.sessionState.conf.adaptiveExecutionEnabled) {
+      applyForAQE(plan)
+    } else {
+      applyForNonAQE(plan)
+    }
+  }
+
+  private def applyForAQE(plan: SparkPlan): SparkPlan = {
+    plan match {
+      case _: BroadcastExchangeLike => plan
+      case exchange: ShuffleExchangeLike =>
+        revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+          .map(reverted => exchange.withNewChildren(Seq(reverted)))
+          .getOrElse(plan)
+      case _ =>
+        revertStageIfNeeded(plan, outputColumnar = false).getOrElse(plan)
+    }
+  }
+
+  private def applyForNonAQE(plan: SparkPlan): SparkPlan = {
+    plan.transformUp { case exchange: ShuffleExchangeLike =>
+      revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+        .map(reverted => exchange.withNewChildren(Seq(reverted)))
+        .getOrElse(exchange)

Review Comment:
   Added



##########
spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.comet.{CometColumnarToRowExec, CometExec, 
CometNativeColumnarToRowExec, CometSparkToColumnarExec}
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.{ColumnarToRowExec, 
ColumnarToRowTransition, RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, 
ShuffleExchangeLike}
+
+import org.apache.comet.CometConf
+
+/**
+ * Reverts a query stage to Spark row-based execution when it has too many 
columnar-to-row (C2R)
+ * transitions. Each C2R indicates Comet could not keep execution columnar and 
had to fall back.
+ * With columnar shuffle enabled, each C2R implies a corresponding R2C 
round-trip.
+ */
+case class RevertNativeForTransitionHeavyStages(session: SparkSession)
+    extends Rule[SparkPlan]
+    with Logging {
+
+  private lazy val enabled = 
CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.get()
+  private lazy val maxTransitions = 
CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.get()
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!enabled) return plan
+
+    if (session.sessionState.conf.adaptiveExecutionEnabled) {
+      applyForAQE(plan)
+    } else {
+      applyForNonAQE(plan)
+    }
+  }
+
+  private def applyForAQE(plan: SparkPlan): SparkPlan = {
+    plan match {
+      case _: BroadcastExchangeLike => plan
+      case exchange: ShuffleExchangeLike =>
+        revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+          .map(reverted => exchange.withNewChildren(Seq(reverted)))
+          .getOrElse(plan)
+      case _ =>
+        revertStageIfNeeded(plan, outputColumnar = false).getOrElse(plan)
+    }
+  }
+
+  private def applyForNonAQE(plan: SparkPlan): SparkPlan = {
+    plan.transformUp { case exchange: ShuffleExchangeLike =>
+      revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+        .map(reverted => exchange.withNewChildren(Seq(reverted)))
+        .getOrElse(exchange)
+    }
+  }
+
+  /**
+   * Reverts the stage if C2R count exceeds threshold. Wraps in R2C if 
exchange needs columnar.
+   */
+  private def revertStageIfNeeded(
+      stagePlan: SparkPlan,
+      outputColumnar: Boolean): Option[SparkPlan] = {
+    val transitionCount = countTransitions(stagePlan)
+    if (transitionCount <= maxTransitions) return None
+
+    logInfo(
+      s"Reverting Comet native execution for stage with $transitionCount C2R 
transitions " +
+        s"(threshold: $maxTransitions).")
+
+    val reverted = revertToSpark(stagePlan)
+    val result = if (outputColumnar && !reverted.supportsColumnar) {
+      RowToColumnarExec(reverted)
+    } else {
+      reverted
+    }
+    Some(result)
+  }
+
+  /** Counts C2R transitions within this stage, stopping at stage boundaries. 
*/
+  private[rules] def countTransitions(plan: SparkPlan): Int = {
+    var count = 0
+    def visit(node: SparkPlan): Unit = node match {
+      case _: QueryStageExec | _: ShuffleExchangeLike => ()
+      case _: ColumnarToRowTransition =>
+        count += 1
+        node.children.foreach(visit)
+      case _ =>
+        node.children.foreach(visit)
+    }
+    visit(plan)
+    count
+  }
+
+  // Three passes:
+  // 1. Strip existing transitions (they assert child.supportsColumnar in 
constructors)
+  // 2. Revert Comet operators to row-based Spark equivalents
+  // 3. Re-insert ColumnarToRowExec where a columnar child feeds a row-based 
parent
+  //    (e.g. QueryStageExec from a prior CometShuffleExchangeExec stage)
+  private[rules] def revertToSpark(plan: SparkPlan): SparkPlan = {
+    val stripped = plan.transformDown {
+      case CometNativeColumnarToRowExec(child) => child
+      case CometColumnarToRowExec(child) => child
+      case ColumnarToRowExec(child) => child
+      case sparkToColumnar: CometSparkToColumnarExec => sparkToColumnar.child
+      case RowToColumnarExec(child) => child
+    }
+    val reverted = stripped.transformUp {
+      case cometShuffle: CometShuffleExchangeExec =>
+        cometShuffle.originalPlan.withNewChildren(Seq(cometShuffle.child))
+      case cometExec: CometExec =>
+        if (cometExec.originalPlan.children.size == cometExec.children.size) {
+          cometExec.originalPlan.withNewChildren(cometExec.children)
+        } else {
+          cometExec.originalPlan
+        }
+    }
+    insertTransitions(reverted)
+  }
+
+  private def insertTransitions(plan: SparkPlan): SparkPlan = {
+    plan.transformUp {
+      case node if !node.isInstanceOf[QueryStageExec] && 
!node.supportsColumnar =>
+        val newChildren = node.children.map { child =>
+          if (child.supportsColumnar) ColumnarToRowExec(child) else child

Review Comment:
   After `revertToSpark`, all CometExec nodes are replaced with their row-based 
operator. The only columnar nodes remaining would be QueryStageExec leaves 
(inputs from prior stages). I think we will have  only  columnar children 
feeding row-based parents. May be i am missing the scenario, an example would 
help.



##########
spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala:
##########
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.comet.{CometColumnarToRowExec, CometExec, 
CometNativeColumnarToRowExec, CometSparkToColumnarExec}
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution.{ColumnarToRowExec, 
ColumnarToRowTransition, RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, 
ShuffleExchangeLike}
+
+import org.apache.comet.CometConf
+
+/**
+ * Reverts a query stage to Spark row-based execution when it has too many 
columnar-to-row (C2R)
+ * transitions. Each C2R indicates Comet could not keep execution columnar and 
had to fall back.
+ * With columnar shuffle enabled, each C2R implies a corresponding R2C 
round-trip.
+ */
+case class RevertNativeForTransitionHeavyStages(session: SparkSession)
+    extends Rule[SparkPlan]
+    with Logging {
+
+  private lazy val enabled = 
CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.get()
+  private lazy val maxTransitions = 
CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.get()
+
+  override def apply(plan: SparkPlan): SparkPlan = {
+    if (!enabled) return plan
+
+    if (session.sessionState.conf.adaptiveExecutionEnabled) {
+      applyForAQE(plan)
+    } else {
+      applyForNonAQE(plan)
+    }
+  }
+
+  private def applyForAQE(plan: SparkPlan): SparkPlan = {
+    plan match {
+      case _: BroadcastExchangeLike => plan
+      case exchange: ShuffleExchangeLike =>
+        revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+          .map(reverted => exchange.withNewChildren(Seq(reverted)))
+          .getOrElse(plan)
+      case _ =>
+        revertStageIfNeeded(plan, outputColumnar = false).getOrElse(plan)
+    }
+  }
+
+  private def applyForNonAQE(plan: SparkPlan): SparkPlan = {
+    plan.transformUp { case exchange: ShuffleExchangeLike =>
+      revertStageIfNeeded(exchange.child, exchange.supportsColumnar)
+        .map(reverted => exchange.withNewChildren(Seq(reverted)))
+        .getOrElse(exchange)
+    }
+  }
+
+  /**
+   * Reverts the stage if C2R count exceeds threshold. Wraps in R2C if 
exchange needs columnar.
+   */
+  private def revertStageIfNeeded(
+      stagePlan: SparkPlan,
+      outputColumnar: Boolean): Option[SparkPlan] = {
+    val transitionCount = countTransitions(stagePlan)
+    if (transitionCount <= maxTransitions) return None
+
+    logInfo(
+      s"Reverting Comet native execution for stage with $transitionCount C2R 
transitions " +
+        s"(threshold: $maxTransitions).")
+
+    val reverted = revertToSpark(stagePlan)
+    val result = if (outputColumnar && !reverted.supportsColumnar) {
+      RowToColumnarExec(reverted)
+    } else {
+      reverted
+    }
+    Some(result)
+  }
+
+  /** Counts C2R transitions within this stage, stopping at stage boundaries. 
*/
+  private[rules] def countTransitions(plan: SparkPlan): Int = {
+    var count = 0
+    def visit(node: SparkPlan): Unit = node match {
+      case _: QueryStageExec | _: ShuffleExchangeLike => ()
+      case _: ColumnarToRowTransition =>
+        count += 1
+        node.children.foreach(visit)
+      case _ =>
+        node.children.foreach(visit)
+    }
+    visit(plan)
+    count
+  }
+
+  // Three passes:
+  // 1. Strip existing transitions (they assert child.supportsColumnar in 
constructors)
+  // 2. Revert Comet operators to row-based Spark equivalents
+  // 3. Re-insert ColumnarToRowExec where a columnar child feeds a row-based 
parent
+  //    (e.g. QueryStageExec from a prior CometShuffleExchangeExec stage)
+  private[rules] def revertToSpark(plan: SparkPlan): SparkPlan = {
+    val stripped = plan.transformDown {
+      case CometNativeColumnarToRowExec(child) => child
+      case CometColumnarToRowExec(child) => child
+      case ColumnarToRowExec(child) => child
+      case sparkToColumnar: CometSparkToColumnarExec => sparkToColumnar.child
+      case RowToColumnarExec(child) => child
+    }
+    val reverted = stripped.transformUp {
+      case cometShuffle: CometShuffleExchangeExec =>
+        cometShuffle.originalPlan.withNewChildren(Seq(cometShuffle.child))
+      case cometExec: CometExec =>
+        if (cometExec.originalPlan.children.size == cometExec.children.size) {
+          cometExec.originalPlan.withNewChildren(cometExec.children)
+        } else {
+          cometExec.originalPlan
+        }
+    }
+    insertTransitions(reverted)
+  }
+
+  private def insertTransitions(plan: SparkPlan): SparkPlan = {
+    plan.transformUp {
+      case node if !node.isInstanceOf[QueryStageExec] && 
!node.supportsColumnar =>
+        val newChildren = node.children.map { child =>
+          if (child.supportsColumnar) ColumnarToRowExec(child) else child
+        }
+        if (newChildren != node.children) node.withNewChildren(newChildren) 
else node
+    }
+  }
+}

Review Comment:
   Unrelated?



##########
spark/src/test/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStagesSuite.scala:
##########
@@ -0,0 +1,277 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.comet.rules
+
+import org.apache.spark.sql.CometTestBase
+import org.apache.spark.sql.comet._
+import org.apache.spark.sql.comet.execution.shuffle.CometShuffleExchangeExec
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+
+import org.apache.comet.CometConf
+
+class RevertNativeForTransitionHeavyStagesSuite extends CometTestBase {
+
+  private def createSparkPlan(sql: String): SparkPlan = {
+    var plan: SparkPlan = null
+    withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+      plan = spark.sql(sql).queryExecution.executedPlan
+    }
+    stripAQEPlan(plan)
+  }
+
+  private def applyCometExecRule(plan: SparkPlan): SparkPlan = {
+    CometExecRule(spark).apply(plan)
+  }
+
+  private def applyFullColumnarPipeline(plan: SparkPlan): SparkPlan = {
+    val cometPlan = CometScanRule(spark).apply(plan)
+    val execPlan = CometExecRule(spark).apply(cometPlan)
+    val withTransitions = ApplyColumnarRulesAndInsertTransitions(Seq.empty, 
false).apply(execPlan)
+    EliminateRedundantTransitions(spark).apply(withTransitions)
+  }
+
+  private def countCometExecs(plan: SparkPlan): Int = {
+    plan.collect { case _: CometExec => true }.size
+  }
+
+  private def countC2RNodes(plan: SparkPlan): Int = {
+    plan.collect { case _: ColumnarToRowTransition => true }.size
+  }
+
+  test("rule is a no-op when disabled") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.key -> "false") {
+      val rule = RevertNativeForTransitionHeavyStages(spark)
+      val sparkPlan = createSparkPlan("SELECT 1")
+      val cometPlan = applyCometExecRule(sparkPlan)
+      val result = rule.apply(cometPlan)
+      assert(result eq cometPlan, "Rule should be a no-op when disabled")
+    }
+  }
+
+  test("rule does not revert plan below threshold") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.key -> "10") {
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan =
+          createSparkPlan("SELECT id, id * 2 as doubled FROM test_data WHERE 
id > 5")
+        val cometPlan = applyCometExecRule(sparkPlan)
+
+        val rule = RevertNativeForTransitionHeavyStages(spark)
+        val result = rule.apply(cometPlan)
+        assert(result eq cometPlan, "Plan should be unchanged when below 
threshold")
+      }
+    }
+  }
+
+  test("countTransitions counts non-root C2R correctly") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true") {
+      val rule = RevertNativeForTransitionHeavyStages(spark)
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan = createSparkPlan("SELECT id FROM test_data")
+        val cometPlan = applyFullColumnarPipeline(sparkPlan)
+
+        val count = rule.countTransitions(cometPlan)
+        // A simple scan+project plan should have 0 or 1 transitions
+        assert(count >= 0, s"Transition count should be non-negative, got 
$count")
+      }
+    }
+  }
+
+  test("countTransitions counts all C2R nodes including root") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true") {
+      val rule = RevertNativeForTransitionHeavyStages(spark)
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan = createSparkPlan("SELECT id FROM test_data")
+        val cometPlan = applyCometExecRule(sparkPlan)
+
+        // Wrap in a ColumnarToRow (simulating a terminal output)
+        val planWithRootC2R = ColumnarToRowExec(cometPlan)
+        val count = rule.countTransitions(planWithRootC2R)
+        assert(count == 1, s"Should count the C2R node, got $count")
+      }
+    }
+  }
+
+  test("revertToSpark removes CometExec operators") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_LOCAL_TABLE_SCAN_ENABLED.key -> "true") {
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan =
+          createSparkPlan("SELECT id, id * 2 as doubled FROM test_data WHERE 
id > 5")
+        val cometPlan = applyCometExecRule(sparkPlan)
+
+        assert(countCometExecs(cometPlan) > 0, "Should have CometExec nodes 
before revert")
+
+        val rule = RevertNativeForTransitionHeavyStages(spark)
+        val reverted = rule.revertToSpark(cometPlan)
+
+        assert(
+          countCometExecs(reverted) == 0,
+          s"Should have no CometExec nodes after revert, 
plan:\n${reverted.treeString}")
+      }
+    }
+  }
+
+  test("revertToSpark preserves plan structure") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_LOCAL_TABLE_SCAN_ENABLED.key -> "true") {
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan =
+          createSparkPlan("SELECT id, id * 2 as doubled FROM test_data WHERE 
id > 5")
+        val cometPlan = applyCometExecRule(sparkPlan)
+        val rule = RevertNativeForTransitionHeavyStages(spark)
+        val reverted = rule.revertToSpark(cometPlan)
+
+        // Reverted plan should have same output schema
+        assert(
+          reverted.output.map(_.name) == cometPlan.output.map(_.name),
+          "Output schema should be preserved after revert")
+      }
+    }
+  }
+
+  test("revertToSpark removes all Comet operators from a plan with 
transitions") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_LOCAL_TABLE_SCAN_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.key -> "true") {
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan =
+          createSparkPlan("SELECT id, id * 2 as doubled FROM test_data WHERE 
id > 5")
+        val cometPlan = applyFullColumnarPipeline(sparkPlan)
+
+        val rule = RevertNativeForTransitionHeavyStages(spark)
+        val result = rule.revertToSpark(cometPlan)
+        assert(
+          countCometExecs(result) == 0,
+          s"All CometExec should be reverted. Plan:\n${result.treeString}")
+      }
+    }
+  }
+
+  test("CometShuffleExchangeExec is reverted by revertToSpark") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
+      "spark.sql.adaptive.enabled" -> "false") {
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan = createSparkPlan("SELECT id FROM test_data DISTRIBUTE 
BY id")
+        val cometPlan = applyCometExecRule(sparkPlan)
+
+        val cometShuffles = cometPlan.collect { case s: 
CometShuffleExchangeExec => s }
+        if (cometShuffles.nonEmpty) {
+          val rule = RevertNativeForTransitionHeavyStages(spark)
+          val reverted = rule.revertToSpark(cometPlan)
+          val remainingCometShuffles = reverted.collect { case s: 
CometShuffleExchangeExec =>
+            s
+          }
+          assert(
+            remainingCometShuffles.isEmpty,
+            "CometShuffleExchangeExec should be reverted to 
ShuffleExchangeExec")
+          val sparkShuffles = reverted.collect { case s: ShuffleExchangeExec 
=> s }
+          assert(sparkShuffles.nonEmpty, "Should have ShuffleExchangeExec 
after revert")
+        }
+      }
+    }
+  }
+
+  test("non-AQE path applies rule per-stage via transformUp") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.key -> "10",
+      "spark.sql.adaptive.enabled" -> "false") {
+
+      withTempView("test_data") {
+        spark
+          .range(10)
+          .selectExpr("id", "id % 3 as grp")
+          .createOrReplaceTempView("test_data")
+        val sparkPlan = createSparkPlan("SELECT grp, count(*) FROM test_data 
GROUP BY grp")
+        val cometPlan = applyCometExecRule(sparkPlan)
+
+        // With high threshold, the non-AQE path should not revert anything
+        val rule = RevertNativeForTransitionHeavyStages(spark)
+        val result = rule.apply(cometPlan)
+        assert(result eq cometPlan, "Non-AQE path should not revert when below 
threshold")
+      }
+    }
+  }
+
+  test("default threshold of 2 allows stages with up to 2 transition pairs") {
+    withSQLConf(
+      CometConf.COMET_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_ENABLED.key -> "true",
+      CometConf.COMET_EXEC_TRANSITION_REVERT_MAX_TRANSITIONS.key -> "2") {
+      val rule = RevertNativeForTransitionHeavyStages(spark)
+
+      withTempView("test_data") {
+        spark.range(10).toDF("id").createOrReplaceTempView("test_data")
+        val sparkPlan = createSparkPlan("SELECT id FROM test_data")
+        val cometPlan = applyFullColumnarPipeline(sparkPlan)
+
+        val pairs = rule.countTransitions(cometPlan)
+        val result = rule.apply(cometPlan)
+        if (pairs <= 2) {
+          assert(
+            result eq cometPlan,
+            s"Plan with $pairs pairs should NOT be reverted at threshold 2")
+        } else {
+          assert(
+            countCometExecs(result) == 0,
+            s"Plan with $pairs pairs should be reverted at threshold 2")
+        }
+      }
+    }
+  }
+}

Review Comment:
   I disabled the project operator to guarantee transitions Do you think we 
still need a test with a naturally fallback (unsupported expression may be 
UDF), or is the current approach
   sufficient?



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