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

LuciferYang 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 0d6a143919 [GLUTEN-13713][CORE] Fix input_file_name() used through a 
projection over an offloaded scan (#13714)
0d6a143919 is described below

commit 0d6a143919e4b2fab60d0f36b4f20d0895149367
Author: YangJie <[email protected]>
AuthorDate: Fri Nov 27 02:20:45 2026 -0500

    [GLUTEN-13713][CORE] Fix input_file_name() used through a projection over 
an offloaded scan (#13714)
    
    ## What changes are proposed in this pull request?
    
    `PushDownInputFileExpression` gave wrong results for `input_file_name()` 
used through a projection over an offloaded scan (queries in the issue):
    
    - PreOffload rewrites a Project or Filter, and PostOffload folds a 
projection into a scan, only when it calls an input file function, not when it 
references a column named `input_file_name`.
    - PostOffload folds a projection into a file or Hive scan only when it 
lists nothing but columns and input file function calls, so a projection 
computing other columns is kept. The native scan maps a column to one output 
only, so a repeated column, or a function called at several levels, is read 
once and copied by a project above the scan.
    - For a DSv2 scan, PostOffload folds that projection into the scan too, 
instead of dropping the projection above it, which lost renames such as 
`input_file_name() AS f`. The scan keeps its own data columns, since Iceberg 
renames them for the native reader.
    
    Fixes #13713.
    
    ## How was this patch tested?
    
    Added tests, which check the scan is offloaded and, except where noted, 
compare results with vanilla Spark:
    
    - `FallbackSuite`: `input_file_name()` next to a Scala UDF and with project 
offload off. `input_file_name()` through a column of an earlier projection (in 
a Project, a Filter, a UNION ALL, and with an input file function called again 
above, including across a join), with DSv1 and DSv2 and project offload on and 
off, and on one or both sides of a cross join with DSv2. A projection that 
repeats a column over the scan, comparing only that column, because vanilla 
Spark returns an empty fi [...]
    - `GlutenHiveUDFSuite`: `input_file_name()` next to computed columns over a 
Hive table scan.
    - `IcebergSuite`: `input_file_name()` next to a column named `my/data`, 
including calls at two levels.
    
    All of them fail without the fix.
    
    ## Was this patch authored or co-authored using generative AI tooling?
    
    Yes. Generated-by: Claude Opus.
---
 .../apache/gluten/execution/FallbackSuite.scala    | 162 ++++++++++++++++++-
 .../spark/sql/execution/GlutenHiveUDFSuite.scala   |  26 ++-
 .../org/apache/gluten/execution/IcebergSuite.scala |  29 +++-
 .../columnar/PushDownInputFileExpression.scala     | 177 +++++++++++++++------
 4 files changed, 341 insertions(+), 53 deletions(-)

diff --git 
a/backends-velox/src/test/scala/org/apache/gluten/execution/FallbackSuite.scala 
b/backends-velox/src/test/scala/org/apache/gluten/execution/FallbackSuite.scala
index e1daac4aa7..3c8f9a76ee 100644
--- 
a/backends-velox/src/test/scala/org/apache/gluten/execution/FallbackSuite.scala
+++ 
b/backends-velox/src/test/scala/org/apache/gluten/execution/FallbackSuite.scala
@@ -20,13 +20,15 @@ import org.apache.gluten.config.{GlutenConfig, VeloxConfig}
 
 import org.apache.spark.SparkConf
 import org.apache.spark.sql.DataFrame
-import org.apache.spark.sql.execution.{ColumnarBroadcastExchangeExec, 
ColumnarShuffleExchangeExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.{ColumnarBroadcastExchangeExec, 
ColumnarShuffleExchangeExec, ProjectExec, SortExec, SparkPlan}
 import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, 
AQEShuffleReadExec}
 import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
 import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, 
BroadcastNestedLoopJoinExec, SortMergeJoinExec}
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.utils.GlutenSuiteUtils
 
+import java.util.Locale
+
 class FallbackSuite extends VeloxWholeStageTransformerSuite with 
AdaptiveSparkPlanHelper {
   protected val rootPath: String = getClass.getResource("/").getPath
   override protected val resourcePath: String = "/tpch-data-parquet"
@@ -655,4 +657,162 @@ class FallbackSuite extends 
VeloxWholeStageTransformerSuite with AdaptiveSparkPl
         }
     }
   }
