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

dongjoon-hyun pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 4b29b6f90e21 [SPARK-61574][SQL] Fix file scan failures when a scan 
copied by subquery reuse re-decides columnar output at execution
4b29b6f90e21 is described below

commit 4b29b6f90e215b1c31dc2a788fa200b22600834a
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Thu Nov 12 19:45:45 2026 -0800

    [SPARK-61574][SQL] Fix file scan failures when a scan copied by subquery 
reuse re-decides columnar output at execution
    
    ### What changes were proposed in this pull request?
    
    This PR aims to fix `FileSourceScanExec` to keep its columnar decision on a 
copy of the node.
    
    `supportsColumnar` now records its decision in a `TreeNodeTag` and reads it 
back when the tag is present. Since `makeCopy` and the tree transforms carry 
tags over to a new node, a copy keeps the decision that the columnar 
transitions around it were planned against, instead of deciding again from the 
conf at the time it is first asked. This is the same mechanism `UnionExec` uses 
to keep its decisions across copies (SPARK-59122, #58419).
    
    ### Why are the changes needed?
    
    `FileSourceScanExec.supportsColumnar` is a `lazy val` that reads the live 
session conf (`spark.sql.codegen.wholeStage`, `spark.sql.codegen.maxFields`, 
and the format's `supportBatch`). Without AQE, `ReuseExchangeAndSubquery` runs 
after `ApplyColumnarRulesAndInsertTransitions`, and when it rewrites a subquery 
of a scan, the scan is rebuilt by `makeCopy`. For example,
    - the dynamic pruning subquery of a fact table scan reuses the broadcast 
exchange of the join when the build side comes first (`BuildLeft`).
    - the second of two identical scalar subqueries becomes a 
`ReusedSubqueryExec`.
    
    The copy has a fresh `lazy val`, so it decides when it is first asked, 
which is at execution if nothing reads it before. If the conf changed between 
planning and execution, the copy disagrees with the `ColumnarToRowExec` planned 
above it, and the query fails.
    
    Before SPARK-52484 (#51183), the constructor assertion of 
`ColumnarToRowExec` read `child.supportsColumnar` when 
`ReuseExchangeAndSubquery` rebuilt it, which fixed the decision of the copy 
during the preparation. Since 
[v4.1.0](https://github.com/apache/spark/releases/tag/v4.1.0) (2025-12-11), the 
copy decides on its own. `Dataset.explain()` hides the issue because the scan 
metadata (`Batched`) reads the decision.
    
    ```scala
    spark.conf.set("spark.sql.adaptive.enabled", "false")
    spark.range(100).selectExpr("id", "id % 10 AS 
part").write.partitionBy("part").saveAsTable("fact")
    spark.range(10).selectExpr("id AS part", "CAST(id AS STRING) AS 
name").write.saveAsTable("dim")
    val df = spark.sql("SELECT /*+ BROADCAST(d) */ f.id FROM dim d JOIN fact f 
ON d.part = f.part WHERE d.name = '3'")
    df.queryExecution.executedPlan
    spark.conf.set("spark.sql.codegen.wholeStage", "false")
    df.collect()
    ```
    
    - [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) 
(2026-10-21): `Array(3, 13, ..., 93)`
    - [v4.1.4](https://github.com/apache/spark/releases/tag/v4.1.4) 
(2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) 
(2026-10-27): `java.util.NoSuchElementException: key not found: scanTime`
    
    The same happens with `Dataset.debug()`. In the opposite direction (planned 
with `spark.sql.codegen.wholeStage=false`, executed with `true`), the task 
fails with `ClassCastException: ColumnarBatch cannot be cast to InternalRow`. 
In the `master` branch, `Dataset.cache()` followed by a conf change and an 
action hits it too, since SPARK-59024 (#58314) made the name of the cached RDD 
lazy, which used to read the string of the cached plan at `cache()`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, the query above fails before this PR and returns the correct result 
after this PR.
    
    ### How was this patch tested?
    
    Pass the CIs with the newly added test case.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60418 from dongjoon-hyun/SPARK-61574.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    (cherry picked from commit e07a39708f5ca79d167904f8f22c9669c0d584fd)
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    
    skip-checks: true
---
 .../spark/sql/execution/DataSourceScanExec.scala   | 30 +++++++++++-----
 .../execution/ReuseExchangeAndSubquerySuite.scala  | 40 ++++++++++++++++++++++
 2 files changed, 62 insertions(+), 8 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala
index d26f8190f438..e510f4f18824 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/DataSourceScanExec.scala
@@ -29,6 +29,7 @@ import org.apache.spark.sql.catalyst.catalog.BucketSpec
 import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.plans.QueryPlan
 import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, 
Partitioning, SinglePartition, UnknownPartitioning}
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
 import org.apache.spark.sql.catalyst.util.{truncatedString, CaseInsensitiveMap}
 import org.apache.spark.sql.connector.read.streaming.SparkDataStream
 import org.apache.spark.sql.errors.QueryExecutionErrors
@@ -743,14 +744,22 @@ case class FileSourceScanExec(
 
   // Note that some vals referring the file-based relation are lazy 
intentionally
   // so that this plan can be canonicalized on executor side too. See 
SPARK-23731.
-  override lazy val supportsColumnar: Boolean = {
-    val conf = getSqlConf(relation.sparkSession)
-    // Only output columnar if there is WSCG to read it.
-    val requiredWholeStageCodegenSettings =
-      conf.wholeStageEnabled && !WholeStageCodegenExec.isTooManyFields(conf, 
schema)
-    requiredWholeStageCodegenSettings &&
-      relation.fileFormat.supportBatch(relation.sparkSession, schema)
-  }
+  //
+  // The decision is also kept in a tag, which a copy of this node takes over. 
The transitions
+  // around this node are planned against it, and a copy made after them, such 
as the one
+  // `ReuseExchangeAndSubquery` makes when it rewrites a dynamic pruning 
filter, would otherwise
+  // decide again from the conf at the time it is first asked.
+  override lazy val supportsColumnar: Boolean =
+    getTagValue(FileSourceScanExec.SUPPORTS_COLUMNAR).getOrElse {
+      val conf = getSqlConf(relation.sparkSession)
+      // Only output columnar if there is WSCG to read it.
+      val requiredWholeStageCodegenSettings =
+        conf.wholeStageEnabled && !WholeStageCodegenExec.isTooManyFields(conf, 
schema)
+      val decision = requiredWholeStageCodegenSettings &&
+        relation.fileFormat.supportBatch(relation.sparkSession, schema)
+      setTagValue(FileSourceScanExec.SUPPORTS_COLUMNAR, decision)
+      decision
+    }
 
   private lazy val needsUnsafeRowConversion: Boolean = {
     if (relation.fileFormat.isInstanceOf[ParquetSource]) {
@@ -987,3 +996,8 @@ case class FileSourceScanExec(
 
   override def getStream: Option[SparkDataStream] = stream
 }
+
+object FileSourceScanExec {
+  /** The columnar decision of a [[FileSourceScanExec]]. See 
`supportsColumnar`. */
+  private val SUPPORTS_COLUMNAR = 
TreeNodeTag[Boolean]("fileSourceScanSupportsColumnar")
+}
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
index bec13f43f18b..e0740ba8b1f0 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/ReuseExchangeAndSubquerySuite.scala
@@ -182,4 +182,44 @@ class ReuseExchangeAndSubquerySuite extends 
SharedSparkSession with AdaptiveSpar
       }
     }
   }
+
+  test("SPARK-61574: A scan copied by ReuseExchangeAndSubquery keeps its 
columnar decision") {
+    withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+      withTable("df1", "df2") {
+        spark.range(100)
+          .select(col("id"), (col("id") % 10).as("k"))
+          .write
+          .partitionBy("k")
+          .format(tableFormat)
+          .saveAsTable("df1")
+
+        spark.range(10)
+          .select(col("id"), col("id").as("k"))
+          .write
+          .format(tableFormat)
+          .saveAsTable("df2")
+
+        // The broadcast side comes first, so the dynamic pruning subquery of 
the `df1` scan reuses
+        // its exchange, and the scan is copied after the columnar transitions 
are in place.
+        val df = sql(
+          """
+            |SELECT /*+ BROADCAST(df2) */ df1.id
+            |FROM df2 JOIN df1 ON df2.k = df1.k
+            |WHERE df2.id = 3
+            |""".stripMargin)
+
+        val copiedScans = df.queryExecution.executedPlan.collect {
+          case s: FileSourceScanExec if s.partitionFilters.exists(_.exists {
+            case e: ExecSubqueryExpression => 
e.plan.exists(_.isInstanceOf[ReusedExchangeExec])
+            case _ => false
+          }) => s
+        }
+        assert(copiedScans.size == 1)
+
+        withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false") {
+          assert(df.collect().map(_.getLong(0)).sorted.toSeq === (3L until 
100L by 10))
+        }
+      }
+    }
+  }
 }


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

Reply via email to