dongjoon-hyun commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4515255492


##########
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(
+            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(

Review Comment:
   Since the scan cannot drop a pushed filter once the query has started, a 
micro-batch for which `impliedBy` cannot prove a pushed filter fails here, and 
so does every following micro-batch. The only recovery is to restart the query 
with `spark.sql.streaming.v2FilterPushdown.enabled=false`.
   
   As the doc of `impliedBy` says, this can happen even when the filter is 
actually implied. For example, with `stream.join(static.where("k = 
named_struct('a', 0.0)"), $"s" === $"k")` and the pushed filter `s.a > -1`, the 
micro-batch infers `s = named_struct('a', 0.0)` and `ConstantPropagation` folds 
`s.a > -1` into true, but `hasNoFloatingZero` gives `s` no value, so the check 
fails. The same happens with more than 3 floating columns equal to zero, or 
with strings of a non-binary collation.
   
   Could we avoid this permanent failure mode, e.g., by not pushing at startup 
the filters on the columns that `impliedBy` cannot give values to? At the very 
least, it would be good to document it in the config doc.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -21,67 +21,126 @@ import scala.collection.mutable
 import scala.util.{Failure, Success, Try}
 import scala.util.control.NonFatal
 
+import com.google.common.cache.{Cache, CacheBuilder}
+
 import org.apache.spark.SparkException
 import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
-import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, AttributeSet, Cast, Expression, Generator, NamedExpression, 
OuterReference, SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, EqualNullSafe, EqualTo, 
Expression, ExpressionSet, ExprUtils, Generator, Literal, Or, OuterReference, 
PredicateHelper, SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.Literal.TrueLiteral
 import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
-import org.apache.spark.sql.catalyst.optimizer.ReplaceExpressions
+import org.apache.spark.sql.catalyst.optimizer.{CollapseProject, 
InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions}
 import org.apache.spark.sql.catalyst.planning.PhysicalOperation
-import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, LeafNode, 
LogicalPlan, Statistics}
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, 
Statistics}
 import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
 import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
 import org.apache.spark.sql.catalyst.types.DataTypeUtils
-import org.apache.spark.sql.catalyst.util.{truncatedString, CharVarcharUtils}
+import org.apache.spark.sql.catalyst.util.{truncatedString, ArrayData, 
CharVarcharUtils}
 import org.apache.spark.sql.classic.SparkSession
 import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, 
SupportsRead, Table, TableCapability}
-import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, 
SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, 
SupportsPushDownFilters, SupportsPushDownRequiredColumns}
 import org.apache.spark.sql.connector.read.streaming.SparkDataStream
 import org.apache.spark.sql.errors.QueryExecutionErrors
 import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.execution.datasources.v2.{PushDownUtils, 
StreamingDataSourceV2ScanRelation}
 import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
 import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.types.{AnyTimestampNanoType, AnyTimeType, 
ArrayType, BinaryType, BooleanType, DataType, DatetimeType, DateType, 
DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, 
StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, 
YearMonthIntervalType}
 import org.apache.spark.sql.util.CaseInsensitiveStringMap