+
+  test("input_file_name() next to an expression that stays on Spark") {
+    withUserDefinedFunction("upper_on_spark" -> true) {
+      spark.udf.register(
+        "upper_on_spark",
+        (s: String) => if (s == null) null else s.toUpperCase(Locale.ROOT))
+      withTempPath {
+        dir =>
+          import testImplicits._
+          Seq(("a", 1), ("b", 2)).toDF("name", 
"id").write.parquet(dir.getCanonicalPath)
+          withTempView("t") {
+            
spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("t")
+            // The Scala UDF, or a disabled project offload, keeps the project 
on Spark over the
+            // offloaded scan, which can't produce the project's computed 
columns.
+            Seq(
+              "true" -> "SELECT input_file_name() AS f, upper_on_spark(name) 
AS u FROM t",
+              "false" -> "SELECT input_file_name() AS f, name, id + 1 AS i 
FROM t",
+              "false" -> "SELECT concat(input_file_name(), name) AS f FROM t"
+            ).foreach {
+              case (projectEnabled, query) =>
+                withSQLConf(GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> 
projectEnabled) {
+                  runQueryAndCompare(query, noFallBack = false) {
+                    df =>
+                      val plan = df.queryExecution.executedPlan
+                      assert(hasNativeScan(df), plan)
+                      assert(find(plan)(_.isInstanceOf[ProjectExec]).nonEmpty, 
plan)
+                  }
+                }
+            }
+          }
+      }
+    }
+  }
+
+  // The project that gives the scan's repeated columns their values follows 
project offload.
+  private def assertNoNativeProjectIfDisabled(plan: SparkPlan, projectEnabled: 
String): Unit = {
+    if (projectEnabled == "false") {
+      assert(find(plan)(_.isInstanceOf[ProjectExecTransformer]).isEmpty, plan)
+    }
+  }
+
+  test("input_file_name() used through a column of an earlier projection") {
+    withTempPath {
+      dir =>
+        import testImplicits._
+        Seq(("a", 1), ("b", 2)).toDF("name", 
"id").write.parquet(dir.getCanonicalPath)
+        withTempView("t") {
+          // input_file_name() is nondeterministic, so Spark keeps both 
projections.
+          val queries = Seq(
+            "SELECT concat(f, name) AS g FROM (SELECT input_file_name() AS f, 
name FROM t)",
+            "SELECT concat(input_file_name, '#') AS g FROM " +
+              "(SELECT input_file_name() AS input_file_name, name FROM t)",
+            "SELECT concat(input_file_name, '#') AS g FROM " +
+              "(SELECT input_file_name() AS input_file_name, name FROM t) " +
+              "WHERE input_file_name LIKE '%.parquet'",
+            // Both projections call an input file function, another one or 
the same one.
+            "SELECT concat(input_file_name, input_file_block_length()) AS g 
FROM " +
+              "(SELECT input_file_name() AS input_file_name FROM t)",
+            "SELECT concat(input_file_name, input_file_name()) AS g FROM " +
+              "(SELECT input_file_name() AS input_file_name FROM t)",
+            "SELECT input_file_name() AS f, name FROM t WHERE 
input_file_name() LIKE '%.parquet'",
+            "SELECT concat(f, input_file_name()) AS g FROM (SELECT 
input_file_name() AS f " +
+              "FROM t UNION ALL SELECT input_file_name() AS f FROM t)",
+            "SELECT input_file_name() AS g, f FROM (SELECT input_file_name() 
AS f FROM t " +
+              "UNION ALL SELECT input_file_name() AS f FROM t) " +
+              "WHERE input_file_name() LIKE '%.parquet'",
+            "SELECT input_file_name() AS g, a.f FROM " +
+              "(SELECT input_file_name() AS f, id FROM t) a " +
+              "JOIN (VALUES (1), (2)) s(id) ON a.id = s.id"
+          )
+          for {
+            // Parquet read through DataSource V1 and V2.
+            v1Sources <- Seq(SQLConf.USE_V1_SOURCE_LIST.defaultValueString, "")
+            projectEnabled <- Seq("true", "false")
+            query <- queries
+          } {
+            withSQLConf(
+              SQLConf.USE_V1_SOURCE_LIST.key -> v1Sources,
+              GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> projectEnabled) {
+              
spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("t")
+              runQueryAndCompare(query, noFallBack = false) {
+                df =>
+                  val plan = df.queryExecution.executedPlan
+                  val nativeScan = find(plan) {
+                    case _: BatchScanExecTransformerBase => v1Sources.isEmpty
+                    case _: FileSourceScanExecTransformer => v1Sources.nonEmpty
+                    case _ => false
+                  }
+                  assert(nativeScan.nonEmpty, s"$v1Sources/$projectEnabled: 
$query\n$plan")
+                  assertNoNativeProjectIfDisabled(plan, projectEnabled)
+                  df.collect().foreach(row => 
assert(row.getString(0).contains(".parquet")))
+              }
+            }
+          }
+          // A project over the scan that repeats a column: the native scan 
reads the column once.
+          // Above a Sort, vanilla Spark returns an empty file name, so only 
the other columns are
+          // compared.
+          for {
+            v1Sources <- Seq(SQLConf.USE_V1_SOURCE_LIST.defaultValueString, "")
+            projectEnabled <- Seq("true", "false")
+          } {
+            withSQLConf(
+              SQLConf.USE_V1_SOURCE_LIST.key -> v1Sources,
+              GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> projectEnabled) {
+              
spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("t")
+              val df =
+                spark.sql(
+                  "SELECT input_file_name() AS g, a.* FROM (SELECT id, id FROM 
t SORT BY id) a")
+              val plan = df.queryExecution.executedPlan
+              
assert(find(plan)(_.isInstanceOf[BasicScanExecTransformer]).nonEmpty, plan)
+              assertNoNativeProjectIfDisabled(plan, projectEnabled)
+              val rows = df.collect()
+              assert(rows.map(r => (r.getInt(1), r.getInt(2))).sorted.toSeq 
=== Seq((1, 1), (2, 2)))
+            }
+          }
+          // A join in one stage with input_file_name() called on one or both 
sides. Spark rejects
+          // that over two DSv1 relations, so only DSv2 runs it.
+          val crossJoins = Seq(
+            "SELECT input_file_name() AS h, a.f, b.g FROM " +
+              "(SELECT input_file_name() AS f FROM t) a " +
+              "CROSS JOIN (SELECT input_file_name() AS g FROM t) b",
+            "SELECT input_file_name() AS h, a.f, b.g, b.id FROM " +
+              "(SELECT input_file_name() AS f FROM t) a CROSS JOIN " +
+              "(SELECT input_file_name() AS g, id FROM " +
+              "(SELECT id FROM t UNION ALL SELECT id FROM t)) b",
+            "SELECT input_file_name() AS h, a.id, b.g FROM t a " +
+              "CROSS JOIN (SELECT input_file_name() AS g FROM t2) b"
+          )
+          withTempPath {
+            dir2 =>
+              Seq(("c", 3)).toDF("name", 
"id").write.parquet(dir2.getCanonicalPath)
+              withTempView("t2") {
+                for {
+                  projectEnabled <- Seq("true", "false")
+                  query <- crossJoins
+                } {
+                  withSQLConf(
+                    SQLConf.USE_V1_SOURCE_LIST.key -> "",
+                    SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+                    GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> 
projectEnabled) {
+                    
spark.read.parquet(dir.getCanonicalPath).createOrReplaceTempView("t")
+                    
spark.read.parquet(dir2.getCanonicalPath).createOrReplaceTempView("t2")
+                    runQueryAndCompare(query, noFallBack = false) {
+                      df =>
+                        val plan = df.queryExecution.executedPlan
+                        assert(
+                          
find(plan)(_.isInstanceOf[BatchScanExecTransformerBase]).nonEmpty,
+                          plan)
+                        assertNoNativeProjectIfDisabled(plan, projectEnabled)
+                        df.collect().foreach(row => 
assert(row.getString(0).contains(".parquet")))
+                    }
+                  }
+                }
+              }
+          }
+        }
+    }
+  }
 }
