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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -195,6 +197,9 @@ case class DataSourceV2Relation(
  *                             false: a pushed limit, offset, top-N, sample, 
aggregate or join
  *                             decides which rows the scan returns, and a 
build site that does not
  *                             set it keeps storage filters away from its scan.
+ * @param filterRemovalCandidates post-scan conjuncts recorded during filter 
pushdown, resolved
+ *                                against the pruned output and covered by the 
table's fully pushed
+ *                                attribute declaration, that physical 
planning may omit.

Review Comment:
   **Nit (P3):** `pruneColumns` records here the conjuncts of the residuals the 
builder returned unchanged plus, when adjustment filters are added, the 
remapped inferred filters and `outputBoundPushedFilters`, and keeps those that 
the declaration covers and that pass `isPushablePartitionFilter`. The 
`pushedFilters` parameter above says fully pushed filters "do not appear as 
post-scan filters", so in this scaladoc's vocabulary "post-scan conjuncts" 
leaves out the fully pushed and inferred predicates that are in fact recorded 
and omitted, which the `keepResiduals = false` case of 'retain logical 
statistics without physical evaluation' relies on. The trait doc already says 
"returned residuals or adjustment predicates"; something like:
   
   ```suggestion
    * @param filterRemovalCandidates conjuncts that physical planning may omit: 
residuals the builder
    *                                returned unchanged and the adjustment 
predicates Spark re-adds
    *                                (surviving inferred filters and fully 
pushed filters bound to
    *                                the output), remapped to the pruned 
output, covered by the
    *                                table's fully pushed attribute 
declaration, and deterministic
    *                                without subqueries or Python UDFs.
   ```
   
   **Verification:**
   - **Inspection:** The field's scaladoc describes the same set pruneColumns 
stores: residuals returned unchanged and statistics-adjustment predicates that 
the declaration covers and that pass the eligibility check, without calling the 
adjustment predicates post-scan filters in the sense the pushedFilters 
parameter uses.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -215,6 +221,47 @@ case class DataSourceV2ScanRelation(
   // skip adding IsNotNull when the scan already implies it, or infer new 
filters across
   // joins), so plan stability testing is needed first.
 
+  /** Resolved table fields whose static Catalyst filters the source fully 
evaluates. */
+  lazy val fullyPushedFilterAttrs: ExpressionSet = relation.table match {
+    case table: SupportsFullyPushedCatalystFilters =>
+      val refs = table.fullyPushedFilterAttributes().toImmutableArraySeq
+      val tableSchema = fromAttributes(relation.withMetadataColumns().output)
+      refs.foreach { ref =>
+        val names = ref.fieldNames.toImmutableArraySeq
+        val valid = try {
+          names.nonEmpty && tableSchema.findNestedField(names, resolver = 
conf.resolver).isDefined
+        } catch {
+          case _: AnalysisException => false
+        }
+        if (!valid) {
+          throw 
QueryCompilationErrors.invalidDataSourceFullyPushedFilterAttributeError(
+            ref.fieldNames, table.name(), tableSchema)
+        }
+      }
+      val schema = fromAttributes(output)
+      val available = refs.filter { ref =>
+        schema.findNestedField(ref.fieldNames.toImmutableArraySeq, resolver = 
conf.resolver)
+          .isDefined
+      }
+      ExpressionSet(available.map { ref =>
+        V2ExpressionUtils.resolveRef[NamedExpression](ref, this) match {
+          case Alias(child, _) => child
+          case expression => expression
+        }
+      })
+    case _ => ExpressionSet()
+  }
+
+  /** Whether every field accessed by a filter is covered by the table's 
static declaration. */

Review Comment:
   **Nit (P3):** The body is `filter.references.nonEmpty && covered(filter)`, 
so a filter that accesses no field is not covered, although the documented 
condition holds vacuously for it. Both callers, candidate recording in 
`pruneColumns` and `removeFullyPushedFilters`, rely on that `false` to keep 
reference-free conjuncts executable, such as a deterministic zero-argument UDF 
predicate that the builder received and returned: no declared field makes the 
source responsible for it. An edit that aligned the body with this doc would 
drop such a conjunct and return rows that fail it. Suggest stating both 
conditions:
   
   ```suggestion
     /**
      * Whether a filter accesses at least one field and every field it 
accesses is covered by the
      * table's static declaration.
      */
   ```
   
   **Verification:**
   - **Inspection:** The scaladoc of the coverage check states that a filter 
accessing no field is not covered, matching the references.nonEmpty guard in 
its body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Relation.scala:
##########
@@ -215,6 +221,47 @@ case class DataSourceV2ScanRelation(
   // skip adding IsNotNull when the scan already implies it, or infer new 
filters across
   // joins), so plan stability testing is needed first.
 
+  /** Resolved table fields whose static Catalyst filters the source fully 
evaluates. */
+  lazy val fullyPushedFilterAttrs: ExpressionSet = relation.table match {
+    case table: SupportsFullyPushedCatalystFilters =>
+      val refs = table.fullyPushedFilterAttributes().toImmutableArraySeq
+      val tableSchema = fromAttributes(relation.withMetadataColumns().output)
+      refs.foreach { ref =>
+        val names = ref.fieldNames.toImmutableArraySeq
+        val valid = try {
+          names.nonEmpty && tableSchema.findNestedField(names, resolver = 
conf.resolver).isDefined
+        } catch {
+          case _: AnalysisException => false
+        }
+        if (!valid) {
+          throw 
QueryCompilationErrors.invalidDataSourceFullyPushedFilterAttributeError(
+            ref.fieldNames, table.name(), tableSchema)
+        }
+      }
+      val schema = fromAttributes(output)
+      val available = refs.filter { ref =>
+        schema.findNestedField(ref.fieldNames.toImmutableArraySeq, resolver = 
conf.resolver)

Review Comment:
   **Non-blocking (P2):** This lookup sits outside the `try` that guards 
validation, and `removeFullyPushedFilters` forces it for every planned scan, 
before its `inferredFilters.isEmpty` check. Join and aggregate pushdown build 
`DataSourceV2ScanRelation(holder.relation, wrappedScan, 
toAttributes(scan.readSchema()))`: `relation` is still the declaring (left) 
table, but `output` is whatever schema the source reports, which for a pushed 
join also carries the other table's columns. 
`generateColumnAliasesForDuplicatedName` renames a column only when its name is 
duplicated among the required columns.
   
   Tracing the code: with `spark.sql.optimizer.datasourceV2JoinPushdown=true`, 
take `t1 (id INT, s STRUCT<a: INT>)`, whose table declares `s.a` and whose 
builder implements `SupportsPushDownJoin`, and `t2 (k INT, s INT)` from the 
same source. In `SELECT t1.id, t2.s FROM t1 JOIN t2 ON t1.id = t2.k`, `t2.s` is 
the only required column named `s`, so the joined output carries `s: INT`. 
Validation of `s.a` against `t1`'s schema passes, and this 
`findNestedField(Seq("s", "a"))` then reaches `s: INT` and throws 
`INVALID_FIELD_NAME`. Planning fails with an error that names the declared path 
rather than anything in the query, although the declaration is valid and the 
join-pushed scan has no inferred filters, so nothing could be omitted. An 
aggregate-pushed scan fails the same way when the source gives an output column 
a declared root's name and a non-struct type. Reaching this needs a connector 
that implements the new trait together with join pushdown, which that internal 
setting keeps off by
  default, or with aggregate pushdown; none in the repository does.
   
   Suggested fix: keep the validation, but look up and resolve declared 
references only among the output columns that belong to the declaring relation, 
that is, whose exprIds come from `relation.output`. Plain pushdown keeps those 
exprIds (`PushDownUtils.toOutputAttrs`), while join, aggregate and variant 
pushdown create new ones, so a reference with no such column is treated as 
absent, like a pruned field, and binding on plain pushdown scans does not 
change. This also stops a top-level declaration from binding to the other 
table's column of the same name, which is harmless today only because these 
scans never carry inferred filters.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60147#discussion_r4487526008).
   
   **Verification:**
   - **Regression:** A pushed join between a declaring table with a valid 
nested declaration and a same-source table whose required columns include a 
top-level non-struct column named like the declared root plans without 
INVALID_FIELD_NAME, and the join-pushed scan relation reports no fully pushed 
attributes, including for a declared top-level name that only the other table's 
columns carry.
   - **Regression:** A pushed aggregate over a declaring table with a valid 
nested declaration, whose source-reported output has a top-level non-struct 
column named like the declared root, plans without INVALID_FIELD_NAME, and the 
aggregate-pushed scan relation reports no fully pushed attributes.
   - **Compatibility:** On plain pushdown scans, declarations still bind as 
before: nested siblings, dotted top-level names, struct declarations, 
case-insensitive pruned schemas and metadata columns keep the same omitted and 
retained conjuncts, and invalid declarations keep failing with the 
connector-specific error with and without inferred filters.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanRelationPushDown.scala:
##########
@@ -1073,9 +1077,28 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] 
with PredicateHelper {
         } else {
           Nil
         }
+      val adjustmentFilters = if 
(shouldAddPostPushdownAdjustmentFilters(scanRelation)) {
+        inferredAdjustmentFilters ++ scanRelation.outputBoundPushedFilters
+      } else {
+        Nil
+      }
+      val removalCandidates = if (
+          
sHolder.relation.table.isInstanceOf[SupportsFullyPushedCatalystFilters] &&
+            remappedInferredFilters.nonEmpty) {
+        remapFilters(sHolder.postScanFilterExpressions) ++ adjustmentFilters

Review Comment:
   **Nit (P3):** The tests with nested declarations ('distinguish nested 
siblings and dotted top-level names', 'resolve nested attributes against the 
pruned scan schema', 'reject invalid attribute declarations consistently') 
build `DataSourceV2ScanRelation` by hand and set `filterRemovalCandidates` 
directly, and every test that runs `V2ScanRelationPushDown` on a declaring 
table uses flat columns, where `ProjectionOverSchema` changes nothing. So, 
reading the code, recording `sHolder.postScanFilterExpressions` here without 
`remapFilters` would pass every test: under nested schema pruning, a residual 
such as `s.part = 1` would keep the unpruned struct type and field ordinal, 
fail the coverage check against the declaration resolved on the pruned output, 
and silently stay in `FilterExec`. Results stay correct, but the omission this 
PR adds for nested declarations would be lost without a failing test.
   
   Suggest an end-to-end pushdown test, for example with 
`InMemoryCatalystFilterTable` over a struct that has a field the query does not 
read, so pruning changes its ordinals: declare one nested field, have the 
builder return residuals over that field and a sibling and report an inferred 
filter, and assert that the residual over the declared field is recorded and 
omitted while the sibling residual stays in `FilterExec`.
   
   **Verification:**
   - **Regression:** Recording the unremapped residuals instead of the remapped 
ones makes the new nested case fail; with the current code it passes, omitting 
the residual over the declared nested field and keeping the sibling-field 
residual in FilterExec.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2StrategySuite.scala:
##########
@@ -1501,6 +1503,343 @@ class DataSourceV2StrategySuite extends 
SharedSparkSession {
     }
   }
 
+  gridTest("filters guaranteed pushed down by data source: " +
+    "keep inferred filters logical for batch, V1 and local scans")(
+      Seq("batch", "v1", "local")) { scanType =>
+    val schema = StructType(Seq(
+      StructField("id", LongType, nullable = false),
+      StructField("value", LongType, nullable = true)))
+    val inferred = GreaterThanOrEqual(AttributeReference("value", LongType)(), 
Literal(0L))
+    val factory: StructType => Scan = required => scanType match {
+      case "batch" => new Scan with SupportsSparkFilterEstimation {
+        override def readSchema(): StructType = required
+        override def toBatch: Batch = emptyBatch
+      }
+      case "local" => new LocalScan with SupportsSparkFilterEstimation {
+        override def readSchema(): StructType = required
+        override def rows(): Array[InternalRow] = Array.empty
+      }
+      case "v1" => new V1Scan with SupportsSparkFilterEstimation {
+        override def readSchema(): StructType = required
+        override def toV1TableScan[T <: BaseRelation with TableScan](context: 
SQLContext): T = {
+          new BaseRelation with TableScan {
+            override def sqlContext: SQLContext = context
+            override def schema: StructType = required
+            override def buildScan() = context.sparkContext.emptyRDD[Row]
+          }.asInstanceOf[T]
+        }
+      }
+    }
+    val table = new InMemoryCatalystFilterTable(schema, inferred, 
Some(factory),
+      estimateInferred = false, fullyPushedColumns = Seq("value"))
+    val relation = DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty)
+    val residual = EqualTo(relation.output.head, Literal(1L))
+    val pushed = V2ScanRelationPushDown(Filter(residual, relation))
+    val logicalFilters = pushed.collect { case Filter(condition, _) => 
condition }
+    assert(logicalFilters.exists(_.references.exists(_.name == "value")))
+    assertInferredEvaluation(pushed, evaluate = false)
+    val physical = new DataSourceV2Strategy(spark).apply(pushed).head
+    val remaining = physical.collect { case FilterExec(condition, _) => 
condition }
+    assert(remaining.size == 1 && remaining.head.semanticEquals(residual))
+  }
+
+  test("filters guaranteed pushed down by data source: " +
+    "retain residuals derived by the scan builder") {
+    val schema = new StructType().add("value", LongType)
+    val inferred = GreaterThanOrEqual(AttributeReference("value", LongType)(), 
Literal(0L))
+    val table = new InMemoryCatalystFilterTable(schema, inferred,
+      estimateInferred = false, fullyPushedColumns = Seq("value"),
+      residualFilters = filters => filters :+ 
LessThan(filters.head.references.head, Literal(10L)))
+    val relation = DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty)
+    val value = relation.output.head
+    val unchanged = GreaterThan(value, Literal(0L))
+    val derived = LessThan(value, Literal(10L))
+    val pushed = V2ScanRelationPushDown(Filter(unchanged, relation))
+    val scan = pushed.collectFirst { case s: DataSourceV2ScanRelation => s 
}.get
+    assert(ExpressionSet(scan.filterRemovalCandidates).contains(unchanged))
+    assert(!ExpressionSet(scan.filterRemovalCandidates).contains(derived))
+    val physical = new DataSourceV2Strategy(spark).apply(pushed).head
+    val remaining = physical.collect { case FilterExec(condition, _) => 
condition }
+    assert(remaining.size == 1 && remaining.head.semanticEquals(derived))
+  }
+
+  test("filters guaranteed pushed down by data source: " +
+    "preserve merges across undeclared residuals") {
+    withSQLConf(
+        SQLConf.MERGE_SUBPLANS_FILTER_PROPAGATION_ENABLED.key -> "true",
+        SQLConf.MERGE_SUBPLANS_SYMMETRIC_FILTER_PROPAGATION_ENABLED.key -> 
"false") {
+      val schema = new StructType().add("id", LongType).add("value", LongType)
+      val inferred = GreaterThanOrEqual(AttributeReference("value", 
LongType)(), Literal(0L))
+      val sharedScan = new Scan with SupportsInferredFilterEstimation {
+        override def readSchema(): StructType = schema
+        override def toBatch: Batch = emptyBatch
+      }
+      val table = new InMemoryCatalystFilterTable(schema, inferred,
+        scanFactory = Some(_ => sharedScan), fullyPushedColumns = Seq("value"),
+        residualFilters = filters => filters.filter(_.references.exists(_.name 
== "id")))
+      val subqueries = Seq(false, true).map { extraResidual =>
+        val relation = DataSourceV2Relation.create(table, None, None,
+          CaseInsensitiveStringMap.empty)
+        val Seq(id, value) = relation.output
+        val common = GreaterThan(value, Literal(0L))
+        val condition = if (extraResidual) And(common, EqualTo(id, 
Literal(1L))) else common
+        val pushed = CombineFilters(V2ScanRelationPushDown(Filter(condition, 
relation)))
+        val scan = pushed.collectFirst { case s: DataSourceV2ScanRelation => s 
}.get
+        assert(scan.filterRemovalCandidates.isEmpty)
+        val aggregate = Aggregate(Nil,
+          Seq(Alias(Count(Add(id, value)).toAggregateExpression(), 
"count")()), pushed)
+        Alias(ScalarSubquery(aggregate), s"count_$extraResidual")()
+      }
+      val merged = MergeSubplans(Project(subqueries, OneRowRelation()))
+      val scans = merged.collectWithSubqueries { case s: 
DataSourceV2ScanRelation => s }
+      assert(scans.size == 1, s"expected undeclared residuals to allow scan 
merging:\n$merged")
+    }
+  }
+
+  gridTest("filters guaranteed pushed down by data source: " +
+    "distinguish nested siblings and dotted top-level names")(
+      Seq("s.part", "`s.part`", "s")) { declared =>
+    val nestedType = new StructType().add("other", LongType).add("part", 
LongType)
+    val schema = new StructType().add("s", nestedType).add("s.part", LongType)
+    val inferred = IsNotNull(AttributeReference("s", nestedType)())
+    val table = new InMemoryCatalystFilterTable(schema, inferred,
+      estimateInferred = false, fullyPushedColumns = Seq(declared))
+    val relation = DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty)
+    val scan = DataSourceV2ScanRelation(relation, 
table.newScanBuilder(relation.options).build(),
+      relation.output, inferredFilters = Seq(inferred))
+    val root = relation.output.head
+    val nested = EqualTo(Add(GetStructField(root, 1), Literal(1L)), 
Literal(2L))
+    val sibling = EqualTo(GetStructField(root, 0), Literal(2L))
+    val dotted = EqualTo(relation.output(1), Literal(3L))
+    val wholeStruct = IsNotNull(root)
+    val predicates = Seq(nested, sibling, dotted, wholeStruct)

Review Comment:
   **Nit (P3):** Every candidate or `FilterExec` assertion in the new tests 
uses a conjunct that reads one field, or only declared fields (`a OR b`). The 
only mixed residual, `a OR c` with `c` undeclared in 'retain factored Boolean 
predicates', is never checked: `BooleanSimplification` factors the planned 
condition into `a OR (b AND c)`, which matches no candidate either way. So, 
reading the tests, replacing `children.forall(covered)` with 
`children.exists(covered)` in `isFilterOverFullyPushedAttributes` would still 
pass all of them, because literal operands stop being vacuously covered and 
single-field conjuncts keep their outcome. With that change, a builder-returned 
residual such as `value > 0 OR id = 1`, with only `value` declared, would be 
recorded and dropped from `FilterExec`, although the source need not enforce 
predicates over `id`, and rows failing it would be returned.
   
   Suggest adding a predicate that reads both a declared and an undeclared 
field to this grid (for example `s.part = 1 OR s.other = 2`, which only the `s` 
declaration covers), or a pushdown-driven case with `value > 0 OR id = 1` and 
only `value` declared, asserting that it is not recorded as a candidate and 
stays in `FilterExec` while a declared-only conjunct is omitted.
   
   **Verification:**
   - **Regression:** With the coverage check weakened so that one covered child 
suffices, the new case fails; with the current check it passes, finding the 
mixed residual in FilterExec and not among the recorded candidates, while the 
declared-only residual is omitted.



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