-import org.apache.spark.util.Utils
 
 /**
- * Pushes the top-level columns that the optimized plan of a streaming query 
reads from each Data
- * Source V2 streaming source down to the scan of the source, as 
`V2ScanRelationPushDown` does for
- * the scans of batch queries, if the table of the source has the capability
- * `STREAMING_COLUMN_PRUNING`.
+ * Pushes the top-level columns and the filters that the optimized plan of a 
streaming query reads
+ * from each Data Source V2 streaming source down to the scan of the source, as
+ * `V2ScanRelationPushDown` does for the scans of batch queries, if the table 
of the source has the
+ * capability `STREAMING_COLUMN_PRUNING` or `STREAMING_FILTER_PUSHDOWN`.
  *
  * The stream of a source is created from its scan, and has to exist before 
any micro-batch is
  * planned, so the scan is built when the query starts. The query is optimized 
once at that point,
  * by the optimizer of its micro-batches and with their configuration, and the 
scan of each source
- * reads the columns that the planner takes from the optimized plan for the 
relation of the source
- * (see `DataSourceV2Strategy`): those of the projections and the filters over 
each occurrence of
- * the relation.
+ * gets what the planner takes from the optimized plan for the relation of the 
source (see
+ * `DataSourceV2Strategy`): the projections and the filters over each 
occurrence of the relation.
  *
- * The plan of each micro-batch is the one without this pushdown: the 
optimizer keeps deciding
- * which columns every operator gets, and in which order, including the 
stateful ones. Only the
- * scan node of the physical plan outputs the columns that the scan reads, and 
the planner checks
- * that the micro-batch reads no other column of the relation. A scan cannot 
read other columns
- * once its stream exists, so a micro-batch that does fails with 
STREAMING_SCAN_MISSING_COLUMNS,
- * as when the configuration of the optimizer changes in the session of the 
query after it starts
- * so that its plan reads other columns of a source.
+ * The scan may drop the rows that fail the filters that its builder got, so 
the optimized plan of
+ * each micro-batch must apply them to all the rows that it reads from the 
source, which it checks
+ * before it reads them (see `checkPushedFilters`). Otherwise, it is the plan 
without these
+ * pushdowns: the optimizer keeps deciding which columns every operator gets, 
and in which order,
+ * including the stateful ones. Only the scan node of the physical plan 
outputs the columns that
+ * the scan reads, and the planner checks that the micro-batch reads no other 
column of the
+ * relation. A scan cannot read other columns once its stream exists, so a 
micro-batch that does
+ * fails with STREAMING_SCAN_MISSING_COLUMNS, as when the configuration of the 
optimizer changes in
+ * the session of the query after it starts so that its plan reads other 
columns of a source.
  *
  * The other operations that the scans of batch queries can apply, such as 
aggregates and limits,
  * apply to the data of all the micro-batches of a streaming query, which the 
scan of a micro-batch
  * does not read, so they are not pushed down.
  */