diff --git 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenHiveUDFSuite.scala
 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenHiveUDFSuite.scala
index 9657d1033f..54bf0fd913 100644
--- 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenHiveUDFSuite.scala
+++ 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenHiveUDFSuite.scala
@@ -30,7 +30,7 @@ import 
org.apache.spark.sql.catalyst.expressions.CodegenObjectFactoryMode
 import org.apache.spark.sql.catalyst.optimizer.ConvertToLocalRelation
 import org.apache.spark.sql.classic.ClassicTypes._
 import org.apache.spark.sql.functions.udf
-import org.apache.spark.sql.hive.HiveUtils
+import org.apache.spark.sql.hive.{HiveTableScanExecTransformer, HiveUtils}
 import org.apache.spark.sql.internal.{SQLConf, StaticSQLConf}
 import org.apache.spark.sql.test.SQLTestUtils
 
@@ -465,4 +465,28 @@ class GlutenHiveUDFSuite extends GlutenQueryComparisonTest 
with SQLTestUtils {
       }
     }
   }
+
+  test("input_file_name() next to computed columns over a hive table scan") {
+    withTable("hive_input_file") {
+      withSQLConf(
+        HiveUtils.CONVERT_METASTORE_PARQUET.key -> "false",
+        GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> "false") {
+        sql("CREATE TABLE hive_input_file (name STRING, id INT) STORED AS 
PARQUET")
+        sql("INSERT INTO hive_input_file VALUES ('a', 1), ('b', 2)")
+        // The project stays on Spark, and the hive scan can't produce its 
computed columns.
+        // Only the file name is compared: the native scan returns the path as 
file:///...
+        Seq(
+          "SELECT substring_index(input_file_name(), '/', -1) AS f, name, id + 
1 AS i " +
+            "FROM hive_input_file",
+          "SELECT concat(substring_index(input_file_name(), '/', -1), name) AS 
f " +
+            "FROM hive_input_file"
+        ).foreach {
+          query =>
+            runQueryAndCompare(query, noFallBack = false) {
+              checkOperatorMatch[HiveTableScanExecTransformer]
+            }
+        }
+      }
+    }
+  }
 }
