spark-test commented on code in PR #60084:
URL: https://github.com/apache/spark/pull/60084#discussion_r4543254077


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetUtils.scala:
##########
@@ -323,12 +324,30 @@ object ParquetUtils extends Logging {
   private[sql] def getPushedDownAggResult(
       footer: ParquetMetadata,
       filePath: String,
-      dataSchema: StructType,
+      isCaseSensitive: Boolean,
       partitionSchema: StructType,
       aggregation: Aggregation)
   : (Array[PrimitiveType], Array[Any]) = {
-    val footerFileMetaData = footer.getFileMetaData
-    val fields = footerFileMetaData.getSchema.getFields
+    // The column chunks of a row group follow the leaf columns of the file 
schema, and a nested
+    // column has one chunk per leaf, so a column's position among the 
top-level fields is not
+    // the index of its chunk. The file may also order its columns differently 
from the data
+    // schema. Aggregates are only pushed down for top-level primitive 
columns, so find the
+    // chunk index by matching the column name against the top-level leaves of 
the file schema.
+    // Returns -1 if the file does not have the column.
+    val leafColumns = footer.getFileMetaData.getSchema.getColumns
+    val columnIndexes = mutable.HashMap.empty[String, Int]
+    def columnIndex(colName: String): Int = 
columnIndexes.getOrElseUpdate(colName, {
+      val matches = (0 until leafColumns.size).filter { i =>
+        val path = leafColumns.get(i).getPath
+        path.length == 1 &&
+          (if (isCaseSensitive) path.head == colName else 
path.head.equalsIgnoreCase(colName))

Review Comment:
   **Blocking (P1):** With aggregate push-down on and the default 
`spark.sql.caseSensitive=false`, this compares names with 
`String.equalsIgnoreCase`, which folds each character through upper case. The 
Parquet reader (`ParquetReadSupport.clipParquetGroupFields`) and the analyzer 
instead key names by `toLowerCase(Locale.ROOT)`, and the two rules disagree for 
letters with special case mappings, so push-down can disagree with reading the 
data:
   
   - `ıd` (U+0131) upper-cases to `ID`, so a file with columns `id` and `ıd` 
matches both here. Reading the code, `SELECT max(id)` over a file Spark itself 
wrote with ``spark.range(3).selectExpr("id", "id * 2 AS `ıd`")`` and read back 
with its own schema now fails with `_LEGACY_ERROR_TEMP_2093`, while the base 
branch and the read with push-down off both return 2. The write and the table's 
duplicate-name check accept both names because they lower-case them.
   - `i̇d` (i + U+0307) and `İd` (U+0130) share the reader's key but differ in 
length, so a file column `i̇d` read with the user schema `İd LONG` is found by 
the read, while here COUNT returns 0 for that file and MIN/MAX raise 
`NO_MIN_MAX`.
   - `ſum` (U+017F) matches `sum` here, so push-down answers from `ſum`'s 
statistics while the read treats `sum` as missing.
   
   The first case breaks a query that works on the base branch, and the second 
gives a silently wrong COUNT.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetUtils.scala:
##########
@@ -323,12 +324,30 @@ object ParquetUtils extends Logging {
   private[sql] def getPushedDownAggResult(
       footer: ParquetMetadata,
       filePath: String,
-      dataSchema: StructType,
+      isCaseSensitive: Boolean,
       partitionSchema: StructType,
       aggregation: Aggregation)
   : (Array[PrimitiveType], Array[Any]) = {
-    val footerFileMetaData = footer.getFileMetaData
-    val fields = footerFileMetaData.getSchema.getFields
+    // The column chunks of a row group follow the leaf columns of the file 
schema, and a nested
+    // column has one chunk per leaf, so a column's position among the 
top-level fields is not
+    // the index of its chunk. The file may also order its columns differently 
from the data
+    // schema. Aggregates are only pushed down for top-level primitive 
columns, so find the
+    // chunk index by matching the column name against the top-level leaves of 
the file schema.
+    // Returns -1 if the file does not have the column.
+    val leafColumns = footer.getFileMetaData.getSchema.getColumns
+    val columnIndexes = mutable.HashMap.empty[String, Int]
+    def columnIndex(colName: String): Int = 
columnIndexes.getOrElseUpdate(colName, {
+      val matches = (0 until leafColumns.size).filter { i =>
+        val path = leafColumns.get(i).getPath
+        path.length == 1 &&

Review Comment:
   **Non-blocking (P2):** `path.length == 1` keeps only top-level primitive 
leaves, so a top-level struct, array or map column never takes part in the 
match. `ParquetReadSupport.clipParquetGroupFields` matches against all 
top-level fields, groups included, so the two disagree whenever a group's name 
matches the aggregated column:
   
   - A file written case-sensitively with `a BIGINT` and `A STRUCT<x: BIGINT>`, 
then read in a case-insensitive session with the schema `a LONG`: the read 
fails with `_LEGACY_ERROR_TEMP_2093` (matched `[a, A]`), but this lookup sees 
only `a`, so, reading the code, `SELECT max(a), count(a)` returns 2 and 3.
   - A file whose `a` is a `STRUCT<x: BIGINT>`, read with the schema `a LONG`: 
the read fails because it cannot read the group as a LONG, but here `a` counts 
as missing, so `count(a)` is 0 for that file and MIN/MAX raise `NO_MIN_MAX`.
   
   Both need a user-specified schema or files whose schemas differ. The new 
ambiguity test uses two primitive columns, so it does not cover either case.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60084#issuecomment-6655665123), 
[2](https://github.com/apache/spark/pull/60084#pullrequestreview-5783203020).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/parquet/ParquetScanBuilder.scala:
##########
@@ -95,7 +95,29 @@ case class ParquetScanBuilder(
   }
 
   override def pushAggregation(aggregation: Aggregation): Boolean = {
-    if (!sparkSession.sessionState.conf.parquetAggregatePushDown) {
+    val sqlConf = sparkSession.sessionState.conf
+    if (!sqlConf.parquetAggregatePushDown) {
+      return false
+    }
+    // With field ID reading, the reader matches columns by field ID rather 
than by name (see
+    // `ParquetReadSupport.clipParquetGroupFields`), but the footer statistics 
are looked up by
+    // name, so the two could pick different columns.
+    if (sqlConf.parquetFieldIdReadEnabled && 
ParquetUtils.hasFieldIds(dataSchema)) {
+      return false
+    }
+    // The footer only has statistics for leaf columns, and the null count of 
a leaf of a nested
+    // column is not the number of nulls of the column itself: a non-null 
struct can have a null
+    // field, and an empty array or map has no leaf value. So COUNT of a 
nested column cannot be
+    // answered from the footer.
+    val countsNestedColumn = aggregation.aggregateExpressions.exists {
+      case count: Count => V2ColumnUtils.extractV2Column(count.column).exists 
{ colName =>
+        // `colName` is the name of the resolved column, so match it exactly: 
`getFieldIndex` is
+        // case-insensitive and could pick another column that differs only in 
case.

Review Comment:
   **Nit (P3):** `StructType.getFieldIndex` is `nameToIndex.get(name)` over the 
exact field names (StructType.scala:315-316); the case-insensitive variant is 
`getFieldIndexCaseInsensitive`. So `schema.getFieldIndex(colName)` already 
picked this same field, and the reason given here is false. It could also lead 
someone to distrust other exact lookups on this path, such as 
`partitionSchema.getFieldIndex(colName)` in `getPushedDownAggResult`. Since 
`colName` arrives spelled as in the table schema, the comment only needs to say 
that:
   
   ```suggestion
           // `colName` is the name of the resolved column, as it appears in 
the table schema, so
           // match it exactly.
   ```
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60084#issuecomment-6655665123), 
[2](https://github.com/apache/spark/pull/60084#pullrequestreview-5783203020).
   
   **Verification:**
   - **Inspection:** The comment above the nested-COUNT lookup describes an 
exact match on the resolved column name and makes no claim that getFieldIndex 
ignores case.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetUtils.scala:
##########
@@ -323,12 +324,30 @@ object ParquetUtils extends Logging {
   private[sql] def getPushedDownAggResult(
       footer: ParquetMetadata,
       filePath: String,
-      dataSchema: StructType,
+      isCaseSensitive: Boolean,
       partitionSchema: StructType,
       aggregation: Aggregation)
   : (Array[PrimitiveType], Array[Any]) = {
-    val footerFileMetaData = footer.getFileMetaData
-    val fields = footerFileMetaData.getSchema.getFields
+    // The column chunks of a row group follow the leaf columns of the file 
schema, and a nested
+    // column has one chunk per leaf, so a column's position among the 
top-level fields is not
+    // the index of its chunk. The file may also order its columns differently 
from the data
+    // schema. Aggregates are only pushed down for top-level primitive 
columns, so find the
+    // chunk index by matching the column name against the top-level leaves of 
the file schema.
+    // Returns -1 if the file does not have the column.
+    val leafColumns = footer.getFileMetaData.getSchema.getColumns
+    val columnIndexes = mutable.HashMap.empty[String, Int]
+    def columnIndex(colName: String): Int = 
columnIndexes.getOrElseUpdate(colName, {
+      val matches = (0 until leafColumns.size).filter { i =>

Review Comment:
   **Nit (P3):** This filter walks every leaf column once per distinct 
aggregated column, for every file, so the work grows with the number of 
aggregated columns times the number of leaf columns. A query that counts every 
column of a 2,000-column table makes about 4 million name comparisons per file, 
where the base branch made 2,000 map lookups. That is negligible for a few 
aggregates and has not been measured for wide ones, but one map of the file's 
top-level fields, built once per file, gives the same matches and errors in a 
single pass.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceAggregatePushDownSuite.scala:
##########
@@ -773,17 +779,145 @@ class ParquetV2AggregatePushDownSuite extends 
ParquetAggregatePushDownSuite {
     }
   }
 
+  test("SPARK-60598: aggregate push-down reads the right column after a nested 
column") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // `s`, `arr` and `m` have several leaf column chunks each, so a later 
column's

Review Comment:
   **Nit (P3):** `arr` is a `Seq[Int]`, which Spark writes as a LIST with the 
single leaf `arr.list.element`; only `s` (two ints) and `m` (key and value) 
have two chunks each, so `a` is chunk 5 because of `s` and `m` alone. If an 
array with several chunks is meant to be covered, `arr` would need to be an 
array of structs; otherwise:
   
   ```suggestion
           // `s` and `m` have two leaf column chunks each (and `arr` one), so 
a later column's
   ```
   
   **Verification:**
   - **Inspection:** The fixture comment gives two leaf chunks for `s` and `m` 
and one for `arr`.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceAggregatePushDownSuite.scala:
##########
@@ -773,17 +779,145 @@ class ParquetV2AggregatePushDownSuite extends 
ParquetAggregatePushDownSuite {
     }
   }
 
+  test("SPARK-60598: aggregate push-down reads the right column after a nested 
column") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // `s`, `arr` and `m` have several leaf column chunks each, so a later 
column's
+        // position among the top-level fields is not its position among the 
column chunks.
+        Seq(((100, 200), Seq(7, 8), Map(9 -> 10), Some(1), 2, true),
+            ((300, 400), Seq(11), Map(12 -> 13), None, 6, false),
+            ((500, 600), Seq.empty[Int], Map.empty[Int, Int], Some(5), 4, 
false))
+          .toDF("s", "arr", "m", "a", "b", "c")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(b), count(a), max(c), min(c) FROM 
t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(b), COUNT(a), 
MAX(c), MIN(c)]")
+            checkAnswer(df, Row(5, 2, 2, true, false))
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: COUNT of a nested column is not pushed down") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // The footer only has statistics for the leaf columns. A non-null 
struct whose first
+        // field is null, and an empty array, are both null in the first leaf 
column, so its
+        // null count is not the number of null values of the column.
+        sql("SELECT named_struct('x', CAST(NULL AS INT), 'y', 1) AS s, array() 
AS arr, " +
+            "map(1, 2) AS m " +
+          "UNION ALL SELECT NULL, NULL, NULL " +
+          "UNION ALL SELECT named_struct('x', 3, 'y', 4), array(5), map()")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT count(s), count(arr), count(m) FROM t")
+            checkPushedInfo(df, "PushedAggregation: []")
+            checkAnswer(df, Row(2, 2, 2))
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: aggregate push-down with a user schema that differs from 
the file schema") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        Seq((1, 10L, 100), (2, 20L, 200)).toDF("x", "a", 
"b").coalesce(1).write.parquet(path)
+        withTempView("t") {
+          // The data schema lists `b` (as `B`) before `a`, leaves out `x`, 
and adds `z`, which
+          // the file does not have.
+          spark.read.schema("B INT, a LONG, z 
INT").parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(B), count(B), count(z) FROM t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(B), COUNT(B), 
COUNT(z)]")
+            checkAnswer(df, Row(20L, 100, 2, 0))
+            // A column the file does not have is all null, so it has no min 
or max either.
+            Seq("min", "max").foreach { agg =>
+              checkErrorMatchPVals(
+                exception = interceptAggPushDownError(s"SELECT $agg(z) FROM 
t"),
+                condition = 
"PARQUET_AGGREGATE_PUSH_DOWN_UNSUPPORTED.NO_MIN_MAX",
+                parameters = Map("filePath" -> ".*", "config" -> 
aggPushDownEnabledKey))
+            }
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: aggregate push-down fails on an ambiguous 
case-insensitive column match") {
+    withTempPath { dir =>
+      val path = dir.getCanonicalPath
+      withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+        spark.range(3).selectExpr("id AS a", "id * 2 AS 
A").coalesce(1).write.parquet(path)
+      }
+      withTempView("t") {
+        spark.read.schema("a LONG").parquet(path).createOrReplaceTempView("t")
+        withSQLConf(aggPushDownEnabledKey -> "true") {
+          // The reader fails in the same way for this file (see 
`ParquetReadSupport`).
+          val e = interceptCause[SparkRuntimeException]("SELECT max(a) FROM t")

Review Comment:
   **Nit (P3):** For this file the reader raises the same 
`_LEGACY_ERROR_TEMP_2093` with the same parameters, as the comment above says, 
so if `MAX(a)` stopped being pushed, for example because a planning guard 
declined it, this test would still pass without ever reaching the duplicate 
check in `columnIndex`. Checking the plan first makes the test depend on that 
branch:
   
   ```suggestion
             checkPushedInfo(sql("SELECT max(a) FROM t"), "PushedAggregation: 
[MAX(a)]")
             val e = interceptCause[SparkRuntimeException]("SELECT max(a) FROM 
t")
   ```
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60084#issuecomment-6655665123), 
[2](https://github.com/apache/spark/pull/60084#pullrequestreview-5783203020).
   
   **Verification:**
   - **Regression:** The ambiguity test checks both that MAX(a) is pushed down 
and that collecting it fails with _LEGACY_ERROR_TEMP_2093.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceAggregatePushDownSuite.scala:
##########
@@ -773,17 +779,145 @@ class ParquetV2AggregatePushDownSuite extends 
ParquetAggregatePushDownSuite {
     }
   }
 
+  test("SPARK-60598: aggregate push-down reads the right column after a nested 
column") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // `s`, `arr` and `m` have several leaf column chunks each, so a later 
column's
+        // position among the top-level fields is not its position among the 
column chunks.
+        Seq(((100, 200), Seq(7, 8), Map(9 -> 10), Some(1), 2, true),
+            ((300, 400), Seq(11), Map(12 -> 13), None, 6, false),
+            ((500, 600), Seq.empty[Int], Map.empty[Int, Int], Some(5), 4, 
false))
+          .toDF("s", "arr", "m", "a", "b", "c")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(b), count(a), max(c), min(c) FROM 
t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(b), COUNT(a), 
MAX(c), MIN(c)]")
+            checkAnswer(df, Row(5, 2, 2, true, false))

Review Comment:
   **Nit (P3):** `count(a)` expects 2, but the chunk at `a`'s top-level 
position, `m.key_value.key`, also has one null (from the empty map), so the old 
lookup gives 2 as well; likewise `count(B)` in the user-schema test is 2 
whether it reads `b` or `x`. So a COUNT-only regression that uses a column's 
top-level position in the file as its chunk index would pass every COUNT 
assertion while returning another column's null count; only `count(z)` catches 
a regression to the data-schema position. Adding `count(b)` here, where 
`m.key_value.value` at `b`'s old position has a null and `b` has none, and 
giving `b` a null in the user-schema test, would make the COUNT assertions 
depend on the chunk they read.
   
   **Verification:**
   - **Regression:** In both tests at least one COUNT of a column the file has 
expects a value that the chunk at the column's old position would not give.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceAggregatePushDownSuite.scala:
##########
@@ -773,17 +779,145 @@ class ParquetV2AggregatePushDownSuite extends 
ParquetAggregatePushDownSuite {
     }
   }
 
+  test("SPARK-60598: aggregate push-down reads the right column after a nested 
column") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // `s`, `arr` and `m` have several leaf column chunks each, so a later 
column's
+        // position among the top-level fields is not its position among the 
column chunks.
+        Seq(((100, 200), Seq(7, 8), Map(9 -> 10), Some(1), 2, true),
+            ((300, 400), Seq(11), Map(12 -> 13), None, 6, false),
+            ((500, 600), Seq.empty[Int], Map.empty[Int, Int], Some(5), 4, 
false))
+          .toDF("s", "arr", "m", "a", "b", "c")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(b), count(a), max(c), min(c) FROM 
t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(b), COUNT(a), 
MAX(c), MIN(c)]")
+            checkAnswer(df, Row(5, 2, 2, true, false))
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: COUNT of a nested column is not pushed down") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // The footer only has statistics for the leaf columns. A non-null 
struct whose first
+        // field is null, and an empty array, are both null in the first leaf 
column, so its
+        // null count is not the number of null values of the column.
+        sql("SELECT named_struct('x', CAST(NULL AS INT), 'y', 1) AS s, array() 
AS arr, " +
+            "map(1, 2) AS m " +
+          "UNION ALL SELECT NULL, NULL, NULL " +
+          "UNION ALL SELECT named_struct('x', 3, 'y', 4), array(5), map()")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT count(s), count(arr), count(m) FROM t")

Review Comment:
   **Nit (P3):** Because `pushAggregation` declines the whole aggregation as 
soon as any COUNT is nested, `count(s)` alone keeps this query from being 
pushed, so `PushedAggregation: []` and `Row(2, 2, 2)` still hold if 
`isNestedType` loses its array or map case. The shared nested-COUNT test also 
uses a struct, and no test counts a variant or a UDT over a nested type. Losing 
any of those cases would let COUNT of such a column be pushed, find no 
top-level leaf, and return 0 without failing a test. Counting each type in its 
own query, and adding a `parse_json` variant column and a UDT column such as 
`TestUDT.MyDenseVectorUDT`, would pin each case.
   
   **Verification:**
   - **Regression:** COUNT of a struct, an array, a map, a variant and a UDT 
over a nested type are each checked in their own query to be not pushed down 
and to return the read's count.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/FileSourceAggregatePushDownSuite.scala:
##########
@@ -773,17 +779,145 @@ class ParquetV2AggregatePushDownSuite extends 
ParquetAggregatePushDownSuite {
     }
   }
 
+  test("SPARK-60598: aggregate push-down reads the right column after a nested 
column") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // `s`, `arr` and `m` have several leaf column chunks each, so a later 
column's
+        // position among the top-level fields is not its position among the 
column chunks.
+        Seq(((100, 200), Seq(7, 8), Map(9 -> 10), Some(1), 2, true),
+            ((300, 400), Seq(11), Map(12 -> 13), None, 6, false),
+            ((500, 600), Seq.empty[Int], Map.empty[Int, Int], Some(5), 4, 
false))
+          .toDF("s", "arr", "m", "a", "b", "c")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(b), count(a), max(c), min(c) FROM 
t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(b), COUNT(a), 
MAX(c), MIN(c)]")
+            checkAnswer(df, Row(5, 2, 2, true, false))
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: COUNT of a nested column is not pushed down") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        // The footer only has statistics for the leaf columns. A non-null 
struct whose first
+        // field is null, and an empty array, are both null in the first leaf 
column, so its
+        // null count is not the number of null values of the column.
+        sql("SELECT named_struct('x', CAST(NULL AS INT), 'y', 1) AS s, array() 
AS arr, " +
+            "map(1, 2) AS m " +
+          "UNION ALL SELECT NULL, NULL, NULL " +
+          "UNION ALL SELECT named_struct('x', 3, 'y', 4), array(5), map()")
+          .coalesce(1).write.parquet(path)
+        withTempView("t") {
+          spark.read.parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT count(s), count(arr), count(m) FROM t")
+            checkPushedInfo(df, "PushedAggregation: []")
+            checkAnswer(df, Row(2, 2, 2))
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: aggregate push-down with a user schema that differs from 
the file schema") {
+    Seq("false", "true").foreach { enableVectorizedReader =>
+      withTempPath { dir =>
+        val path = dir.getCanonicalPath
+        Seq((1, 10L, 100), (2, 20L, 200)).toDF("x", "a", 
"b").coalesce(1).write.parquet(path)
+        withTempView("t") {
+          // The data schema lists `b` (as `B`) before `a`, leaves out `x`, 
and adds `z`, which
+          // the file does not have.
+          spark.read.schema("B INT, a LONG, z 
INT").parquet(path).createOrReplaceTempView("t")
+          withSQLConf(
+            aggPushDownEnabledKey -> "true",
+            vectorizedReaderEnabledKey -> enableVectorizedReader) {
+            val df = sql("SELECT max(a), min(B), count(B), count(z) FROM t")
+            checkPushedInfo(df, "PushedAggregation: [MAX(a), MIN(B), COUNT(B), 
COUNT(z)]")
+            checkAnswer(df, Row(20L, 100, 2, 0))
+            // A column the file does not have is all null, so it has no min 
or max either.
+            Seq("min", "max").foreach { agg =>
+              checkErrorMatchPVals(
+                exception = interceptAggPushDownError(s"SELECT $agg(z) FROM 
t"),
+                condition = 
"PARQUET_AGGREGATE_PUSH_DOWN_UNSUPPORTED.NO_MIN_MAX",
+                parameters = Map("filePath" -> ".*", "config" -> 
aggPushDownEnabledKey))
+            }
+          }
+        }
+      }
+    }
+  }
+
+  test("SPARK-60598: aggregate push-down fails on an ambiguous 
case-insensitive column match") {
+    withTempPath { dir =>
+      val path = dir.getCanonicalPath
+      withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {

Review Comment:
   **Nit (P3):** This is the only place the new tests turn on 
`spark.sql.caseSensitive`, and it only wraps the write; every pushed aggregate 
in the suite runs case-insensitively. So nothing would fail if the readers 
passed `false` for `isCaseSensitive`, if `columnIndex` ignored it, or if the 
nested-COUNT check matched names ignoring case, although each of those changes 
a case-sensitive answer: `max(a)` over this file would hit the duplicate-field 
error, `count(B)` over a file column `b` would count `b` although the read 
treats `B` as missing, and `COUNT(A)` of a struct `A` beside a primitive `a` 
would be pushed and return 0. Running the user-schema and ambiguity tests under 
both values of the setting, plus a case-sensitive nested-COUNT case, would 
cover these branches.
   
   **Verification:**
   - **Regression:** With spark.sql.caseSensitive=true, push-down answers 
max(a) over a file with `a` and `A` from `a`, counts `B` over a file column `b` 
as missing, and declines COUNT of a struct `A` while pushing COUNT of a 
primitive `a`.



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