-private[sql] object StreamingV2ScanPushDown extends Logging {
+private[sql] object StreamingV2ScanPushDown
+  extends Logging with PredicateHelper with AliasHelper {
+
+  /**
+   * What the optimized plan of a streaming query reads from a streaming 
relation.
+   *
+   * @param requiredColumns the columns of the relation that the plan reads
+   * @param occurrenceFilters for each occurrence of the relation, its filters 
in the order in which
+   *                          the plan evaluates them, up to the first 
nondeterministic one: a
+   *                          filter pushed before it would change how many 
times it is evaluated
+   */
+  case class Reads(requiredColumns: AttributeSet, occurrenceFilters: 
Seq[Seq[Expression]]) {
+
+    /**
+     * The filters that every occurrence evaluates first, in the same order: 
the longest common
+     * prefix of the leading pushable filters of the occurrences. The scan may 
evaluate the pushed
+     * filters first, on the rows of the source, so a pushed filter that may 
fail on some rows, as
+     * a cast or a division does under ANSI, or `raise_error`, must not see a 
row that a filter
+     * written before it drops. These are the filters for a scan builder whose 
filters may fail.
+     */
+    def filters: Seq[Expression] = {
+      occurrenceFilters.map(_.takeWhile(isPushable)).reduceOption { (left, 
right) =>
+        // As `ExpressionSet` compares them, which tells 0.0 from -0.0, unlike 
`semanticEquals`.
+        left.zip(right).takeWhile { case (l, r) => 
ExpressionSet(Seq(l)).contains(r) }.map(_._1)

Review Comment:
   `ExpressionSet` tells `0.0` from `-0.0` here only because their 
`Literal.hashCode` differs (`java.lang.Double.hashCode` of different bits), 
while `Literal.equals` considers them equal (`a == b` on boxed numbers is a 
numeric comparison in Scala). The same applies to `filtersInAnyOrder`, `holds` 
in `impliedBy`, and the keys of `PushedFilterRewrites`.
   
   So the correctness depends on an implementation detail: the hash codes of 
the two expressions must never collide, and `Literal.hashCode` must not be 
normalized for `-0.0` someday, which would be a natural change to make it 
consistent with `equals`. Otherwise, filters whose results depend on the sign 
of a zero, e.g., `atan2(0.0, x) > 0` and `atan2(-0.0, x) > 0` for a negative 
`x`, would be the same filter here, and a scan could silently drop rows that 
another read must keep. The test `push down no filter that the reads of a 
source apply with another zero` would catch a change of `Literal.hashCode`, but 
not a collision. Could we compare them explicitly instead, e.g., with a helper 
that also compares the raw bits of the floating literals?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +384,207 @@ 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, unless the read schema of the pruned scan did not 
follow it, 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 the streams 
may apply first, to
+    // the rows of the source: the others, such as a filter with a UDF that 
cannot be translated
+    // to a filter of the source, are evaluated after the scan, as for the 
scans of batch queries.
+    // 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.
+    // These builders also get the other filters that all the reads apply and 
that cannot fail
+    // (see `ExprUtils.canEvaluateUnconditionally`), wherever they are, after 
the leading ones.
+    // `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 _ =>
+            val leading = DataSourceStrategy.normalizeExprs(r.filters, 
output).takeWhile(gets)
+            val pushed = ExpressionSet(leading)
+            leading ++ DataSourceStrategy.normalizeExprs(r.filtersInAnyOrder, 
output).filter {
+              filter => !pushed.contains(filter) && 
ExprUtils.canEvaluateUnconditionally(filter) &&
+                gets(filter)
+            }
+        }
+      }
+      .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 (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, next) = Try(scanWith(builder, columns, filters)) 
match {
+            case Success(Right((scan, scanOutput))) =>
+              return (scan -> scanOutput.getOrElse(outputOfAllColumns(scan))) 
-> filters

Review Comment:
   When the query reads all the columns with filters, `scanWith` returns 
`Right(scan -> None)` without calling `readSchema()`, and 
`outputOfAllColumns(scan)` runs here, outside of the `Try`. Since 
`fewerPushdowns` is empty in this case, a `readSchema()` that throws because of 
the pushed filters goes to `invalid()` and fails the query with 
`STREAMING_SCAN_INVALID_READ_SCHEMA`, instead of retrying with `(output, Nil)`.
   
   I see that the comment on `scanWith` says a scan of all the columns with 
filters is checked outside of the fallback because its read schema fails the 
query in the same way. That holds for a read schema that does not follow the 
relation (`Left`), but a `readSchema()` that throws (`Failure`) may be caused 
by the filters themselves. Could we fall back to the scan with no filter in 
that case too?



##########
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:
   The simulation of the streams dropping rows (`SIMULATE_STREAMING_FILTERS`) 
only applies to the V1 filters of `InMemoryBatchScan`. `FilterStreamTable` in 
`StreamingV2ScanPushDownSuite`, which covers the `SupportsPushDownV2Filters` 
and `SupportsPushDownCatalystFilters` builders, returns all the rows. So if the 
check wrongly accepted a plan that does not apply a pushed V2 predicate or 
Catalyst filter, `CheckAnswer` would still pass. Could the V2/Catalyst fixtures 
also drop the rows that fail the pushed filters, so that these paths are 
covered end to end?



##########
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:
   `withoutInferredFilters` is applied here regardless of whether the filter 
pushdown is used, i.e., also when no source has `STREAMING_FILTER_PUSHDOWN` or 
`spark.sql.streaming.v2FilterPushdown.enabled` is false. Before this PR, the 
startup optimization for the column pruning (#59943) ran the same rules as the 
micro-batches, as the doc of `spark.sql.streaming.v2ColumnPruning.enabled` says 
("as it optimizes each micro-batch"). Now a query that only uses the column 
pruning is optimized at startup with a different set of rules than its 
micro-batches, and a plan difference caused by the inference rules could lead 
to `STREAMING_SCAN_MISSING_COLUMNS`. Could we exclude these rules only when the 
filters may be pushed down?



##########
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:
   Two concerns about this check in the planning of each micro-batch:
   
   1. This `optimizer.execute` runs within the OPTIMIZATION phase of the 
micro-batch's `IncrementalExecution`, so its rules are recorded in the same 
`QueryPlanningTracker` and in the `RuleExecutor` metrics, which inflates the 
numbers of the micro-batch. Could we run it with a separate tracker, e.g., 
`QueryPlanningTracker.withTracker(new QueryPlanningTracker)`?
   2. When the values that the facts give to the columns change between 
micro-batches (e.g., a literal from `current_timestamp()` that reaches the 
stream side through a join), `PushedFilterRewrites` never hits. Then each 
micro-batch clones the whole session conf (`optimizerConf`) and runs the 
optimizer up to 8 times (once per subset of the zeros) per pushed filter, 
synchronously during planning. Is this overhead acceptable, or could we reduce 
it?



##########
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(
+            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,
+            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. A conjunct
+  // goes through a projection only if `CollapseProject` would inline its 
aliases, as
+  // `PhysicalOperation` does, so that an expensive alias used more than once 
is not copied.
+  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)
+        val alwaysInline = 
SQLConf.get.getConf(SQLConf.COLLAPSE_PROJECT_ALWAYS_INLINE)
+        val inlined = above.filter { condition =>
+          CollapseProject.canCollapseExpressions(Seq(condition), aliases, 
alwaysInline)
+        }
+        conditionsOverRelations(child, inlined.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 given the values that the facts give to its 
columns, equal to
+   * literals: the filter holds if it evaluates to true with these values when 
all its columns
+   * have one, and otherwise if `optimize`, the optimizer of the micro-batch, 
rewrites the filter
+   * with the equalities of these values into conditions that hold, or 
evaluate to true with the
+   * values. The optimizer of a micro-batch puts these values in place of the 
columns in its
+   * filters (see `ConstantPropagation`), wherever no expression that may fail 
keeps them, 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 `(a + 
b > 3 AND b > 0) OR
+   * a > 9` becomes `a + b > 3 OR a > 9` with `b = 1`. Only the columns of the 
types whose equal
+   * values are the same get values (see `hasExactEquality`): for the floating 
types, 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'`, and a struct or an array with 
floating fields or elements
+   * only gets its value if it has no 0.0 or -0.0 in them. 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) =>
+      DataType.equalsIgnoreNullability(column.dataType, value.dataType) &&
+        hasExactEquality(column.dataType) &&
+        (isFloating(column.dataType) || hasNoFloatingZero(value.value, 
value.dataType))
+    })
+    filter => noRow || holds(filter) || {
+      val columns = filter.references.toSeq.filter(values.contains)
+      // The columns of the filter that are equal to zero, which is 0.0 or 
-0.0 in each row.
+      val zeros = columns.filter(column => 
isFloatingZero(values(column))).toSet
+      val zeroColumns = AttributeSet(zeros)
+      columns.nonEmpty && zeros.size <= 3 && zeros.subsets().forall { negative 
=>

Review Comment:
   The enumeration of the signs of the zeros (`zeros.subsets()`, up to 3 
columns) and the check of the zeros inside structs and arrays 
(`hasNoFloatingZero`) add quite a lot of special handling (`isFloating`, 
`isFloatingZero`, `floatingZero`, `hasNoFloatingZero`, the subset loop, and 
more cache keys) for rare cases. Giving no value to the floating columns (and 
to the structs and arrays with floating fields or elements) would be equally 
safe, and would only make the check fail conservatively in these cases. Given 
the comment on L676, this is a tradeoff, though: if the permanent failure is 
addressed, would it be worth simplifying this?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -311,7 +314,8 @@ class MicroBatchExecution(
                 sourceIdentifyingName
               )
             StreamingDataSourceV2ScanRelation(relation, streamingScan.scan, 
output,

Review Comment:
   This construction of a `StreamingDataSourceV2ScanRelation` from the result 
of `buildScan` (`scanOutput`, `pushedFilters`) is duplicated in 
`ContinuousExecution`, and this PR adds one more field to both copies. If a 
field is added to `StreamingScan` later and only one copy is updated, e.g., 
`pushedFilters` is missed in one mode, the check would be skipped 
(`checkPushedFilters` only checks the relations with non-empty `pushedFilters`) 
while the scan still drops rows. Could we add a helper that builds the relation 
from a `StreamingScan` and use it in both places?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PushDownUtils.scala:
##########
@@ -43,6 +43,30 @@ import org.apache.spark.util.collection.Utils
 
 object PushDownUtils extends Logging {
 
+  /** Returns whether [[pushFilters]] may push filters down to `scanBuilder`. 
*/
+  def supportsFilters(scanBuilder: ScanBuilder): Boolean = scanBuilder match {
+    case _: SupportsPushDownFilters | _: SupportsPushDownV2Filters |
+        _: SupportsPushDownCatalystFilters => true
+    case _ => false
+  }
+
+  /**
+   * Returns whether [[pushFilters]] gives `filter` to `scanBuilder` in some 
form: whether it
+   * translates it to a data source filter or predicate, or whether it is 
deterministic for a
+   * [[SupportsPushDownCatalystFilters]] builder. The other filters are only 
evaluated after the
+   * scan. This must decide as [[pushFilters]] does.
+   */
+  def getsFilter(scanBuilder: ScanBuilder, filter: Expression): Boolean = 
scanBuilder match {

Review Comment:
   `getsFilter` duplicates the routing and translation decisions of 
`pushFilters`, and the two are kept in sync only by "This must decide as 
[[pushFilters]] does". If `pushFilters` changes later (e.g., another condition 
before it translates a filter to a V2 predicate) without `getsFilter`, 
`takeWhile(gets)` in `StreamingV2ScanPushDown.buildScan` would not stop at a 
filter that the builder does not actually get. Then a filter that may fail 
(e.g., an ANSI cast) after it could be pushed, and the stream could evaluate it 
on a row that the previous filter drops. Could `pushFilters` use `getsFilter` 
itself (or a shared helper) to decide which filters it gives to the builder, so 
that they cannot drift apart?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +384,207 @@ 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, unless the read schema of the pruned scan did not 
follow it, 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 the streams 
may apply first, to
+    // the rows of the source: the others, such as a filter with a UDF that 
cannot be translated
+    // to a filter of the source, are evaluated after the scan, as for the 
scans of batch queries.
+    // 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.
+    // These builders also get the other filters that all the reads apply and 
that cannot fail
+    // (see `ExprUtils.canEvaluateUnconditionally`), wherever they are, after 
the leading ones.
+    // `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 _ =>
+            val leading = DataSourceStrategy.normalizeExprs(r.filters, 
output).takeWhile(gets)
+            val pushed = ExpressionSet(leading)
+            leading ++ DataSourceStrategy.normalizeExprs(r.filtersInAnyOrder, 
output).filter {
+              filter => !pushed.contains(filter) && 
ExprUtils.canEvaluateUnconditionally(filter) &&
+                gets(filter)
+            }
+        }
+      }
+      .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 (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, next) = Try(scanWith(builder, columns, filters)) 
match {
+            case Success(Right((scan, scanOutput))) =>
+              return (scan -> scanOutput.getOrElse(outputOfAllColumns(scan))) 
-> filters
+            // The read schema of the next scans of these columns would not 
follow them either.
+            case Success(Left(reason)) =>
+              (s"its read schema $reason", None, rest.filterNot(_._1 == 
columns))
+            case Failure(e) => (s"it failed with $e", Some(e), rest)
+          }
+          val (nextColumns, nextFilters) = next.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))}: " +

Review Comment:
   The pushdowns of the failed attempt and of the next one are logged with 
`LogKeys.OLD_VALUE` and `LogKeys.NEW_VALUE`, which usually stand for the old 
and new values of something like a configuration. Consumers of the structured 
logs could misread them, and it is hard to find these fallbacks by key. Could 
we use dedicated keys for them (new `LogKeys` entries if needed)?



##########
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:
   This says that a scan builder whose filters may fail "only gets those that 
the query applies before any other filter", but `buildScan` also gives such 
builders the filters after the leading ones that all the reads apply and that 
`ExprUtils.canEvaluateUnconditionally` accepts (`StreamingV2ScanPushDown.scala` 
L459-464). For example, with the filters `[udf(a) > 0, b > 5]`, a 
`SupportsPushDownV2Filters` builder gets `b > 5` although no filter leads. The 
Javadoc of `SupportsPushDownV2Filters.pushPredicates` has the same issue ("the 
predicates that the query applies first, in their order"). Could we update both 
to describe the actual contract?



##########
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:
   Before this PR, the shared extractor `ScanOfStream` made sure that 
`StreamingV2ScanPushDown.readsOfSources` and this planner match the same nodes. 
Now both use `PhysicalOperation` directly, and this invariant is kept only by 
the comment. If one side changes later (e.g., this case gets another extractor 
or guard), what the scans get at startup would no longer match what the 
micro-batches plan with them, which could cause spurious 
`STREAMING_SCAN_MISSING_COLUMNS` or `STREAMING_SCAN_FILTERS_CHANGED`. Could we 
keep a shared extractor so that both sides use the same match 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