diff --git 
a/gluten-iceberg/src/test/scala/org/apache/gluten/execution/IcebergSuite.scala 
b/gluten-iceberg/src/test/scala/org/apache/gluten/execution/IcebergSuite.scala
index d69e2229a0..082816b9ce 100644
--- 
a/gluten-iceberg/src/test/scala/org/apache/gluten/execution/IcebergSuite.scala
+++ 
b/gluten-iceberg/src/test/scala/org/apache/gluten/execution/IcebergSuite.scala
@@ -16,7 +16,7 @@
  */
 package org.apache.gluten.execution
 
-import org.apache.gluten.config.GlutenIcebergConfig
+import org.apache.gluten.config.{GlutenConfig, GlutenIcebergConfig}
 
 import org.apache.spark.SparkConf
 import org.apache.spark.sql.Row
@@ -896,4 +896,31 @@ abstract class IcebergSuite extends 
WholeStageTransformerSuite {
       }
     }
   }
+
+  test("iceberg input_file_name with special characters in column name") {
+    withTable("iceberg_input_file_special") {
+      spark.sql("""
+                  |CREATE TABLE iceberg_input_file_special (id INT, `my/data` 
STRING)
+                  |USING iceberg
+                  |""".stripMargin)
+      spark.sql("INSERT INTO iceberg_input_file_special VALUES (1, 'a'), (2, 
'b')")
+      for {
+        projectEnabled <- Seq("true", "false")
+        query <- Seq(
+          "SELECT input_file_name() AS f, `my/data` FROM 
iceberg_input_file_special",
+          "SELECT `my/data` FROM iceberg_input_file_special " +
+            "WHERE input_file_name() LIKE '%.parquet'",
+          // input_file_name() at two levels: the scan outputs one 
input_file_name column.
+          "SELECT input_file_name() AS f, `my/data` FROM 
iceberg_input_file_special " +
+            "WHERE input_file_name() LIKE '%.parquet'",
+          "SELECT concat(f, input_file_name()) AS g, `my/data` FROM " +
+            "(SELECT input_file_name() AS f, `my/data` FROM 
iceberg_input_file_special)"
+        )
+      } {
+        withSQLConf(GlutenConfig.COLUMNAR_PROJECT_ENABLED.key -> 
projectEnabled) {
+          checkGlutenPlan[IcebergScanTransformer](runAndCompare(query))
+        }
+      }
+    }
+  }
 }
