dongjoon-hyun commented on code in PR #60538:
URL: https://github.com/apache/spark/pull/60538#discussion_r4581322699


##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(

Review Comment:
   This case doesn't exercise the new `plan.subqueries` traversal in 
`allPlanNodes`. `RewritePredicateSubquery` turns `k1 IN (SELECT ...)` into a 
left semi join, so no IN subquery is left at execution time, and the target 
`Project` is always satisfied by the main plan (e.g. the `Project` of `l`). The 
case would still pass if the subquery traversal broke or the scalar subquery 
stage went away.
   
   How about targeting a node that only exists in the subquery, e.g. the 
`HashAggregate` of `max(v2)`? Also, we could either drop "IN" from the case 
name or use a query that actually keeps an `InSubqueryExec`.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),
+          () => spark.table("p").where($"v1" > 3).groupBy("k1").count(), 
Set("Filter")),
+        ("cached table scan", Nil, () => 
spark.table("c").groupBy("k1").count(),
+          Set("HashAggregate", "Range")),
+        ("merge rows", Nil, () => {
+          val source = l.selectExpr("CAST(v1 AS INT) AS t", "CAST(k1 AS INT) 
AS s")
+          val attrs = source.queryExecution.analyzed.output
+          classic.Dataset.ofRows(spark, MergeRows(
+            isSourceRowPresent = Literal.TrueLiteral,
+            isTargetRowPresent = Literal.TrueLiteral,
+            matchedInstructions = Seq(Keep(Update, Literal.TrueLiteral, 
attrs)),
+            notMatchedInstructions = Nil,
+            notMatchedBySourceInstructions = Nil,
+            checkCardinality = false,
+            output = attrs.map(_.newInstance()),
+            child = source.queryExecution.analyzed))
+        }, Set("MergeRows")))
+      aggs ++ smj ++ shj ++ bhj ++ bnlj ++ rangeJoin ++ asOfJoin ++ others
+    }
+
+    withTempPath { dir =>
+      withTempView("l", "r", "p", "c") {
+        spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), $"id".as("v1"))
+          .createOrReplaceTempView("l")
+        spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), $"id".as("v2"))
+          .createOrReplaceTempView("r")
+        spark.table("l").write.parquet(dir.getCanonicalPath)
+        spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("p")
+        // Not the plan of `l`, which the other queries would then read from 
the cache.
+        val cached =
+          spark.range(0, 50, 1, 2).select(($"id" % 10).as("k1"), 
$"id".as("v1")).cache()
+        cached.createOrReplaceTempView("c")
+        try {
+          for {
+            (name, confs, query, expectedNodes) <- cases
+            aqe <- Seq(false, true)
+            usePartitionEvaluator <- Seq(false, true)
+          } {
+            withSQLConf(confs ++ Seq(
+                SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+                SQLConf.USE_PARTITION_EVALUATOR.key -> 
usePartitionEvaluator.toString): _*) {
+              val clue = s"$name, aqe=$aqe, 
usePartitionEvaluator=$usePartitionEvaluator"
+              val df = query()
+              df.collect()
+              // The RDDs are cached by the plans, so these are the ones the 
query ran.
+              val plan = df.queryExecution.executedPlan
+              val stages = allPlanNodes(plan).collect { case s: 
WholeStageCodegenExec => s }
+              val generated = stages.flatMap(s => 
generatedNodes(s.child)).map(_.nodeName)
+              expectedNodes.foreach { expected =>
+                assert(generated.exists(_.startsWith(expected)),

Review Comment:
   With `startsWith`, `Sort` also matches `SortMergeJoin`, `SortAggregate` and 
`SortMergeAsOfJoin`. So the `Sort` target of the sort merge join cases 
(`Set("Sort", "SortMergeJoin")`) is always satisfied by the join itself, even 
if the `SortExec` below it leaves codegen.
   
   If the prefix match is only for the `(skew=true)` suffix, could we compare 
exactly, e.g. `generated.exists(_.stripSuffix("(skew=true)") == expected)`?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),

Review Comment:
   `ENABLE_TWOLEVEL_AGG_MAP` defaults to `true` and 
`ENABLE_VECTORIZED_HASH_MAP` defaults to `false`. So this case has the same 
configs as `hash aggregate, row-based fast hash map` below, and no case in this 
test runs a partial hash aggregate without a fast hash map.
   
   To cover "with and without fast hash maps" as the PR description says, how 
about `Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "false")` here?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),
+          () => spark.table("p").where($"v1" > 3).groupBy("k1").count(), 
Set("Filter")),
+        ("cached table scan", Nil, () => 
spark.table("c").groupBy("k1").count(),
+          Set("HashAggregate", "Range")),
+        ("merge rows", Nil, () => {
+          val source = l.selectExpr("CAST(v1 AS INT) AS t", "CAST(k1 AS INT) 
AS s")
+          val attrs = source.queryExecution.analyzed.output
+          classic.Dataset.ofRows(spark, MergeRows(
+            isSourceRowPresent = Literal.TrueLiteral,
+            isTargetRowPresent = Literal.TrueLiteral,
+            matchedInstructions = Seq(Keep(Update, Literal.TrueLiteral, 
attrs)),
+            notMatchedInstructions = Nil,
+            notMatchedBySourceInstructions = Nil,
+            checkCardinality = false,
+            output = attrs.map(_.newInstance()),
+            child = source.queryExecution.analyzed))
+        }, Set("MergeRows")))
+      aggs ++ smj ++ shj ++ bhj ++ bnlj ++ rangeJoin ++ asOfJoin ++ others
+    }
+
+    withTempPath { dir =>
+      withTempView("l", "r", "p", "c") {
+        spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), $"id".as("v1"))
+          .createOrReplaceTempView("l")
+        spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), $"id".as("v2"))
+          .createOrReplaceTempView("r")
+        spark.table("l").write.parquet(dir.getCanonicalPath)
+        spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("p")
+        // Not the plan of `l`, which the other queries would then read from 
the cache.
+        val cached =

