HyukjinKwon commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4515669963


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -97,70 +156,111 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
   }
 
   /**
-   * Returns the columns that each streaming relation of Data Source V2 needs 
to read, from `plan`
-   * optimized as the micro-batches are (see `forStartup`). A relation without 
an entry reads all
-   * its columns, as all do if the optimization fails.
+   * Returns the columns that each streaming relation of Data Source V2 needs 
to read, and the
+   * filters that its scan may get, from `plan` optimized as the micro-batches 
are (see
+   * `forStartup`), without the filters that the optimizer infers from the 
constraints of the plan
+   * or from generators, so that a scan only gets the filters that the query 
applies to its own
+   * source. A relation without an entry reads all its columns with no filter, 
as all do if the
+   * optimization fails, unless 
`spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` makes
+   * the failure fail the query, as in the tests. The plan is not optimized 
when no source prunes
+   * its columns and the plan has no condition, since nothing could be pushed 
down.
    *
    * @param session the session of the stream
    * @param offsetLogMetadata the metadata of the last entry of the offset log 
of the query, if any
    */
-  def requiredColumnsOfSources(
+  def columnsAndFiltersOfSources(
       session: SparkSession,
       plan: LogicalPlan,
-      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, AttributeSet] = {
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    try {
+      readsOfSources(session, plan, offsetLogMetadata)
+    } catch {
+      case NonFatal(e)
+          if 
!session.sessionState.conf.getConf(SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR)
 =>
+        logWarning(log"Could not optimize the streaming query to push down 
what it reads " +
+          log"to the scans of its sources, which read all their columns with 
no filter.", e)
+        Map.empty
+    }
+  }
+
+  // What the relations of `plan` read, see `columnsAndFiltersOfSources`, or 
the failure of the
+  // optimization.
+  private def readsOfSources(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
     val conf = session.sessionState.conf.clone()
     offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf))
     conf.setConf(SQLConf.CBO_ENABLED, false)
+    withoutInferredFilters(conf)

Review Comment:
   Done in 95f97ea: the rules are now excluded only when a source may get 
filters. The new `startupConf` excludes them when 
`spark.sql.streaming.v2FilterPushdown.enabled` is true and a source has 
`STREAMING_FILTER_PUSHDOWN`, also for a plan without conditions, since 
`InferFiltersFromGenerate` adds some. A query that only uses the column pruning 
is optimized at startup with the rules of its micro-batches again, as with 
#59943.
   
   The new test `exclude the rules that infer filters when the query starts 
only for the filter pushdown` checks the three cases. The startup optimization 
is now also skipped when no source prunes its columns and none can get filters.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -6321,6 +6321,35 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val STREAMING_V2_FILTER_PUSHDOWN_ENABLED =
+    buildConf("spark.sql.streaming.v2FilterPushdown.enabled")
+      .doc("When true, the scan of a Data Source V2 streaming source whose 
table has the " +
+        "capability STREAMING_FILTER_PUSHDOWN gets the filters that the 
streaming query applies " +
+        "to all the rows that it reads from the source, which Spark takes from 
the plan of the " +
+        "query optimized when the query starts, as it does for batch scans: 
Spark optimizes the " +
+        "query once more when it starts, as it optimizes each micro-batch. A 
scan builder " +
+        "whose filters may fail on some rows, as a cast does with ANSI, only 
gets those that the " +

Review Comment:
   Done in 95f97ea: both now describe the actual contract, as the Javadoc of 
`STREAMING_FILTER_PUSHDOWN` does. A builder gets the predicates that the query 
applies first, in their order, and then those that cannot fail, which the query 
may apply anywhere. The config doc also says which columns get no filter, and 
what happens when a micro-batch cannot be checked (see the thread at L676).



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryBaseTable.scala:
##########
@@ -815,7 +835,11 @@ abstract class InMemoryBaseTable(
 
     override def toMicroBatchStream(checkpointLocation: String): 
MicroBatchStream = {
       createdMicroBatchStreams.incrementAndGet()
-      new InMemoryMicroBatchStream(readSchema, tableSchema)
+      val filters = this match {
+        case scan: InMemoryBatchScan if simulateStreamingFilters => 
scan.pushedFilters

Review Comment:
   Done in 95f97ea: `FilterStreamTable` now reads a `FilteringMemoryStream`, 
whose readers drop the rows that fail the pushed filters, in their order.
   - The Catalyst filters are bound to the columns of the stream.
   - The V2 predicates are evaluated through `PredicateUtils.toV1`, and the 
stream keeps all the rows for a predicate that it cannot translate.
   - A row on which a filter cannot be evaluated is kept from that filter on, 
as a filter that may fail would not see the rows that a filter before it drops.
   
   So the answers of the V2 and Catalyst tests now depend on the pushed 
filters, as those of the V1 tests do. Two new tests also fail a micro-batch 
that no longer applies the filters of a V2 or a Catalyst builder.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +628,237 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
     }
   }
 
+  /**
+   * Checks that `plan`, the optimized plan of a micro-batch in `session`, 
applies the filters that
+   * the scans of its sources got when the query started to all the rows that 
it reads from them:
+   * a scan may drop the rows that fail its filters, so the plan must drop 
them too. The conditions
+   * that the plan applies to all the rows of each occurrence of a relation 
whose scan got filters
+   * must imply these filters (see `impliedBy`). Otherwise, the value of an 
expression in a pushed
+   * filter changed after the query started, as a function of the time that 
`forStartup` does not
+   * replace would, or the configuration of the optimizer changed in the 
session of the query, or
+   * the optimizer of the micro-batch rewrote a pushed filter in a way that 
`impliedBy` does not
+   * follow, and the micro-batch fails before it reads its data, with the 
failure of the optimizer
+   * as its cause if there is one.
+   */
+  def checkPushedFilters(
+      session: SparkSession,
+      plan: LogicalPlan,
+      rewrites: PushedFilterRewrites = new PushedFilterRewrites): Unit = {
+    val hasPushedFilters = plan.exists {
+      case relation: StreamingDataSourceV2ScanRelation => 
relation.pushedFilters.nonEmpty
+      case _ => false
+    }
+    if (hasPushedFilters) {
+      // The configuration of the micro-batch, without the rules that infer 
filters, which would
+      // add conditions to those that `impliedBy` gets from the optimizer.
+      lazy val optimizerConf = 
withoutInferredFilters(session.sessionState.conf.clone())
+      // The conjuncts of `condition` once the optimizer of the micro-batch 
optimizes a filter of
+      // `relation` with it, none if it folds into true, which the next 
micro-batches reuse.
+      def optimized(relation: StreamingDataSourceV2ScanRelation)(
+          condition: Expression): Option[Seq[Expression]] = 
rewrites(condition) {
+        SQLConf.withExistingConf(optimizerConf) {
+          session.sessionState.optimizer.execute(

Review Comment:
   1. Done in 95f97ea: the check now optimizes with 
`QueryPlanningTracker.withTracker(new QueryPlanningTracker)`, so its rules no 
longer count in the tracker of the micro-batch. `RuleExecutor`'s metrics are 
global to the JVM (`RuleExecutor.queryExecutionMeter`), so its rules still 
count there, as those of any other optimization in the JVM do.
   2. It is lower now:
      - The configuration of the check is cloned once for each run of the 
query, in `PushedFilterRewrites`, instead of in each micro-batch that misses 
the cache.
      - Since the floating columns get no values (see the thread at L790), the 
optimizer runs at most once for each pushed filter, instead of up to 8 times.
      - It only runs when the plan of the micro-batch does not have the pushed 
filter as it is, and the plan gives values to some of the filter's columns. 
Each run optimizes a single `Filter` over the relation.
   
      With values that change in each micro-batch, it still runs once for each 
such filter in each micro-batch. I think that is acceptable for these rare 
plans.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Strategy.scala:
##########
@@ -268,8 +267,9 @@ class DataSourceV2Strategy(session: SparkSession) extends 
Strategy with Predicat
         StorageFilterPlanning.skipCheckedRows(filtersAbove, storageFilters, 
checked),
         batchExec, !batchExec.supportsColumnar) :: Nil
 
-    // StreamingV2ScanPushDown takes the columns that each scan reads with the 
same match.
-    case ScanOfStream(p, f, r: StreamingDataSourceV2ScanRelation)
+    // StreamingV2ScanPushDown takes what each streaming scan reads with the 
same match, which must
+    // match the same nodes as this one and the next.
+    case PhysicalOperation(p, f, r: StreamingDataSourceV2ScanRelation)

Review Comment:
   Done in 95f97ea: `ScanOfStream` is back, and `readsOfSources` and both cases 
of `DataSourceV2Strategy` match with it, so they match the same nodes by 
construction.



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