karuppayya commented on code in PR #4519: URL: https://github.com/apache/datafusion-comet/pull/4519#discussion_r3426085919
########## 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: [This](https://github.com/apache/datafusion-comet/pull/4519/changes#diff-9c8fff44b484eeb532a537ea57778e453a032516420cb81f21cf3ccecaa1e8ecR73-R74) handles the final stage, since case match on `Exchnage` above(using `transformUp`) cannot catch it, which is the equivalent of `case _` (`ResultStage`) in AQE flow ########## spark/src/main/scala/org/apache/comet/CometConf.scala: ########## @@ -442,6 +442,31 @@ 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) Review Comment: Mkae sense. (Didnt really mean to enable it , missed reverting) ########## 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: added [here](https://github.com/apache/datafusion-comet/pull/4519/changes#diff-6ba61acc897639ecc2e2c074bdb4060bfd844a2d81287508f3d8244735f634a8R154) ########## spark/src/main/scala/org/apache/comet/rules/RevertNativeForTransitionHeavyStages.scala: ########## @@ -0,0 +1,143 @@ +/* + * 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.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 = { + val withRevertedStages = plan.transformUp { case exchange: ShuffleExchangeLike => + revertStageIfNeeded(exchange.child, exchange.supportsColumnar) + .map(reverted => exchange.withNewChildren(Seq(reverted))) + .getOrElse(exchange) + } + revertStageIfNeeded(withRevertedStages, outputColumnar = false) + .getOrElse(withRevertedStages) + } + + /** + * 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 Review Comment: Done -- 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]