diff --git 
a/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/PushDownInputFileExpression.scala
 
b/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/PushDownInputFileExpression.scala
index 5ad5b9fcc4..40c63eb664 100644
--- 
a/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/PushDownInputFileExpression.scala
+++ 
b/gluten-substrait/src/main/scala/org/apache/gluten/extension/columnar/PushDownInputFileExpression.scala
@@ -16,17 +16,18 @@
  */
 package org.apache.gluten.extension.columnar
 
+import org.apache.gluten.backendsapi.BackendsApiManager
+import org.apache.gluten.config.GlutenConfig
 import org.apache.gluten.execution.{BatchScanExecTransformerBase, 
FileSourceScanExecTransformer, ProjectExecTransformer}
 import org.apache.gluten.expression.ConverterUtils
 
-import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, Expression, InputFileBlockLength, InputFileBlockStart, 
InputFileName, NamedExpression}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, Expression, ExprId, InputFileBlockLength, 
InputFileBlockStart, InputFileName, NamedExpression}
 import org.apache.spark.sql.catalyst.optimizer.CollapseProjectShim
 import org.apache.spark.sql.catalyst.rules.Rule
 import org.apache.spark.sql.catalyst.trees.TreeNodeTag
 import org.apache.spark.sql.execution.{DeserializeToObjectExec, 
FileSourceScanExec, FilterExec, LeafExecNode, ProjectExec, 
SerializeFromObjectExec, SparkPlan, UnionExec}
 import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
 import org.apache.spark.sql.hive.HiveTableScanExecTransformer
-import org.apache.spark.sql.internal.SQLConf
 
 import scala.collection.mutable
 
