peter-toth commented on code in PR #59706:
URL: https://github.com/apache/spark/pull/59706#discussion_r4590608884


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/SchemaPruning.scala:
##########
@@ -51,23 +76,277 @@ object SchemaPruning extends Rule[LogicalPlan] {
           }).getOrElse(op)
     }
 
+  /** The projects and filters [[ScanOperation]] collects between two 
operators. */
+  private[sql] case class Segment(
+      projects: Seq[NamedExpression],
+      filtersStayUp: Seq[Expression],
+      filtersPushDown: Seq[Expression]) {
+    def filters: Seq[Expression] = filtersPushDown ++ filtersStayUp
+  }
+
+  /**
+   * ORC is not pruned through generators yet. Its readers mishandle some 
narrowed nested schemas:
+   * positional schema evolution (explicit, or inferred from `_colN` file 
schemas) maps nested
+   * fields by position, the ORC V1 timestamp compatibility check compares 
nested fields by ordinal,
+   * and the row reader merges map keys that become equal. Ordinary nested 
pruning already hits
+   * these on ORC; skipping generators keeps the queries through them as they 
are until the ORC
+   * readers are fixed.
+   *
+   * Matches `explode` / `posexplode` generators stacked over a leaf, each one 
optionally under
+   * `Project`s and `Filter`s. Returns the segments from the top (the one 
above the top generator
+   * first, the one over the leaf last), the generators from the top, and the 
leaf.
+   */
+  private[sql] object GeneratorsOverScan {
+    def unapply(plan: LogicalPlan): Option[(Seq[Segment], Seq[Generate], 
LogicalPlan)] = {
+      if (!plan.containsPattern(GENERATE) || !conf.nestedSchemaPruningEnabled 
||
+          !conf.nestedSchemaPruningThroughGenerateEnabled) {

Review Comment:
   **Finding 13.** With 
`spark.sql.legacy.parquet.returnNullStructIfAllFieldsMissing` on, the Parquet 
reader returns a struct as null when a file has none of its requested fields. 
Through a generator, that struct is the element of the narrowed array. An outer 
explode over such a file then emits one row per array instead of one row per 
element.
   
   Measured on this head, V1 and V2 Parquet. The table has two directories, 
read with `mergeSchema`:
   - In the first, the elements are `struct<n0>`, three per row.
   - In the second, they are `struct<n0, n1, n2>`, two per row.
   
   ```sql
   SET spark.sql.legacy.parquet.returnNullStructIfAllFieldsMissing=true;
   SELECT id, e.n1, e.n2 FROM t LATERAL VIEW OUTER explode(items) g AS e
   ```
   
   ```
   throughGenerate.enabled   rows   scan
   false                     10     items:array<struct<n0,n1,n2>>
   true                      6      items:array<struct<n1,n2>>
   ```
   
   The single-field form, `SELECT id, e.n1 ...`, already returns 6 rows on 
master, through `GeneratorNestedColumnAliasing`. The legacy flag's doc warns 
about this ("schema pruning may cause non-null structs to be read as null"). 
This PR extends it to every multi-field and chained shape. Skipping the 
generator path under the legacy flag returns the 10 rows on V1 and V2, and the 
PR's suites stay green:
   
   ```suggestion
         if (!plan.containsPattern(GENERATE) || 
!conf.nestedSchemaPruningEnabled ||
             !conf.nestedSchemaPruningThroughGenerateEnabled ||
             
conf.getConf(SQLConf.LEGACY_PARQUET_RETURN_NULL_STRUCT_IF_ALL_FIELDS_MISSING)) {
   ```
   
   A test with this table would pin it, with the legacy flag on and the rows 
compared with the run with pruning through generators disabled.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -1015,8 +1018,60 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
       Project(rewrittenProjectList, withFilter)
   }
 
-  def pruneColumns(plan: LogicalPlan): LogicalPlan = plan.transform {
+  def pruneColumns(plan: LogicalPlan, isSubquery: Boolean): LogicalPlan = 
plan.transform {
+    case op @ SchemaPruning.GeneratorsOverScan(segments, generators, sHolder: 
ScanBuilderHolder)
+        if !hasBlockingPushdown(sHolder) && 
!sHolder.relation.table.isInstanceOf[OrcTable] =>

Review Comment:
   **Finding 15.** Finding 9 
([r4516350322](https://github.com/apache/spark/pull/59706#discussion_r4516350322))
 made the V1 rule Parquet-only, since only Parquet and ORC prune nested data 
schemas. This guard still lets every other V2 table through. Of the V2 file 
tables, only `ParquetScanBuilder` and `OrcScanBuilder` set 
`supportsNestedSchemaPruning`. So the V2 JSON, CSV, text and Avro tables run 
the `size()` rewrite, the root-field collection and `rebuildAbove`, since 
`pruneScan` always returns a plan here. Then they read the same columns as 
before. This is from reading, I haven't measured the planning time on V2.
   
   Excluding the other file tables keeps the narrowed schema for every other 
source, as the description's V2 paragraph says. With this, the V2 suites stay 
green:
   
   ```scala
       case op @ SchemaPruning.GeneratorsOverScan(segments, generators, 
sHolder: ScanBuilderHolder)
           if !hasBlockingPushdown(sHolder) && (sHolder.relation.table match {
             case _: ParquetTable => true
             // other file tables do not prune nested fields, and ORC is not 
pruned through
             // generators yet, see `SchemaPruning.GeneratorsOverScan`
             case _: FileTable => false
             case _ => true
           }) =>
   ```
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/SchemaPruning.scala:
##########
@@ -51,23 +76,277 @@ object SchemaPruning extends Rule[LogicalPlan] {
           }).getOrElse(op)
     }
 
+  /** The projects and filters [[ScanOperation]] collects between two 
operators. */
+  private[sql] case class Segment(
+      projects: Seq[NamedExpression],
+      filtersStayUp: Seq[Expression],
+      filtersPushDown: Seq[Expression]) {
+    def filters: Seq[Expression] = filtersPushDown ++ filtersStayUp
+  }
+
+  /**
+   * ORC is not pruned through generators yet. Its readers mishandle some 
narrowed nested schemas:
+   * positional schema evolution (explicit, or inferred from `_colN` file 
schemas) maps nested
+   * fields by position, the ORC V1 timestamp compatibility check compares 
nested fields by ordinal,
+   * and the row reader merges map keys that become equal. Ordinary nested 
pruning already hits
+   * these on ORC; skipping generators keeps the queries through them as they 
are until the ORC
+   * readers are fixed.
+   *
+   * Matches `explode` / `posexplode` generators stacked over a leaf, each one 
optionally under
+   * `Project`s and `Filter`s. Returns the segments from the top (the one 
above the top generator
+   * first, the one over the leaf last), the generators from the top, and the 
leaf.
+   */
+  private[sql] object GeneratorsOverScan {
+    def unapply(plan: LogicalPlan): Option[(Seq[Segment], Seq[Generate], 
LogicalPlan)] = {
+      if (!plan.containsPattern(GENERATE) || !conf.nestedSchemaPruningEnabled 
||
+          !conf.nestedSchemaPruningThroughGenerateEnabled) {
+        return None
+      }
+      @tailrec
+      def collect(p: LogicalPlan, segments: Seq[Segment], generators: 
Seq[Generate])
+          : Option[(Seq[Segment], Seq[Generate], LogicalPlan)] = p match {
+        case ScanOperation(projects, filtersStayUp, filtersPushDown,
+            g @ Generate(_: ExplodeBase, _, _, _, _, _)) =>
+          collect(g.child, segments :+ Segment(projects, filtersStayUp, 
filtersPushDown),
+            generators :+ g)
+        case ScanOperation(projects, filtersStayUp, filtersPushDown, leaf: 
LeafNode)
+            if generators.nonEmpty =>
+          Some((segments :+ Segment(projects, filtersStayUp, filtersPushDown), 
generators, leaf))
+        case _ => None
+      }
+      collect(plan, Nil, Nil)
+    }
+  }
+
+  /**
+   * Prunes the scan below a chain of `explode` / `posexplode` generators of 
arrays to the fields
+   * that the plan above each generator, up to `op`, reads from its element, 
then re-resolves the
+   * chain against the narrower types. Going down from the top generator, the 
fields read from a
+   * generator's element become fields read from its input: a column of the 
scan, or the element
+   * of a generator below it.
+   *
+   * `pruneScan` prunes the scan given the projects over the scan that do not 
only feed the
+   * bottom generator and the root fields the generators need, and returns the 
new plan over the
+   * scan. Returns None if nothing is pruned, or if the output of `op` would 
change.
+   */
+  private[sql] def pruneThroughGenerators(
+      op: LogicalPlan,
+      scanRelation: LogicalPlan)(
+      pruneScan: (Segment, Seq[NamedExpression], Seq[RootField]) => 
Option[LogicalPlan])
+      : Option[LogicalPlan] = {
+    // the flags are checked by GeneratorsOverScan, which matched `op`
+    try {
+      // e.g. the `size(arr) > 0` filters inferred for a non-outer explode
+      op.transformAllExpressions {
+        case s @ Size(child, _) => s.copy(child = lengthOnly(child))
+      } match {
+        case sized @ GeneratorsOverScan(segments, generators, _) =>
+          pruneThroughGeneratorsImpl(sized, segments, generators, 
scanRelation)(pruneScan)
+        case _ => None
+      }
+    } catch {
+      // In tests, surface the bug (e.g. SelectedField and 
ProjectionOverSchema drifting apart)
+      // instead of passing on the unpruned plan.
+      case NonFatal(e) if Utils.isTesting => throw e
+      // Otherwise a missed optimization, not a failed query: keep the plan as 
it is. The rule
+      // runs several times per query, so this is not logged as a warning.
+      case NonFatal(e) =>
+        logDebug("Failed to prune nested fields through generators; " +
+          "the scan is pruned without them", e)
+        None
+    }
+  }
+
+  /**
+   * The size of an array only needs its length. Returns an array of the same 
length that reads
+   * as little as possible: the smallest field of an array of structs, like
+   * [[org.apache.spark.sql.catalyst.optimizer.RewriteSizeOfArrayStruct]] does 
for scan columns,
+   * and of the outer array for a nested field of an array of structs, which 
has the same length.
+   */
+  private def lengthOnly(array: Expression): Expression = {
+    def smallestField(array: Expression): Option[Expression] = array.dataType 
match {
+      case ArrayType(StructType(fields), containsNull) if fields.length > 1 =>
+        val (field, ordinal) = 
fields.zipWithIndex.minBy(_._1.dataType.defaultSize)

Review Comment:
   **Finding 14.** The field this picks depends on how far the array's type is 
already narrowed, and `readSizesDirectly` takes the pick back out of the plan. 
`SchemaPruning` runs three times in the Early Filter and Projection Push-Down 
batch, and V1 retries at every node of the chain. So a later run sees the 
narrowed type. A nested array that was the larger field can then be the smaller 
one, and that run picks it and prunes the first pick away.
   
   Measured on this head under `spark.testing`, which checks that a `Once` 
batch is idempotent. The table is `as_ array<struct<a_s string, bs 
array<struct<b_s string, cs array<struct<c_s string, ds array<struct<d_s 
string, es array<struct<e_i int, e_j int, e_s string>>>>>>>>>>`:
   
   ```sql
   SELECT size(a.bs), size(a.bs[0].cs), size(a.bs[0].cs[0].ds), 
size(a.bs[0].cs[0].ds[0].es)
   FROM t LATERAL VIEW OUTER explode(as_) t1 AS a
   ```
   
   - V1: `SparkRuntimeException: Once strategy's idempotence is broken for 
batch Early Filter and Projection Push-Down`.
   - V2: 3 rows.
   - With pruning through generators disabled: 3 rows on both.
   
   `ds`'s elements are `struct<d_s, es>`. The first run picks `d_s` (default 
size 20) over `es` (28). Once `es` is narrowed to `e_i`, a later run picks `es` 
(4) and drops `d_s`. Outside tests nothing checks this, and how far the scan is 
pruned then depends on how often the rule fires.
   
   An atomic field keeps its size when the type is narrowed. So the smallest 
atomic field, or the first field when there is none, is the same pick on every 
run. With this, V1 and V2 return the 3 rows with the same scan, and the PR's 
suites stay green:
   
   ```suggestion
           // An atomic field keeps its size when a later run sees the narrowed 
type, so every run
           // picks the same one. Without one, the first field stays first, as 
pruning keeps order.
           val atomic = 
fields.zipWithIndex.filter(_._1.dataType.isInstanceOf[AtomicType])
           val (field, ordinal) =
             if (atomic.nonEmpty) atomic.minBy(_._1.dataType.defaultSize) else 
(fields.head, 0)
   ```
   
   A test with this query would pin it, since the suites run under 
`spark.testing`.
   



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