Review Comment:
   `cached` is planned once here. Its codegen stage is executed, and its RDD 
memoized, by the first iteration of the `cached table scan` case, which has 
`aqe=false` and `usePartitionEvaluator=false`. The later iterations only 
re-check that same RDD through `InMemoryTableScanExec.relation.cachedPlan`, so 
the stage of the cached plan is never built with `usePartitionEvaluator=true`.
   
   Could we cache and unpersist within each configuration instead?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),
+          () => spark.table("p").where($"v1" > 3).groupBy("k1").count(), 
Set("Filter")),
+        ("cached table scan", Nil, () => 
spark.table("c").groupBy("k1").count(),
+          Set("HashAggregate", "Range")),
+        ("merge rows", Nil, () => {
+          val source = l.selectExpr("CAST(v1 AS INT) AS t", "CAST(k1 AS INT) 
AS s")
+          val attrs = source.queryExecution.analyzed.output
+          classic.Dataset.ofRows(spark, MergeRows(
+            isSourceRowPresent = Literal.TrueLiteral,
+            isTargetRowPresent = Literal.TrueLiteral,
+            matchedInstructions = Seq(Keep(Update, Literal.TrueLiteral, 
attrs)),
+            notMatchedInstructions = Nil,
+            notMatchedBySourceInstructions = Nil,
+            checkCardinality = false,
+            output = attrs.map(_.newInstance()),
+            child = source.queryExecution.analyzed))
+        }, Set("MergeRows")))
+      aggs ++ smj ++ shj ++ bhj ++ bnlj ++ rangeJoin ++ asOfJoin ++ others
+    }
+
+    withTempPath { dir =>
+      withTempView("l", "r", "p", "c") {
+        spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), $"id".as("v1"))
+          .createOrReplaceTempView("l")
+        spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), $"id".as("v2"))
+          .createOrReplaceTempView("r")
+        spark.table("l").write.parquet(dir.getCanonicalPath)
+        spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("p")
+        // Not the plan of `l`, which the other queries would then read from 
the cache.
+        val cached =
+          spark.range(0, 50, 1, 2).select(($"id" % 10).as("k1"), 
$"id".as("v1")).cache()
+        cached.createOrReplaceTempView("c")
+        try {
+          for {
+            (name, confs, query, expectedNodes) <- cases
+            aqe <- Seq(false, true)

Review Comment:
   The plans of the `sample`, `generate`, `objects` and `merge rows` cases have 
no exchange, no required child distribution and no subquery. So 
`InsertAdaptiveSparkPlan.shouldApplyAQE` returns false, and `aqe=true` only 
re-checks the same non-adaptive plan.
   
   Could we also set `SQLConf.ADAPTIVE_EXECUTION_FORCE_APPLY.key -> "true"` 
when `aqe` is on, so that these cases actually run through 
`AdaptiveSparkPlanExec`?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),
+          () => spark.table("p").where($"v1" > 3).groupBy("k1").count(), 
Set("Filter")),
+        ("cached table scan", Nil, () => 
spark.table("c").groupBy("k1").count(),
+          Set("HashAggregate", "Range")),
+        ("merge rows", Nil, () => {
+          val source = l.selectExpr("CAST(v1 AS INT) AS t", "CAST(k1 AS INT) 
AS s")
+          val attrs = source.queryExecution.analyzed.output
+          classic.Dataset.ofRows(spark, MergeRows(

Review Comment:
   This `MergeRows` construction is almost the same as the one in `SPARK-60403: 
MergeRows compiles with its function spilled to a nested class`. Could we 
extract a small private helper, e.g. `mergeRows(source: DataFrame): DataFrame`, 
so that both tests are updated together when `MergeRows` changes?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),
+          () => spark.table("p").where($"v1" > 3).groupBy("k1").count(), 
Set("Filter")),
+        ("cached table scan", Nil, () => 
spark.table("c").groupBy("k1").count(),
+          Set("HashAggregate", "Range")),
+        ("merge rows", Nil, () => {
+          val source = l.selectExpr("CAST(v1 AS INT) AS t", "CAST(k1 AS INT) 
AS s")
+          val attrs = source.queryExecution.analyzed.output
+          classic.Dataset.ofRows(spark, MergeRows(
+            isSourceRowPresent = Literal.TrueLiteral,
+            isTargetRowPresent = Literal.TrueLiteral,
+            matchedInstructions = Seq(Keep(Update, Literal.TrueLiteral, 
attrs)),
+            notMatchedInstructions = Nil,
+            notMatchedBySourceInstructions = Nil,
+            checkCardinality = false,
+            output = attrs.map(_.newInstance()),
+            child = source.queryExecution.analyzed))
+        }, Set("MergeRows")))
+      aggs ++ smj ++ shj ++ bhj ++ bnlj ++ rangeJoin ++ asOfJoin ++ others
+    }
+
+    withTempPath { dir =>
+      withTempView("l", "r", "p", "c") {
+        spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), $"id".as("v1"))
+          .createOrReplaceTempView("l")
+        spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), $"id".as("v2"))
+          .createOrReplaceTempView("r")
+        spark.table("l").write.parquet(dir.getCanonicalPath)
+        spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("p")
+        // Not the plan of `l`, which the other queries would then read from 
the cache.
+        val cached =
+          spark.range(0, 50, 1, 2).select(($"id" % 10).as("k1"), 
$"id".as("v1")).cache()
+        cached.createOrReplaceTempView("c")
+        try {

Review Comment:
   This test runs 55 cases x 2 (AQE) x 2 (partition evaluator) = 220 queries 
one after another, and many of them overlap with the matrices of the 
SPARK-61661, SPARK-61666 and SPARK-61668 tests. Also, the first failure stops 
the whole test, which hides the results of the remaining cases.
   
   How about removing the redundant runs mentioned in the other comments, and 
splitting the cases with `gridTest` or one `test` per case?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,
+          () => l.select($"k1", 
rank().over(Window.partitionBy("k1").orderBy("v1"))),
+          Set("Sort")),
+        ("limit", Nil, () => l.limit(5).groupBy("k1").count(), 
Set("GlobalLimit")),
+        ("sample", Nil, () => l.sample(0.5, 1L), Set("Sample")),
+        ("union", Nil, () => 
l.select("k1").union(r.select("k2")).groupBy("k1").count(),
+          Set("Union")),
+        ("objects", Nil, () => spark.range(10).as[Long].map(_ * 2).filter(_ > 
3).toDF(),
+          Set("MapElements")),
+        ("scalar and IN subqueries", noBroadcast, () => sql(
+          "SELECT k1, (SELECT max(v2) FROM r WHERE v2 < 5) FROM l " +
+            "WHERE k1 IN (SELECT k2 FROM r WHERE v2 > 3)"),
+          Set("Project")),
+        ("vectorized parquet scan", Nil, () => spark.table("p").where($"v1" > 
3)
+          .groupBy("k1").count(), Set("ColumnarToRow")),
+        ("row-based parquet scan", 
Seq(SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false"),

Review Comment:
   `FileSourceScanExec` is not a `CodegenSupport`, so the row-based scan stays 
outside codegen, under an `InputAdapter`. The target `Filter` is also in the 
vectorized case above, so this case adds no coverage, and it would still pass 
if the vectorized reader were not actually disabled (i.e. `ColumnarToRow` still 
in the plan).
   
   Could we assert that the plan has no `ColumnarToRow`, or drop this case?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {

Review Comment:
   (Non-blocking) This guard only covers the operators and combinations listed 
here, for example not `LocalTableScan`, `RDDScan` or DSv2 `BatchScan`. A new 
`CodegenSupport` operator that adds `ctx.addReferenceObj("plan", this)` would 
still pass unless someone also adds a case here. It might be worth considering 
a check under `Utils.isTesting` that the references of a 
`WholeStageCodegenExec` contain no `SparkPlan`, so that the whole test suite 
catches this regression.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -904,6 +907,179 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61761: Whole-stage codegen stages do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage adds on top of its input RDDs is 
serialized into every task
+    // binary, so it must not hold a plan node (see `serializedPlanNodes`). 
This checks every
+    // codegen stage of queries that cover the operators that generate code, 
through adaptive query
+    // stages and subqueries.
+    val noBroadcast = Seq(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1")
+    val forceShj = noBroadcast :+ ("spark.sql.join.forceApplyShuffledHashJoin" 
-> "true")
+    val sortAgg =
+      Seq(SQLConf.USE_HASH_AGG.key -> "false", SQLConf.USE_OBJECT_HASH_AGG.key 
-> "false")
+    // (name, configs, the query, the names of nodes that must be generated, 
by prefix)
+    def cases: Seq[(String, Seq[(String, String)], () => DataFrame, 
Set[String])] = {
+      def l = spark.table("l")
+      def r = spark.table("r")
+      def join(strategy: String, joinType: String, buildLeft: Boolean = 
false): () => DataFrame =
+        () => {
+          val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+          if (buildLeft) l.hint(strategy).join(r, cond, joinType)
+          else l.join(r.hint(strategy), cond, joinType)
+        }
+      val existenceJoin = "SELECT * FROM l WHERE EXISTS (SELECT 1 FROM r WHERE 
k2 = k1) OR v1 < 3"
+      val aggs = Seq(
+        ("hash aggregate", Nil, () => l.groupBy("k1").agg(sum("v1"), 
avg("v1")),
+          Set("HashAggregate")),
+        ("hash aggregate, row-based fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "false"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, vectorized fast hash map",
+          Seq(SQLConf.ENABLE_TWOLEVEL_AGG_MAP.key -> "true",
+            SQLConf.ENABLE_VECTORIZED_HASH_MAP.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate, adaptive partial aggregation",
+          Seq(SQLConf.ADAPTIVE_PARTIAL_AGGREGATION_ENABLED.key -> "true"),
+          () => l.groupBy("k1").agg(sum("v1")), Set("HashAggregate")),
+        ("hash aggregate without grouping keys", Nil, () => l.agg(sum("v1"), 
max("k1")),
+          Set("HashAggregate")),
+        ("distinct aggregate", Nil, () => 
l.groupBy("k1").agg(countDistinct("v1"), sum("v1")),
+          Set("HashAggregate")),
+        ("aggregate with a filter", Nil,
+          () => sql("SELECT k1, sum(v1) FILTER (WHERE v1 > 10) FROM l GROUP BY 
k1"),
+          Set("HashAggregate")),
+        ("sort aggregate", sortAgg, () => l.groupBy("k1").agg(sum("v1"), 
max("v1")),
+          Set("SortAggregate")),
+        ("sort aggregate without grouping keys", sortAgg, () => 
l.agg(sum("v1"), max("v1")),
+          Set("SortAggregate")))
+      val joinTypes =
+        Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi", 
"left_anti")
+      val smj = joinTypes.map { joinType =>
+        (s"sort merge join, $joinType", noBroadcast, join("SHUFFLE_MERGE", 
joinType),
+          Set("Sort", "SortMergeJoin"))
+      } :+ ("sort merge join, existence", noBroadcast, () => 
sql(existenceJoin),
+        Set("SortMergeJoin"))
+      val shj = joinTypes.flatMap { joinType =>
+        Seq(false, true).filter(buildLeft => joinType match {
+          case "left_semi" | "left_anti" => !buildLeft
+          case _ => true
+        }).map { buildLeft =>
+          (s"shuffled hash join, $joinType, build ${if (buildLeft) "left" else 
"right"}",
+            noBroadcast, join("SHUFFLE_HASH", joinType, buildLeft), 
Set("ShuffledHashJoin"))
+        }
+      } :+ ("shuffled hash join, existence", forceShj, () => 
sql(existenceJoin),
+        Set("ShuffledHashJoin"))
+      val bhj = Seq(("inner", false), ("inner", true), ("left_outer", false),
+          ("right_outer", true), ("left_semi", false), ("left_anti", 
false)).map {
+        case (joinType, buildLeft) =>
+          (s"broadcast hash join, $joinType, build ${if (buildLeft) "left" 
else "right"}",
+            noBroadcast, join("BROADCAST", joinType, buildLeft), 
Set("BroadcastHashJoin"))
+      } :+ ("broadcast hash join, existence", Nil, () => sql(existenceJoin),
+        Set("BroadcastHashJoin"))
+      val bnlj = Seq("inner", "left_outer", "left_semi", "left_anti").map { 
joinType =>
+        (s"broadcast nested loop join, $joinType", noBroadcast,
+          () => l.join(broadcast(r), $"k1" < $"k2" || $"v1" === $"v2", 
joinType),
+          Set("BroadcastNestedLoopJoin"))
+      }
+      val rangeJoin = Seq("inner", "left_outer", "left_semi").map { joinType =>
+        (s"broadcast range join, $joinType",
+          noBroadcast :+ (SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true"),
+          () => l.join(broadcast(r), $"v1" >= $"k2" && $"v1" <= $"v2", 
joinType),
+          Set("BroadcastRangeJoin"))
+      }
+      val asOfJoin = Seq(("as-of join", noBroadcast :+
+          (SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true"),
+        () => {
+          val right = r.withColumnRenamed("k2", "k1")
+          l.joinAsOf(right, l("v1"), right("v2"), usingColumns = Seq("k1"), 
joinType = "inner",
+            tolerance = null, allowExactMatches = true, direction = "backward")
+        },
+        Set("SortMergeAsOfJoin")))
+      val others = Seq(
+        ("sort", Nil, () => l.orderBy($"v1".desc), Set("Sort")),
+        ("expand", Nil, () => l.rollup("k1").agg(sum("v1")), Set("Expand")),
+        ("generate", Nil, () => l.select($"k1", explode(array($"v1", $"v1" + 
1))),
+          Set("Generate")),
+        ("window", Nil,

Review Comment:
   `WindowExec` doesn't support whole-stage codegen, so this case only checks 
the `SortExec` below it, which the `sort` case already covers. Should we drop 
this case, or take "window" out of the list of operators that generate code in 
the PR description?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -827,16 +836,10 @@ class WholeStageCodegenSuite extends SharedSparkSession
           checkAnswer(result, expected)
           // The RDDs are cached by the plans, so these are the ones the query 
ran.
           val plan = result.queryExecution.executedPlan
-          // All the nodes of the plan, including those in adaptive query 
stages.
-          def allNodes(p: SparkPlan): Seq[SparkPlan] = p +: (p match {
-            case a: AdaptiveSparkPlanExec => allNodes(a.executedPlan)
-            case q: QueryStageExec => allNodes(q.plan)
-            case other => other.children.flatMap(allNodes)
-          })
-          val nodes = allNodes(plan)
+          val nodes = allPlanNodes(plan)

Review Comment:
   The PR description says the helpers are moved, but the shared `allPlanNodes` 
also walks subqueries and cached plans, which the previous local `allNodes` did 
not. As a result, `checkPlans` can now satisfy `expectedNodes` with nodes in a 
subquery or a cached plan, and call `execute()` on interpreted nodes there. It 
makes no difference for the current queries, but could you mention this 
behavior change in the PR description?



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