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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -97,70 +154,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, 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, AttributeSet] = {
+      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 8ed500a with the first option. The Javadoc of 
`STREAMING_FILTER_PUSHDOWN` now says that Spark may evaluate other conditions 
before the pushed filters in a micro-batch, such as those it infers from them 
(`a > 5` from `a = b AND b > 5`) or an equality with a literal that it moves 
first. Such a condition may drop a row in Spark on which a pushed filter that 
may fail, such as a division with ANSI, fails in the stream. The note of 
`SupportsPushDownV2Filters.pushPredicates` points to it.
   
   The guarantee that remains is the one about the filters the query was 
written with: no pushed filter runs before a filter written before it. I didn't 
add a per-batch order check: the inferred conditions come first in the plans of 
most micro-batches, even with no change in the session, so the check would fail 
those queries rather than the few whose pushed filters can fail on such rows. 
The open item in the PR description now covers this case too, and the filter 
pushdown stays off by default.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +382,199 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
 
   /**
    * Builds the scan of a streaming source, and creates its stream with 
`createStream`. If the
-   * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its 
scan builder supports
-   * the pushdown, and `conf` enables it, the scan only reads the columns of 
`output` that the query
-   * reads (see `requiredColumnsOfSources`). `requiredColumns` is only 
evaluated for such a scan.
-   * Otherwise, the scan reads all the columns of `output`, as the scans of 
streaming queries did
-   * before this pushdown.
+   * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+   * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and 
`conf` enables it,
+   * the scan only reads the columns of `output` that the query reads, or gets 
the filters that the
+   * query applies to all the rows that it reads from the source (see 
`columnsAndFiltersOfSources`).
+   * `reads` is only evaluated for such a scan. Otherwise, the scan reads all 
the columns of
+   * `output` with no filter, as the scans of streaming queries did before 
these pushdowns.
    *
-   * The streams of the scans of a table with the capability return the 
columns of the read
-   * schemas of the scans, in their order, so Spark asks each scan of such a 
table for its read
+   * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING` 
return the columns of the
+   * read schemas of the scans, in their order, so Spark asks each scan of 
such a table for its read
    * schema before it creates the stream, whether the scan reads all the 
columns or not. A pruned
    * scan must read the required columns and only columns of `output`, each 
once and with its
    * type, as `SupportsPushDownRequiredColumns` requires. If the scan builder 
or the scan fails
-   * with the pruning, or the read schema of a pruned scan cannot be read or 
does not follow
-   * `SupportsPushDownRequiredColumns`, a scan of all the columns is built 
instead, from a new scan
-   * builder, as without this pushdown. If the read schema of a scan of all 
the columns of such a
-   * table does not follow the relation, the query fails with 
STREAMING_SCAN_INVALID_READ_SCHEMA,
-   * unless `conf` disables the column pruning, with which the scan node 
outputs the columns of
-   * the relation, as it did before the capability.
+   * with the pushdowns, or the read schema of a pruned scan cannot be read or 
does not follow
+   * `SupportsPushDownRequiredColumns`, the scan is built again from a new 
scan builder: with the
+   * column pruning alone and then with the filters alone if it had both, and 
then with all the
+   * columns and no filter, as without these pushdowns. If the read schema of 
a scan of all the
+   * columns of such a table, with or without filters, does not follow the 
relation, the query
+   * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the 
column pruning, with
+   * which the scan node outputs the columns of the relation, as it did before 
the capability.
    *
    * The stream is created once, from the scan that the source reads, outside 
of the fallback: a
    * stream can start to use the checkpoint of the source, or other resources, 
before it fails, so
-   * a failure of `createStream` fails the query, as it did without this 
pushdown.
+   * a failure of `createStream` fails the query, as it did without these 
pushdowns.
    *
    * @param output the output of the relation of the source, with the metadata 
columns that the
    *               query reads, which the analyzer added to it, so that 
connectors implementing
    *               `SupportsMetadataColumns` include them in `readSchema()`
    * @param conf the configuration of the query
-   * @param requiredColumns the columns that the query reads from the 
relation, or None to read
-   *                        all its columns
+   * @param reads what the query reads from the relation, or None to read all 
its columns with no
+   *              filter
    * @param source the name of the source in the errors of its scan, see 
`sourceName`
    */
   def buildScan(
       table: SupportsRead,
       options: CaseInsensitiveStringMap,
       output: Seq[AttributeReference],
       conf: SQLConf,
-      requiredColumns: => Option[AttributeSet],
+      reads: => Option[Reads],
       source: Seq[String])(
       createStream: Scan => SparkDataStream): StreamingScan = {
-    val returnsReadSchema = 
table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+    val capabilities = table.capabilities()
+    val returnsReadSchema = 
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
     val builder = table.newScanBuilder(options)
     val prunesColumns = returnsReadSchema && 
conf.streamingV2ColumnPruningEnabled &&
       builder.isInstanceOf[SupportsPushDownRequiredColumns]
-    val requiredOutput = (if (prunesColumns) requiredColumns else None)
-      .map(columns => output.filter(columns.contains))
+    val pushesFilters = conf.streamingV2FilterPushdownEnabled &&
+      capabilities.contains(TableCapability.STREAMING_FILTER_PUSHDOWN) &&
+      PushDownUtils.supportsFilters(builder)
+    val known = if (prunesColumns || pushesFilters) reads else None
+    val requiredOutput = known.filter(_ => prunesColumns)
+      .map(r => output.filter(r.requiredColumns.contains))
       .getOrElse(output)
+    // The filters that the scan builder gets in some form, which each 
micro-batch applies first:
+    // the others, such as a filter with a UDF that cannot be translated to a 
filter of the source,
+    // are evaluated after them, as for the scans of batch queries, rather 
than on all the rows of
+    // the source. The filters of a `SupportsPushDownFilters` builder compare 
columns with values,
+    // which cannot fail, so it gets those that all the reads apply, wherever 
they are. The
+    // predicates of a `SupportsPushDownV2Filters` builder and the filters of 
the others may fail
+    // on some rows, as a cast does with ANSI, so they are the leading filters 
of the reads, up to
+    // the first that the builder does not get, in their order, which the 
streams evaluate them in
+    // (see `TableCapability.STREAMING_FILTER_PUSHDOWN`): none runs before a 
filter written before

Review Comment:
   Thanks, the Javadoc in 8ed500a covers this order too: it names an equality 
with a literal that a micro-batch moves first, as 
`ConstantPropagation.moveEqualitiesFirst` of SPARK-61033 does, among the 
conditions that Spark may evaluate before the pushed filters. This is the same 
trade-off as in the thread at L193, so the open item in the PR description now 
names both causes. The branch is merged with master after #59943, before 
3c58e92, and nothing in this PR depends on the order that it changes.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,195 @@ 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(
+            Filter(condition, relation.copy(pushedFilters = Nil)))
+        } match {
+          case Filter(optimizedCondition, _: 
StreamingDataSourceV2ScanRelation) =>
+            Some(splitConjunctivePredicates(optimizedCondition))
+          case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+          case _ => None
+        }
+      }
+      conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) 
=>
+        val implied = impliedBy(conditions, optimized(relation))
+        val results = relation.pushedFilters.map(filter => filter -> 
Try(implied(filter)))
+        val unapplied = results.collect {
+          case (filter, result) if !result.getOrElse(false) => filter
+        }
+        if (unapplied.nonEmpty) {
+          throw QueryExecutionErrors.streamingScanFiltersChangedError(
+            sourceName(relation.relation.table, relation.catalog, 
relation.identifier),
+            unapplied.map(_.sql),
+            results.collectFirst { case (_, Failure(e)) => e }.orNull)
+        }
+      }
+    }
+  }
+
+  /**
+   * The conditions that the optimizer of a micro-batch rewrote for 
`checkPushedFilters`, by the
+   * condition canonicalized, which a streaming query keeps for its 
micro-batches: they check the
+   * same filters with the same values, which its optimizer rewrites in the 
same way. A query that
+   * restarts gets a new one, with the configuration that it restarts with.
+   */
+  class PushedFilterRewrites {
+    private val rewrites: Cache[Expression, Option[Seq[Expression]]] =
+      CacheBuilder.newBuilder().maximumSize(100).build[Expression, 
Option[Seq[Expression]]]()
+
+    def apply(condition: Expression)(
+        rewrite: => Option[Seq[Expression]]): Option[Seq[Expression]] = {
+      val key = condition.canonicalized
+      Option(rewrites.getIfPresent(key)).getOrElse {
+        val rewritten = rewrite
+        rewrites.put(key, rewritten)
+        rewritten
+      }
+    }
+  }
+
+  // Each occurrence of a streaming relation in `plan`, with the deterministic 
conditions that the
+  // plan applies to all its rows, given `above`, those that it applies to all 
the rows of `plan`:
+  // the conditions of the filters over it, through the projections, with the 
aliases of these in
+  // place of their names, as `PhysicalOperation` finds the filters of a 
relation. The conditions
+  // over a filter or a projection that is not deterministic do not hold for 
the rows that it gets,
+  // nor do the conjuncts of such a filter after its first nondeterministic 
one, which sees the rows
+  // that these drop: only the leading deterministic ones, as when the query 
starts.
+  private def conditionsOverRelations(
+      plan: LogicalPlan,
+      above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation, 
Seq[Expression])] = {
+    plan match {
+      case relation: StreamingDataSourceV2ScanRelation => Seq(relation -> 
above)
+      case Filter(condition, child) =>
+        val conditions = splitConjunctivePredicates(condition)
+        val applied = if (condition.deterministic) {
+          conditions ++ above
+        } else {
+          conditions.takeWhile(_.deterministic)
+        }
+        conditionsOverRelations(child, applied)
+      case Project(projectList, child) if projectList.forall(_.deterministic) 
=>
+        val aliases = getAliasMap(projectList)
+        conditionsOverRelations(child, above.map(replaceAlias(_, aliases)))
+      case other => other.children.flatMap(conditionsOverRelations(_, Nil))
+    }
+  }
+
+  /**
+   * Returns whether a filter is implied by `facts`, the deterministic 
conditions that hold for all
+   * the rows that a plan keeps from a relation. No row passes a fact that is 
false or null, which
+   * implies any filter. Otherwise, the facts imply a filter if they have it, 
or its conjuncts, or
+   * one of its disjuncts, also once the columns that the facts make equal to 
literals have these
+   * values in it, and `optimize`, the optimizer of the micro-batch, rewrote 
it. The optimizer of a
+   * micro-batch puts these values in place of the columns in its filters (see
+   * `ConstantPropagation`), e.g. with an equality that it infers through a 
join, and rewrites the
+   * filters with the other rules of the same batch, so that `id > 1` becomes 
true with `id = 5`,
+   * and `CAST(extra AS BIGINT) < id` becomes `extra < 5`. The values replace 
their columns for the
+   * types whose equal values are the same (see `hasExactEquality`), and for 
the floating types,
+   * whose equal values only differ for 0.0 and -0.0, and for NaN values, 
which Spark evaluates
+   * alike: a column equal to zero is 0.0 or -0.0, so the filter must hold 
with each, as
+   * `floor(d) >= 0` does, unlike `CAST(d AS STRING) = '0.0'`. A string of a 
collation that is not
+   * binary gets no value, also where `ConstantPropagation` puts it in a 
comparison of two columns
+   * of this collation. This may miss that the facts imply a filter, which 
fails the micro-batch,
+   * but never finds that they imply a filter that they do not imply, as long 
as the rules of the
+   * optimizer keep what the filters mean.
+   */
+  private def impliedBy(
+      facts: Seq[Expression],
+      optimize: Expression => Option[Seq[Expression]]): Expression => Boolean 
= {
+    val noRow = facts.exists {
+      case Literal(false, BooleanType) | Literal(null, _) => true
+      case _ => false
+    }
+    val known = ExpressionSet(facts)
+    def holds(condition: Expression): Boolean = known.contains(condition) || 
(condition match {
+      case TrueLiteral => true
+      case And(left, right) => holds(left) && holds(right)
+      case Or(left, right) => holds(left) || holds(right)
+      case _ => false
+    })
+    val values = AttributeMap(facts.collect {
+      case EqualTo(column: Attribute, value: Literal) => column -> value
+      case EqualTo(value: Literal, column: Attribute) => column -> value
+      case EqualNullSafe(column: Attribute, value: Literal) => column -> value
+      case EqualNullSafe(value: Literal, column: Attribute) => column -> value
+    }.filter { case (column, value) =>

Review Comment:
   Done in 8ed500a: a struct or an array whose floating fields or elements hold 
no 0.0 or -0.0 now gets its value. Its other equal values are the same, apart 
from NaN values, which Spark evaluates alike (`hasExactEquality(..., floating = 
true)` and `hasNoFloatingZero`). A value with a zero in such a field still gets 
none, since trying both signs inside a nested value would multiply the cases. 
The test of the folded filters now also joins on a `struct<a: double>` key with 
`named_struct('a', 1.0D)`, and the test of the check covers the struct of 1.0 
and of 0.0.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +382,199 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
 
   /**
    * Builds the scan of a streaming source, and creates its stream with 
`createStream`. If the
-   * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its 
scan builder supports
-   * the pushdown, and `conf` enables it, the scan only reads the columns of 
`output` that the query
-   * reads (see `requiredColumnsOfSources`). `requiredColumns` is only 
evaluated for such a scan.
-   * Otherwise, the scan reads all the columns of `output`, as the scans of 
streaming queries did
-   * before this pushdown.
+   * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+   * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and 
`conf` enables it,
+   * the scan only reads the columns of `output` that the query reads, or gets 
the filters that the
+   * query applies to all the rows that it reads from the source (see 
`columnsAndFiltersOfSources`).
+   * `reads` is only evaluated for such a scan. Otherwise, the scan reads all 
the columns of
+   * `output` with no filter, as the scans of streaming queries did before 
these pushdowns.
    *
-   * The streams of the scans of a table with the capability return the 
columns of the read
-   * schemas of the scans, in their order, so Spark asks each scan of such a 
table for its read
+   * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING` 
return the columns of the
+   * read schemas of the scans, in their order, so Spark asks each scan of 
such a table for its read
    * schema before it creates the stream, whether the scan reads all the 
columns or not. A pruned
    * scan must read the required columns and only columns of `output`, each 
once and with its
    * type, as `SupportsPushDownRequiredColumns` requires. If the scan builder 
or the scan fails
-   * with the pruning, or the read schema of a pruned scan cannot be read or 
does not follow
-   * `SupportsPushDownRequiredColumns`, a scan of all the columns is built 
instead, from a new scan
-   * builder, as without this pushdown. If the read schema of a scan of all 
the columns of such a
-   * table does not follow the relation, the query fails with 
STREAMING_SCAN_INVALID_READ_SCHEMA,
-   * unless `conf` disables the column pruning, with which the scan node 
outputs the columns of
-   * the relation, as it did before the capability.
+   * with the pushdowns, or the read schema of a pruned scan cannot be read or 
does not follow
+   * `SupportsPushDownRequiredColumns`, the scan is built again from a new 
scan builder: with the
+   * column pruning alone and then with the filters alone if it had both, and 
then with all the
+   * columns and no filter, as without these pushdowns. If the read schema of 
a scan of all the
+   * columns of such a table, with or without filters, does not follow the 
relation, the query
+   * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the 
column pruning, with
+   * which the scan node outputs the columns of the relation, as it did before 
the capability.
    *
    * The stream is created once, from the scan that the source reads, outside 
of the fallback: a
    * stream can start to use the checkpoint of the source, or other resources, 
before it fails, so
-   * a failure of `createStream` fails the query, as it did without this 
pushdown.
+   * a failure of `createStream` fails the query, as it did without these 
pushdowns.
    *
    * @param output the output of the relation of the source, with the metadata 
columns that the
    *               query reads, which the analyzer added to it, so that 
connectors implementing
    *               `SupportsMetadataColumns` include them in `readSchema()`
    * @param conf the configuration of the query
-   * @param requiredColumns the columns that the query reads from the 
relation, or None to read
-   *                        all its columns
+   * @param reads what the query reads from the relation, or None to read all 
its columns with no
+   *              filter
    * @param source the name of the source in the errors of its scan, see 
`sourceName`
    */
   def buildScan(
       table: SupportsRead,
       options: CaseInsensitiveStringMap,
       output: Seq[AttributeReference],
       conf: SQLConf,
-      requiredColumns: => Option[AttributeSet],
+      reads: => Option[Reads],
       source: Seq[String])(
       createStream: Scan => SparkDataStream): StreamingScan = {
-    val returnsReadSchema = 
table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+    val capabilities = table.capabilities()
+    val returnsReadSchema = 
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
     val builder = table.newScanBuilder(options)
     val prunesColumns = returnsReadSchema && 
conf.streamingV2ColumnPruningEnabled &&
       builder.isInstanceOf[SupportsPushDownRequiredColumns]
-    val requiredOutput = (if (prunesColumns) requiredColumns else None)
-      .map(columns => output.filter(columns.contains))
+    val pushesFilters = conf.streamingV2FilterPushdownEnabled &&
+      capabilities.contains(TableCapability.STREAMING_FILTER_PUSHDOWN) &&
+      PushDownUtils.supportsFilters(builder)
+    val known = if (prunesColumns || pushesFilters) reads else None
+    val requiredOutput = known.filter(_ => prunesColumns)
+      .map(r => output.filter(r.requiredColumns.contains))
       .getOrElse(output)
+    // The filters that the scan builder gets in some form, which each 
micro-batch applies first:
+    // the others, such as a filter with a UDF that cannot be translated to a 
filter of the source,
+    // are evaluated after them, as for the scans of batch queries, rather 
than on all the rows of
+    // the source. The filters of a `SupportsPushDownFilters` builder compare 
columns with values,
+    // which cannot fail, so it gets those that all the reads apply, wherever 
they are. The
+    // predicates of a `SupportsPushDownV2Filters` builder and the filters of 
the others may fail
+    // on some rows, as a cast does with ANSI, so they are the leading filters 
of the reads, up to
+    // the first that the builder does not get, in their order, which the 
streams evaluate them in
+    // (see `TableCapability.STREAMING_FILTER_PUSHDOWN`): none runs before a 
filter written before
+    // it. `PushDownUtils.pushFilters` decides which filters the builder gets 
in the same way.
+    def gets(filter: Expression): Boolean = PushDownUtils.getsFilter(builder, 
filter)
+    val filters = known.filter(_ => pushesFilters)
+      .map { r =>
+        builder match {
+          case _: SupportsPushDownFilters =>
+            DataSourceStrategy.normalizeExprs(r.filtersInAnyOrder, 
output).filter(gets)
+          case _ =>
+            DataSourceStrategy.normalizeExprs(r.filters, 
output).takeWhile(gets)
+        }
+      }
+      .getOrElse(Nil)
 
-    // Builds the scan of `columns` with `builder`.
-    def build(builder: ScanBuilder, columns: Seq[AttributeReference]): Scan = {
+    // Builds the scan of `columns` with `builder`, once it pushed `filters` 
down to it.
+    def build(
+        builder: ScanBuilder,
+        columns: Seq[AttributeReference],
+        filters: Seq[Expression]): Scan = {
+      if (filters.nonEmpty) {
+        // Each micro-batch checks that its plan applies these filters to all 
the rows that it
+        // reads from the source, see `checkPushedFilters`, so the scan may 
apply any of them, in
+        // any form.
+        val (pushed, _) = PushDownUtils.pushFilters(builder, filters, 
partitionFields = None)
+        val taken = pushed.fold(_.mkString(", "), _.mkString(", "))
+        logInfo(log"The scan builder of the streaming table " +
+          log"${MDC(LogKeys.STREAMING_TABLE, table)} took the filters " +
+          log"${MDC(LogKeys.PUSHED_FILTERS, taken)}.")
+      }
       builder match {
         case pruning: SupportsPushDownRequiredColumns =>
           pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
         case _ =>
       }
       builder.build()
     }
-    // The scan of all the columns, as without this pushdown, and the columns 
that its scan node
-    // outputs.
-    def scanOfAllColumns(builder: ScanBuilder): (Scan, 
Seq[AttributeReference]) = {
-      val scan = build(builder, output)
+    // The columns that the scan node of `scan`, a scan of all the columns, 
outputs.
+    def outputOfAllColumns(scan: Scan): Seq[AttributeReference] = {
       if (returnsReadSchema) {
         // The readers of the stream return the columns of the read schema, so 
a read schema that
         // does not follow the relation fails the query when it starts: the 
scan node cannot
         // output the columns of the relation in its place. Without the column 
pruning, the scan
         // node outputs them instead, as it did before the capability.
-        def invalid(reason: String, cause: Throwable): (Scan, 
Seq[AttributeReference]) = {
+        def invalid(reason: String, cause: Throwable): Seq[AttributeReference] 
= {
           if (conf.streamingV2ColumnPruningEnabled) {
             throw 
QueryExecutionErrors.streamingScanInvalidReadSchemaError(source, reason, cause)
           }
           logWarning(log"The read schema of the scan of all the columns of the 
streaming table " +
             log"${MDC(LogKeys.STREAMING_TABLE, table)} ${MDC(LogKeys.REASON, 
reason)}. Its scan " +
             log"node outputs the columns of the relation, as the column 
pruning is disabled.")
-          scan -> output
+          output
         }
         Try(readOutput(scan.readSchema(), output, output)) match {
-          case Success(Right(columns)) => scan -> columns
+          case Success(Right(columns)) => columns
           case Success(Left(reason)) => invalid(reason, null)
           case Failure(e) => invalid(s"could not be read: $e", e)
         }
       } else {
-        scan -> output
+        output
       }
     }
-
-    val (scan, scanOutput) = if (requiredOutput.length == output.length) {
-      scanOfAllColumns(builder)
-    } else {
-      // Logs why the pruned scan could not be built, and builds the scan of 
all the columns
-      // instead.
-      def fallBack(reason: String, cause: Option[Throwable]): (Scan, 
Seq[AttributeReference]) = {
-        val message = log"The scan of the streaming table " +
-          log"${MDC(LogKeys.STREAMING_TABLE, table)} could not be built to 
read only the columns " +
-          log"${MDC(LogKeys.COLUMN_NAMES, 
requiredOutput.map(_.name).mkString(", "))}: " +
-          log"${MDC(LogKeys.REASON, reason)}. It reads all the columns 
instead."
-        cause match {
-          case Some(e) => logWarning(message, e)
-          case None => logWarning(message)
-        }
-        scanOfAllColumns(table.newScanBuilder(options))
+    // The scan of all the columns with no filter, as without these pushdowns, 
and the columns that
+    // its scan node outputs.
+    def scanOfAllColumns(builder: ScanBuilder): (Scan, 
Seq[AttributeReference]) = {
+      val scan = build(builder, output, Nil)
+      scan -> outputOfAllColumns(scan)
+    }
+    // The scan of `columns` with `filters` and the columns that its scan node 
outputs, or why its
+    // read schema does not follow `SupportsPushDownRequiredColumns`. A scan 
of all the columns
+    // with filters is checked as one with no filter, outside of the fallback 
(see `firstScan`), as
+    // its read schema fails the query in the same way: the columns of such a 
scan are None.
+    def scanWith(
+        builder: ScanBuilder,
+        columns: Seq[AttributeReference],
+        filters: Seq[Expression]): Either[String, (Scan, 
Option[Seq[AttributeReference]])] = {
+      val scan = build(builder, columns, filters)
+      if (!returnsReadSchema) {
+        Right(scan -> Some(output))
+      } else if (columns.length == output.length) {
+        Right(scan -> None)
+      } else {
+        readOutput(scan.readSchema(), output, columns).map(columns => scan -> 
Some(columns))
       }
-      // The pruned scan and its columns, or why its read schema does not 
follow
-      // `SupportsPushDownRequiredColumns`.
-      Try {
-        val scan = build(builder, requiredOutput)
-        readOutput(scan.readSchema(), output, requiredOutput).map(scan -> _)
-      } match {
-        case Success(Right(pruned)) => pruned
-        case Success(Left(reason)) => fallBack(s"its read schema $reason", 
None)
-        case Failure(e) => fallBack(s"it failed with $e", Some(e))
+    }
+    // The columns and the filters of a scan, in the warnings.
+    def pushdowns(columns: Seq[AttributeReference], filters: Seq[Expression]): 
String = {
+      val names = if (columns.length < output.length) 
columns.map(_.name).mkString(", ") else "all"
+      val sqls = if (filters.isEmpty) "none" else 
filters.map(_.sql).mkString(", ")
+      s"(columns: $names, filters: $sqls)"
+    }
+    // Tries the scans of `attempts`, the columns and the filters of each, in 
order, each from a
+    // new scan builder after the first, and then the scan of all the columns 
with no filter.
+    def firstScan(
+        attempts: Seq[(Seq[AttributeReference], Seq[Expression])],
+        builder: ScanBuilder): ((Scan, Seq[AttributeReference]), 
Seq[Expression]) = {
+      attempts match {
+        case Seq() => scanOfAllColumns(builder) -> Nil
+        case (columns, filters) +: rest =>
+          val (reason, cause) = Try(scanWith(builder, columns, filters)) match 
{
+            case Success(Right((scan, scanOutput))) =>
+              return (scan -> scanOutput.getOrElse(outputOfAllColumns(scan))) 
-> filters
+            case Success(Left(reason)) => s"its read schema $reason" -> None
+            case Failure(e) => s"it failed with $e" -> Some(e)
+          }
+          val (nextColumns, nextFilters) = rest.headOption.getOrElse(output -> 
Nil)
+          val message = log"The scan of the streaming table " +
+            log"${MDC(LogKeys.STREAMING_TABLE, table)} could not be built with 
" +
+            log"${MDC(LogKeys.OLD_VALUE, pushdowns(columns, filters))}: " +
+            log"${MDC(LogKeys.REASON, reason)}. Trying " +
+            log"${MDC(LogKeys.NEW_VALUE, pushdowns(nextColumns, nextFilters))} 
next."
+          cause match {
+            case Some(e) => logWarning(message, e)
+            case None => logWarning(message)
+          }
+          firstScan(rest, table.newScanBuilder(options))
       }
     }
+
+    val ((scan, scanOutput), pushedFilters) =
+      if (requiredOutput.length == output.length && filters.isEmpty) {
+        scanOfAllColumns(builder) -> Nil
+      } else {
+        // When the filters fail, the column pruning alone may still work, and 
when the column
+        // pruning fails, the filters alone.
+        val fewerPushdowns = if (filters.nonEmpty && requiredOutput.length < 
output.length) {
+          Seq(requiredOutput -> Nil, output -> filters)

Review Comment:
   Done in 8ed500a: after a read schema that doesn't follow the column pruning, 
`firstScan` now skips the remaining attempts with the same columns, so the next 
one is `(output, filters)`. The test with `SIMULATE_INCOMPLETE_COLUMN_PRUNING` 
now checks that there's a single warning, which tries the scan of all the 
columns with the filter next.
   



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