@@ -58,16 +59,6 @@ object PushDownInputFileExpression {
   val INPUT_FILE_NAME_COLLISION_TAG: TreeNodeTag[Boolean] =
     TreeNodeTag[Boolean]("org.apache.gluten.InputFileNameCollisionTag")
 
-  private val INPUT_FILE_ATTR_NAMES =
-    Set("input_file_name", "input_file_block_start", "input_file_block_length")
-
-  /**
-   * Whether `name` is the name of an attribute injected for an input file 
function, following
-   * Spark's configured (case-sensitive or case-insensitive) resolution.
-   */
-  def isInputFileAttrName(name: String): Boolean =
-    INPUT_FILE_ATTR_NAMES.exists(SQLConf.get.resolver(name, _))
-
   def containsInputFileFunctionExpr(expr: Expression): Boolean = {
     expr match {
       case _: InputFileName | _: InputFileBlockStart | _: InputFileBlockLength 
=> true
@@ -75,19 +66,19 @@ object PushDownInputFileExpression {
     }
   }
 
-  def containsInputFileRelatedExpr(expr: Expression): Boolean = {
-    expr match {
-      case _: InputFileName | _: InputFileBlockStart | _: InputFileBlockLength 
=> true
-      case a: AttributeReference => isInputFileAttrName(a.name)
-      case _ => expr.children.exists(containsInputFileRelatedExpr)
-    }
-  }
-
   def addFallbackTag(plan: SparkPlan): SparkPlan = {
     FallbackTags.add(plan, "fallback input file expression")
     plan
   }
 
+  /** Whether `projectList` lists nothing but columns and input file function 
calls. */
+  private def isColumnsAndInputFileCalls(projectList: Seq[NamedExpression]): 
Boolean =
+    projectList.forall {
+      case Alias(_: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength, _) => true
+      case _: Attribute => true
+      case _ => false
+    }
+
   private def rewriteExpr(expr: Expression, replacedExprs: mutable.Map[String, 
Alias]): Expression =
     expr match {
       case _: InputFileName =>
@@ -108,8 +99,11 @@ object PushDownInputFileExpression {
 
   object PreOffload extends Rule[SparkPlan] {
     override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+      // Only a call to an input file function needs rewriting: a column that 
is only named like
+      // input_file_name has nothing to push down.
       case ProjectExec(projectList, child)
-          if projectList.exists(containsInputFileRelatedExpr) && 
hasInputFileRelatedSource(child) =>
+          if projectList.exists(containsInputFileFunctionExpr) && 
hasInputFileRelatedSource(
+            child) =>
         val replacedExprs = mutable.Map[String, Alias]()
         val newProjectList = projectList.map {
           expr => rewriteExpr(expr, 
replacedExprs).asInstanceOf[NamedExpression]
@@ -117,7 +111,7 @@ object PushDownInputFileExpression {
         val newChild = addMetadataCol(child, replacedExprs)
         ProjectExec(newProjectList, newChild)
       case f @ FilterExec(condition, child)
-          if containsInputFileRelatedExpr(condition) && 
hasInputFileRelatedSource(child) =>
+          if containsInputFileFunctionExpr(condition) && 
hasInputFileRelatedSource(child) =>
         val replacedExprs = mutable.Map[String, Alias]()
         val newCondition = rewriteExpr(condition, replacedExprs)
         val newChild = addMetadataCol(child, replacedExprs)
@@ -133,16 +127,7 @@ object PushDownInputFileExpression {
           // to prevent offloading when input_file expressions are present
           addFallbackTag(ProjectExec(p.output ++ replacedExprs.values, p))
         case p: LeafExecNode if shouldAddInputFileExpr(p) =>
-          // Tag the scan when the injected attribute name would collide with 
a user data column
-          // under the current case-sensitivity setting.  The native scan 
cannot map two columns
-          // to the same normalized name; 
BasicScanExecTransformer.doValidateInternal checks this
-          // tag and fails validation, which causes the scan to remain on 
vanilla Spark where the
-          // file-path thread-local is set by the JVM iterator.
-          val scanNames = p.output.map(a => 
ConverterUtils.normalizeColName(a.name)).toSet
-          val injectedNames = replacedExprs.values.map(a => 
ConverterUtils.normalizeColName(a.name))
-          if (injectedNames.exists(scanNames)) {
-            p.setTagValue(INPUT_FILE_NAME_COLLISION_TAG, true)
-          }
+          tagNameCollision(p, replacedExprs)
           addFallbackTag(ProjectExec(p.output ++ replacedExprs.values, p))
         case p: LeafExecNode =>
           p
@@ -150,6 +135,15 @@ object PushDownInputFileExpression {
         // a single-field row.
         case p @ (_: SerializeFromObjectExec | _: DeserializeToObjectExec) =>
           addFallbackTag(ProjectExec(p.output ++ replacedExprs.values, p))
+        // The project this rule added over the scan for a call below, 
recognized by its input file
+        // aliases: the new aliases go into it too, and PostOffload folds it 
into the scan.
+        case p @ ProjectExec(projectList, scan: LeafExecNode)
+            if isInputFileSource(scan) && 
isColumnsAndInputFileCalls(projectList) &&
+              projectList.exists(_.isInstanceOf[Alias]) =>
+          if (!scan.isInstanceOf[BatchScanExecTransformerBase]) {
+            tagNameCollision(scan, replacedExprs)
+          }
+          addFallbackTag(p.copy(projectList = projectList ++ 
replacedExprs.values))
         case p: ProjectExec =>
           p.copy(
             projectList = p.projectList ++ 
replacedExprs.values.toSeq.map(_.toAttribute),
@@ -168,6 +162,26 @@ object PushDownInputFileExpression {
         case p => p.withNewChildren(p.children.map(child => 
addMetadataCol(child, replacedExprs)))
       }
 
+    /**
+     * Tags the scan when the injected attribute name would collide with a 
user data column under
+     * the current case-sensitivity setting. The native scan cannot map two 
columns to the same
+     * normalized name; BasicScanExecTransformer.doValidateInternal checks 
this tag and fails
+     * validation, which causes the scan to remain on vanilla Spark where the 
file-path thread-local
+     * is set by the JVM iterator.
+     */
+    private def tagNameCollision(
+        scan: SparkPlan,
+        replacedExprs: mutable.Map[String, Alias]): Unit = {
+      val scanNames = scan.output.map(a => 
ConverterUtils.normalizeColName(a.name)).toSet
+      val injectedNames = replacedExprs.values.map(a => 
ConverterUtils.normalizeColName(a.name))
+      if (injectedNames.exists(scanNames)) {
+        scan.setTagValue(INPUT_FILE_NAME_COLLISION_TAG, true)
+      }
+    }
+
+    private def isInputFileSource(scan: SparkPlan): Boolean =
+      scan.isInstanceOf[BatchScanExecTransformerBase] || 
shouldAddInputFileExpr(scan)
+
     private def hasInputFileRelatedSource(plan: SparkPlan): Boolean = {
       plan match {
         case _: BatchScanExecTransformerBase => true
@@ -188,17 +202,36 @@ object PushDownInputFileExpression {
 
   object PostOffload extends Rule[SparkPlan] {
     override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+      // A project over the scan that lists nothing but columns and input file 
function calls, such
+      // as the one PreOffload added: the scan, with a project over it for 
repeats, can produce its
+      // output.
       case p @ ProjectExec(projectList, child: FileSourceScanExecTransformer)
-          if projectList.exists(containsInputFileRelatedExpr) =>
-        child.copy(output = p.output)
+          if projectList.exists(containsInputFileFunctionExpr) && 
canCollapseProject(p) =>
+        foldIntoScan(p, output => child.copy(output = output))
       case p @ ProjectExec(projectList, child: HiveTableScanExecTransformer)
-          if projectList.exists(containsInputFileRelatedExpr) =>
-        child.copy(
-          requestedAttributes = p.output,
-          relation = child.relation,
-          partitionPruningPred = child.partitionPruningPred,
-          prunedOutput = child.prunedOutput
-        )(child.session)
+          if projectList.exists(containsInputFileFunctionExpr) && 
canCollapseProject(p) =>
+        foldIntoScan(
+          p,
+          output =>
+            child.copy(
+              requestedAttributes = output,
+              relation = child.relation,
+              partitionPruningPred = child.partitionPruningPred,
+              prunedOutput = child.prunedOutput
+            )(child.session)
+        )
+      // The same for a DSv2 scan, so the input file attributes keep the 
exprIds PreOffload gave
+      // them and the projects above can refer to them directly. The scan's 
own columns are kept as
+      // the scan has them: Iceberg renames columns for the native reader.
+      case p @ ProjectExec(projectList, child: BatchScanExecTransformerBase)
+          if projectList.exists(containsInputFileFunctionExpr) && 
canCollapseProject(p) &&
+            namesAliasesAfterFunctions(p) =>
+        val scanAttrs = child.output.map(a => a.exprId -> a).toMap
+        foldIntoScan(
+          p,
+          output =>
+            child.withOutput(
+              output.map(a => scanAttrs.getOrElse(a.exprId, 
a.asInstanceOf[AttributeReference]))))
       case p @ ProjectExec(projectList, child: BatchScanExecTransformerBase)
           if projectList.exists(containsInputFileFunctionExpr) =>
         val replacedExprs = mutable.Map[String, Alias]()
@@ -214,10 +247,6 @@ object PushDownInputFileExpression {
         p.copy(
           projectList = newProjectList,
           child = child.withOutput(child.output ++ inputFileAttrs))
-      case p1 @ ProjectExec(_, ProjectExec(childProjectList, scan: 
BatchScanExecTransformerBase))
-          if childProjectList.exists(containsInputFileRelatedExpr) =>
-        val newOutput = 
childProjectList.map(_.toAttribute.asInstanceOf[AttributeReference])
-        p1.copy(child = scan.withOutput(newOutput))
       case p1 @ ProjectExec(_, p2: ProjectExec) if canCollapseProject(p2) =>
         addFallbackTag(
           p2.copy(projectList =
@@ -228,14 +257,62 @@ object PushDownInputFileExpression {
             CollapseProjectShim.buildCleanedProjectList(p1.projectList, 
p2.projectList)))
     }
 
-    private def canCollapseProject(project: ProjectExec): Boolean = {
-      project.projectList.forall {
-        case Alias(_: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength, _) => true
-        case _: Attribute => true
-        case _ => false
+    /**
+     * Folds `project` into the scan that `withOutput` makes with the given 
output. The scan reads
+     * each column once, and each input file function once even when 
PreOffload added it for calls
+     * at different levels, since the native scan maps a non-partition column 
to one output only. A
+     * project over the scan gives the repeats their values. It is a Spark 
project when project
+     * offload is disabled.
+     */
+    private def foldIntoScan(
+        project: ProjectExec,
+        withOutput: Seq[Attribute] => SparkPlan): SparkPlan = {
+      val firstByName = mutable.Map[String, Attribute]()
+      val read = mutable.Set[ExprId]()
+      // Left: read by the scan. Right: given by the project over it.
+      val columns: Seq[Either[Attribute, NamedExpression]] = 
project.projectList.map {
+        case a: Alias if firstByName.contains(a.name) =>
+          Right(Alias(firstByName(a.name), a.name)(exprId = a.exprId))
+        case a: Alias =>
+          firstByName(a.name) = a.toAttribute
+          read += a.exprId
+          Left(a.toAttribute)
+        case a if read.contains(a.exprId) => Right(a.toAttribute)
+        case a =>
+          read += a.exprId
+          Left(a.toAttribute)
+      }
+      val scan = withOutput(columns.collect { case Left(attr) => attr })
+      if (columns.forall(_.isLeft)) {
+        scan
+      } else {
+        val scanAttrs = scan.output.map(a => a.exprId -> a).toMap
+        val projectList = columns.map {
+          case Left(attr) => scanAttrs(attr.exprId)
+          case Right(attr: Attribute) => scanAttrs(attr.exprId)
+          case Right(alias) => alias
+        }
+        if (GlutenConfig.get.enableColumnarProject) {
+          
BackendsApiManager.getSparkPlanExecApiInstance.genProjectExecTransformer(
+            projectList,
+            scan)
+        } else {
+          ProjectExec(projectList, scan)
+        }
       }
     }
 
+    // PreOffload names each alias it adds after its function, which is the 
name the scan looks the
+    // metadata column up by.
+    private def namesAliasesAfterFunctions(project: ProjectExec): Boolean =
+      project.projectList.forall {
+        case Alias(f, name) => name == f.prettyName
+        case _ => true
+      }
+
+    private def canCollapseProject(project: ProjectExec): Boolean =
+      isColumnsAndInputFileCalls(project.projectList)
+
     private def canCollapseProject(p1: ProjectExecTransformer, p2: 
ProjectExec): Boolean = {
       canCollapseProject(p2) && p1.projectList.forall {
         case Alias(_: Attribute, _) => true


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

Reply via email to