This is an automated email from the ASF dual-hosted git repository.

philo-he pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git


The following commit(s) were added to refs/heads/main by this push:
     new b86f0cb061 [CORE] Skip unfinished AQE subqueries when checking for 
fallbacks (#13747)
b86f0cb061 is described below

commit b86f0cb06167e24de3218beac9a894d3a7756109
Author: Felix Loesing <[email protected]>
AuthorDate: Mon Nov 30 15:13:16 2026 -0800

    [CORE] Skip unfinished AQE subqueries when checking for fallbacks (#13747)
---
 .../spark/sql/execution/GlutenExplainUtils.scala   |  62 ++++++++-----
 .../execution/GlutenFailOnFallbackSuite.scala      | 100 ++++++++++++++++++++-
 2 files changed, 138 insertions(+), 24 deletions(-)

diff --git 
a/gluten-substrait/src/main/scala/org/apache/spark/sql/execution/GlutenExplainUtils.scala
 
b/gluten-substrait/src/main/scala/org/apache/spark/sql/execution/GlutenExplainUtils.scala
index 1151f4584a..5743a56182 100644
--- 
a/gluten-substrait/src/main/scala/org/apache/spark/sql/execution/GlutenExplainUtils.scala
+++ 
b/gluten-substrait/src/main/scala/org/apache/spark/sql/execution/GlutenExplainUtils.scala
@@ -119,16 +119,23 @@ object GlutenExplainUtils extends AdaptiveSparkPlanHelper 
{
    *     from physical or logical [[FallbackTags]], or a synthetic default 
when no tag is present
    *   - nodes ignored by [[shouldIgnoreInFallbackStats]]: no callback
    *
-   * Recurses into AQE subqueries and query stages, and into each visited 
operator's
-   * `innerChildren`. Subqueries reached purely via expressions on a vanilla 
Spark plan are not
-   * visited here; callers that need full subquery coverage should use 
[[processPlan]], which
-   * performs an explicit subquery walk.
+   * Recurses into finalized AQE subqueries and query stages, and into each 
visited operator's
+   * `innerChildren`. Unfinished AQE subqueries are skipped because their 
columnar rules have not
+   * run yet; their plans are checked when AQE prepares their stages. A 
subquery that never
+   * executes, e.g. one skipped because of a LIMIT, is therefore omitted from 
the fallback stats.
+   * Subqueries reached purely via expressions on a vanilla Spark plan are not 
visited here; callers
+   * that need full subquery coverage should use [[processPlan]], which 
performs an explicit
+   * subquery walk.
+   *
+   * Each node instance is visited at most once, even if it is reachable 
through multiple paths.
    */
   def visitFallbackNodes(
       plan: QueryPlan[_],
       onFallback: (SparkPlan, String) => Unit,
       onGluten: SparkPlan => Unit = _ => ()): Unit = {
 
+    val visited = newSetFromMap[AnyRef](new util.IdentityHashMap())
+
     def fallbackReason(p: SparkPlan): String =
       FallbackTags
         .getOption(p)
@@ -138,26 +145,35 @@ object GlutenExplainUtils extends AdaptiveSparkPlanHelper 
{
 
     def visit(tmp: QueryPlan[_]): Unit = {
       tmp.foreachUp {
-        case cmd: CommandResultExec => visit(cmd.commandPhysicalPlan)
-        case p: V2CommandExec
-            if !shouldIgnoreInFallbackStats(p) =>
-          onFallback(p, fallbackReason(p))
-        case sub: AdaptiveSparkPlanExec if sub.isSubquery => 
visit(sub.executedPlan)
-        case p: QueryStageExec => visit(p.plan)
-        case i: InMemoryTableScanExec =>
-          if (PlanUtil.isGlutenTableCache(i)) {
-            onGluten(i)
-          } else {
-            onFallback(i, "Columnar table cache is disabled")
+        node =>
+          if (visited.add(node.asInstanceOf[AnyRef])) {
+            node match {
+              case cmd: CommandResultExec => visit(cmd.commandPhysicalPlan)
+              case p: V2CommandExec
+                  if !shouldIgnoreInFallbackStats(p) =>
+                onFallback(p, fallbackReason(p))
+              // AQE is a leaf, so foreachUp cannot enter its plan before this 
guard.
+              case sub: AdaptiveSparkPlanExec if sub.isSubquery && 
sub.isFinalPlan =>
+                visit(sub.executedPlan)
+              case reused: ReusedSubqueryExec => visit(reused.child)
+              case p: QueryStageExec => visit(p.plan)
+              case i: InMemoryTableScanExec =>
+                if (PlanUtil.isGlutenTableCache(i)) {
+                  onGluten(i)
+                } else {
+                  onFallback(i, "Columnar table cache is disabled")
+                }
+              case p: SparkPlan if shouldIgnoreInFallbackStats(p) => // Ignore
+              case p: GlutenPlan =>
+                onGluten(p)
+                p.innerChildren.foreach(visit)
+              case _: SubqueryExec =>
+              case p: SparkPlan =>
+                onFallback(p, fallbackReason(p))
+                p.innerChildren.foreach(visit)
+              case _ =>
+            }
           }
-        case p: SparkPlan if shouldIgnoreInFallbackStats(p) => // Ignore
-        case p: GlutenPlan =>
-          onGluten(p)
-          p.innerChildren.foreach(visit)
-        case p: SparkPlan =>
-          onFallback(p, fallbackReason(p))
-          p.innerChildren.foreach(visit)
-        case _ =>
       }
     }
     visit(plan)
diff --git 
a/gluten-ut/test/src/test/scala/org/apache/gluten/execution/GlutenFailOnFallbackSuite.scala
 
b/gluten-ut/test/src/test/scala/org/apache/gluten/execution/GlutenFailOnFallbackSuite.scala
index 02f118b4d2..d71aec2a3f 100644
--- 
a/gluten-ut/test/src/test/scala/org/apache/gluten/execution/GlutenFailOnFallbackSuite.scala
+++ 
b/gluten-ut/test/src/test/scala/org/apache/gluten/execution/GlutenFailOnFallbackSuite.scala
@@ -22,7 +22,7 @@ import org.apache.gluten.extension.columnar.FallbackTags
 import org.apache.gluten.utils.BackendTestUtils
 
 import org.apache.spark.SparkConf
-import org.apache.spark.sql.DataFrame
+import org.apache.spark.sql.{DataFrame, Row}
 import org.apache.spark.sql.execution.FileSourceScanExec
 import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
 import org.apache.spark.sql.internal.SQLConf
@@ -37,6 +37,7 @@ class GlutenFailOnFallbackSuite extends 
WholeStageTransformerSuite {
 
   override protected def sparkConf: SparkConf = {
     val conf = super.sparkConf
+      .set("spark.shuffle.manager", 
"org.apache.spark.shuffle.sort.ColumnarShuffleManager")
     if (BackendTestUtils.isCHBackendLoaded()) {
       conf.set(GlutenConfig.NATIVE_VALIDATION_ENABLED.key, "false")
     }
@@ -109,6 +110,27 @@ class GlutenFailOnFallbackSuite extends 
WholeStageTransformerSuite {
       }
   }
 
+  private def withScalarSubqueryTable(f: => Unit): Unit = {
+    import testImplicits._
+    withTable("scalar_subquery_t") {
+      Seq(
+        ("a", 1L, "1"),
+        ("a", 2L, "2"),
+        ("b", 3L, "2")
+      ).toDF("group_key", "value", "epoch")
+        .write
+        .format("parquet")
+        .saveAsTable("scalar_subquery_t")
+      f
+    }
+  }
+
+  private def findGlutenException(t: Throwable): Option[GlutenException] = t 
match {
+    case e: GlutenException => Some(e)
+    case _ if t.getCause != null => findGlutenException(t.getCause)
+    case _ => None
+  }
+
   test("failOnFallback throws only when a fallback is present") {
     withTable("t") {
       spark.range(10).write.format("parquet").saveAsTable("t")
@@ -139,4 +161,80 @@ class GlutenFailOnFallbackSuite extends 
WholeStageTransformerSuite {
       }
     }
   }
+
+  test("failOnFallback allows supported AQE scalar subqueries") {
+    withScalarSubqueryTable {
+      withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        GlutenConfig.FALLBACK_FAIL_ON_FALLBACK.key -> "true") {
+        val filtered = sql(
+          """
+            |SELECT group_key, value
+            |FROM scalar_subquery_t
+            |WHERE epoch = (SELECT MAX(epoch) FROM scalar_subquery_t)
+            |ORDER BY group_key, value
+            |""".stripMargin)
+        assert(filtered.collect().toSeq == Seq(Row("a", 2L), Row("b", 3L)))
+
+        val grouped = sql(
+          """
+            |WITH max_value AS (
+            |  SELECT COALESCE(MAX(value), 0) AS value FROM scalar_subquery_t
+            |)
+            |SELECT group_key, scalar_value, AVG(value)
+            |FROM (
+            |  SELECT group_key, value, (SELECT value FROM max_value) AS 
scalar_value
+            |  FROM scalar_subquery_t
+            |)
+            |GROUP BY group_key, scalar_value
+            |ORDER BY group_key
+            |""".stripMargin)
+        assert(grouped.collect().toSeq == Seq(Row("a", 3L, 1.5), Row("b", 3L, 
3.0)))
+
+        Seq(filtered, grouped).foreach {
+          df =>
+            val subqueries = subqueriesAll(df.queryExecution.executedPlan)
+            assert(subqueries.nonEmpty, df.queryExecution)
+            assert(
+              subqueries.exists(
+                find(_)(_.isInstanceOf[BasicScanExecTransformer]).isDefined),
+              df.queryExecution)
+            assert(
+              subqueries.exists(
+                
find(_)(_.isInstanceOf[HashAggregateExecBaseTransformer]).isDefined),
+              df.queryExecution)
+        }
+      }
+    }
+  }
+
+  test("failOnFallback still rejects fallbacks inside AQE scalar subqueries") {
+    withScalarSubqueryTable {
+      Seq(
+        ("abs", "SELECT MAX(ABS(value)) FROM scalar_subquery_t"),
+        ("coalesce", "SELECT COALESCE(MAX(value), 0) FROM scalar_subquery_t")
+      ).foreach {
+        case (blacklistedExpression, subquery) =>
+          withSQLConf(
+            SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+            GlutenConfig.FALLBACK_FAIL_ON_FALLBACK.key -> "true",
+            GlutenConfig.ENABLE_COLUMNAR_PARTIAL_PROJECT.key -> "false",
+            GlutenConfig.EXPRESSION_BLACK_LIST.key -> blacklistedExpression
+          ) {
+            val thrown = intercept[Throwable] {
+              sql(s"SELECT value FROM scalar_subquery_t WHERE value = 
($subquery)").collect()
+            }
+            // Spark may wrap GlutenException when an asynchronous subquery 
fails.
+            val glutenException = findGlutenException(thrown).getOrElse {
+              fail(s"Expected GlutenException in cause chain, got: $thrown")
+            }
+            
assert(glutenException.getMessage.contains(GlutenConfig.FALLBACK_FAIL_ON_FALLBACK.key))
+            // Structural subquery wrappers must not be reported as fallback 
operators.
+            
assert(!glutenException.getMessage.split("\n").exists(_.trim.startsWith("Subquery:")))
+            assert(
+              
glutenException.getMessage.toLowerCase(Locale.ROOT).contains(blacklistedExpression))
+          }
+      }
+    }
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to