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


##########
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:
   Done in 95f97ea: the read schema of a scan of all the columns with filters 
is now read in the fallback, in `scanWith`. So a `readSchema()` that throws 
with the filters makes the next attempt the scan with no filter, as for a 
pruned scan.
   
   A read schema that is read but does not follow the relation still fails the 
query with `STREAMING_SCAN_INVALID_READ_SCHEMA`, outside of the fallback, as 
the scan with no filter would. The test of the fallback now also fails 
`readSchema()` with any pushdown, and goes through all the attempts down to the 
scan of all the columns with no filter.



##########
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:
   Done in 95f97ea, the first way. The filters on the columns that `impliedBy` 
cannot give values to are no longer pushed down, so this failure mode is gone 
for them. `isPushable` now requires every column of a filter to be of a type 
whose equal values are the same (`hasExactEquality`). That excludes the 
floating types, the strings of a non-binary collation, and the structs and 
arrays that have such values.
   
   Your example now keeps `s.a > -1` in Spark, and its micro-batches fold it 
there. The new test `push down no filter on columns that the check of the 
micro-batches cannot give values` runs it, together with a double and a 
`UTF8_LCASE` string. The cost is that the filters on floating columns are not 
pushed down to streaming scans.
   
   For a rewrite that `impliedBy` still does not follow, the doc of 
`spark.sql.streaming.v2FilterPushdown.enabled` now says that the micro-batch 
fails, as do the next ones, and that restarting the query with the 
configuration set to false reads the source with no filter.



##########
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:
   Done in 95f97ea: the filters are now compared through `exact`. It replaces 
each literal with floating values, also in structs, arrays and maps, with a 
placeholder that holds their bits. The bits come from `doubleToLongBits` / 
`floatToIntBits`, so all the NaNs stay equal, as Spark evaluates them alike.
   
   `Reads.filters`, `filtersInAnyOrder`, the deduplication in `buildScan`, 
`holds` in `impliedBy` and the keys of `PushedFilterRewrites` all use it, so 
none of them depends on `Literal.hashCode` anymore. Filters on doubles are no 
longer pushed (see the thread at L676), so the test of the reads with another 
zero now uses `atan2(0.0, x) > 0` and `atan2(-0.0, x) > 0` on a bigint column. 
The test of the check also rejects `atan2(-0.0, ...)` given `atan2(0.0, ...)`.



##########
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:
   Done in 95f97ea: `pushFilters` and `getsFilter` now decide with the same 
functions:
   - `toDataSourceFilter` for `SupportsPushDownFilters`;
   - `toPredicate`, deterministic and translatable, for 
`SupportsPushDownV2Filters`;
   - `getsCatalystFilter` for `SupportsPushDownCatalystFilters`.
   
   `pushFilters` translates or partitions each filter with them, so a change to 
how it routes a filter changes `getsFilter` too.



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