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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/SchemaPruning.scala:
##########
@@ -51,23 +76,284 @@ 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)] = {
+      // Under the legacy flag, an element missing all the fields read from it 
is read as null,
+      // so an outer generator would emit one row for its whole array.
+      if (!plan.containsPattern(GENERATE) || !conf.nestedSchemaPruningEnabled 
||
+          !conf.nestedSchemaPruningThroughGenerateEnabled ||
+          
conf.getConf(SQLConf.LEGACY_PARQUET_RETURN_NULL_STRUCT_IF_ALL_FIELDS_MISSING)) {
+        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 atomic 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 =>
+        // 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)
+        Some(GetArrayStructFields(
+          array, field, ordinal, fields.length, containsNull || 
field.nullable))

Review Comment:
   **Finding 16.** This fallback comes from my suggestion in finding 14, sorry. 
When the element struct has no atomic field, `smallestField` now returns its 
first field. So `size(items)` becomes `size(items.<first field>)`, and the scan 
reads that field whole. A non-atomic first field can be a wide struct. Before 
`65e6f0f`, the pick was the smallest field of any type.
   
   What I ran, on Parquet V1 and V2 with the same result on both, with `items: 
array<struct<big: struct<b1, b2>, parts: array<struct<pid, label>>, flag: 
struct<f: boolean>>>`:
   
   | query | `throughGenerate` off (master's plan) | `7c70092` | this head |
   |---|---|---|---|
   | `SELECT count(*) FROM t LATERAL VIEW explode(items) x AS e` | `flag` | 
`flag` | `big, flag` |
   | `SELECT e.parts FROM t LATERAL VIEW explode(items) x AS e` | `parts` | 
`parts, flag` | `big, parts` |
   
   Keeping `size()` on its argument when there is no atomic field gives the 
same pick on every run, so finding 14's idempotence holds. With the change 
below, the two queries read `flag` and `parts`, as master does. I tested it 
together with finding 17's change, and these all pass:
   - the catalyst `SchemaPruningSuite` (14 tests);
   - the seven schema pruning suites, including the finding-14 test (1572 
tests);
   - my round-4 probes for 13 and 14.
   
   A test with the first query would pin this. The scaladoc above says the pick 
works "like `RewriteSizeOfArrayStruct`", but that rule picks among all fields, 
so that part could go.
   
   ```suggestion
           // An atomic field keeps its size when a later run sees the narrowed 
type, so every run
           // picks the same one. Without one, `size` keeps its argument: a 
non-atomic field can be
           // a whole wide struct, which the query would not read otherwise.
           val atomic = 
fields.zipWithIndex.filter(_._1.dataType.isInstanceOf[AtomicType])
           if (atomic.isEmpty) None else {
             val (field, ordinal) = atomic.minBy(_._1.dataType.defaultSize)
             Some(GetArrayStructFields(
               array, field, ordinal, fields.length, containsNull || 
field.nullable))
           }
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -6796,6 +6796,27 @@ object SQLConf {
       .booleanConf
       .createWithDefault(true)
 
+  val NESTED_SCHEMA_PRUNING_THROUGH_GENERATE_ENABLED =
+    
buildConf("spark.sql.optimizer.nestedSchemaPruning.throughGenerate.enabled")
+      .internal()
+      .doc(s"When true and ${NESTED_SCHEMA_PRUNING_ENABLED.key} is true, 
nested fields read " +
+        "from the element of an explode or posexplode of an array column also 
prune that " +
+        "column at the scan below the generator. Not applied to ORC scans 
yet.")
+      .version("4.4.0")

Review Comment:
   **Finding 18.** `dev/next_version_candidates.py` now prints `branch-4.x 
4.5.0`. SPARK-61832 moved `branch-4.x` to 4.5.0-SNAPSHOT on 2026-11-17, after 
`branch-4.4` was cut. You want this in master and then `branch-4.x` 
([issuecomment-6765242828](https://github.com/apache/spark/pull/59706#issuecomment-6765242828)),
 so it first ships in 4.5.0. This config and `rejectForTesting` at line 6815 
should both say `4.5.0`. My round-3 note that `4.4.0` answered the version 
question was right then, but no longer is.
   
   ```suggestion
         .version("4.5.0")
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/SchemaPruning.scala:
##########
@@ -152,6 +153,86 @@ object SchemaPruning extends SQLConfHelper {
     } ++ rootFields
   }
 
+  /**
+   * Gets the root field that the array `input` of an `explode` or 
`posexplode` needs, when the
+   * generator's element output `element` is only read by `exprs` through 
nested field accesses.
+   * For example, for `explode(items) AS item` read as `item.a` and `item.b`, 
with
+   * `items: array<struct<a, b, c>>`, it returns `items: array<struct<a, b>>`.
+   *
+   * `elementFields` are fields of the element read by other means, e.g. as 
the input of a
+   * generator above this one, named like the element.
+   *
+   * If nothing of the element is read, only the array sizes are needed, so a 
single smallest
+   * field is kept, as in 
[[org.apache.spark.sql.catalyst.optimizer.GenerateOptimization]].
+   *
+   * If the element is used whole, `input` is needed whole, e.g. `items.parts` 
for
+   * `explode(items.parts)`, which still narrows `items` to `parts`.
+   *
+   * `input` must be expressed over the scan's output, or over the element of 
a generator below
+   * it. Returns None if `input` is not an access path [[SelectedField]] can 
narrow, or if it goes
+   * through map keys: narrowing keys can make distinct keys equal, and a 
reader that builds the
+   * map then keeps only one of them.
+   */
+  def getGeneratorInputRootField(
+      input: Expression,
+      element: Attribute,
+      exprs: Seq[Expression],
+      elementFields: Seq[StructField] = Nil): Option[RootField] = 
input.dataType match {
+    case _ if input.exists(_.isInstanceOf[MapKeys]) => None
+    case ArrayType(elementType, containsNull) =>
+      // Rename the element, and every other attribute too, so that the 
element's fields can be
+      // told apart by name from other columns and generator outputs.
+      val name = s"${element.name}#${element.exprId.id}"
+      val renamed = exprs.map(_.transform {
+        case a: Attribute if a.exprId == element.exprId => a.withName(name)
+        case a: Attribute => a.withName(s"${a.name}#${a.exprId.id}")
+      })
+      val fields = identifyRootFields(Nil, renamed,
+        elementFields.map(f => RootField(f.copy(name = name), derivedFromAtt = 
false)))
+        .filter(_.field.name == name)
+      val prunedElementType = (fields, elementType) match {
+        // not read: only the array sizes are needed
+        case (Seq(), StructType(structFields)) if structFields.length > 1 =>
+          StructType(Array(structFields.minBy(_.dataType.defaultSize)))

Review Comment:
   **Finding 17.** `lengthOnly` became atomic-first in `65e6f0f`, but this pick 
still takes the smallest field of any type. For an unread element the two picks 
can differ, and then the scan reads both. Take `items: array<struct<tags: 
array<int>, id: bigint, name: string>>` and `SELECT id FROM t LATERAL VIEW 
explode(items) x AS e`, where `id` is a top-level column. On Parquet V1 and V2 
it now reads `items: array<struct<tags, id>>`, because this pick takes `tags` 
and `size()` takes `id`. `7c70092` read only `tags`, and one field is enough 
for the array sizes. With the change below it reads `items: array<struct<id>>`. 
I tested it together with finding 16's change, and the same suites pass. The 
scaladoc's "as in `GenerateOptimization`" would then need an atomic-first note.
   
   ```suggestion
           case (Seq(), StructType(structFields)) if structFields.length > 1 =>
             val atomic = 
structFields.filter(_.dataType.isInstanceOf[AtomicType])
             StructType(Array((if (atomic.nonEmpty) atomic else structFields)
               .minBy(_.dataType.defaultSize)))
   ```
   



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