szehon-ho commented on code in PR #60147:
URL: https://github.com/apache/spark/pull/60147#discussion_r4544214220


##########
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:
   Fixed in cc5c734ca63. Validation still uses the full data and metadata 
schema, but lookup and binding now use only scan-output attributes whose 
exprIds belong to the declaring relation. A same-named output from the other 
join input or a pushed aggregate therefore cannot inherit the declaration. The 
capability docs also state this boundary.
   
   Added planner regressions that run V2ScanRelationPushDown for inner, 
left-outer and right-outer joins with a nested-root/type collision and a 
top-level name collision, plus an aggregate whose reported output reuses the 
nested root as a scalar. Each checks that pushdown succeeds, the static fully 
pushed set is empty, and physical planning succeeds.



##########
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:
   Updated in cc5c734ca63. The parameter doc now includes both unchanged 
returned residuals and statistics-adjustment predicates, including surviving 
inferred filters and fully pushed filters bound to the output, along with 
remapping, declaration coverage and eligibility requirements.



##########
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:
   Updated in cc5c734ca63. The doc now explicitly requires at least one 
accessed field as well as coverage of every accessed field, matching the 
references.nonEmpty guard.



##########
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:
   Added the pushdown-driven regression in cc5c734ca63. Only value is declared; 
the builder returns both value > 0 and (value > 10 OR id = 1). The test asserts 
that the declared-only conjunct is recorded and omitted, while the mixed 
conjunct is absent from the candidates and is the only predicate left in 
FilterExec. Weakening coverage to accept one covered child would fail the 
candidate assertion.



##########
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:
   Added the pushdown-driven nested-pruning regression in cc5c734ca63. The 
struct starts with unused, part and other; pruning removes unused and moves 
part from ordinal 1 to 0. The builder reports inference using the named path 
s.part and returns residuals over part and other. The test checks the pruned 
schema and exact remapped candidates, then verifies that only the sibling 
residual remains in FilterExec. Recording the original unremapped residual 
would fail the candidate assertion.



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