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


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

Review Comment:
   **Following up on item 47 
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395315)): 
the micro-batches run `InferFiltersFromConstraints`, which puts the conditions 
that it infers from a filter ahead of the filter's own (`Filter(And(newFilters, 
condition), child)`), so Spark evaluates them before the pushed filters, with 
no change in the session.** For example, with ANSI and a 
`SupportsPushDownV2Filters` builder, `where("10 / x > 0 AND a = b AND b > 5")` 
pushes `10 / x > 0`, `a = b` and `b > 5`, in this order, when the query starts, 
since the inferred filters are left out here. A micro-batch infers `a > 5` from 
`a = b` and `b > 5` and evaluates it first, so Spark drops a row with `a = 1, b 
= 1, x = 0` before `10 / x` runs, while the stream evaluates `10 / x > 0` first 
and fails with `DIVIDE_BY_ZERO`. Without the pushdown the query succeeds, and 
`checkPushedFilters` lets the micro-batch run, since it compares the rows that 
the filters keep, not their order. Table
 Capability.java:206-210 says that the streams must not evaluate a filter on a 
row that a filter before it drops, "as Spark does not", but here Spark drops 
the row with a filter that the builder never got. Could the Javadoc say that 
Spark may evaluate other filters first, such as those that it infers, or could 
the check fail a micro-batch that puts other conditions before the pushed 
filters of such a builder?



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

Review Comment:
   **After a rebase on master, `ConstantPropagation.moveEqualitiesFirst` of 
SPARK-61033 (3c58e92, merged after the base of this PR) moves the equalities 
between a column and a literal ahead of the other conjuncts of a filter in the 
micro-batches, so Spark evaluates such an equality, which is not one with a 
literal when the query starts, before the pushed filters.** It does so when a 
conjunct that can fail comes after one that it rewrote. For example, with ANSI 
and a `SupportsPushDownV2Filters` builder, `where("owner <> '' AND CAST(payload 
AS INT) > 0 AND owner = current_user()")` pushes `owner <> ''` and 
`CAST(payload AS INT) > 0` when the query starts, since `current_user()` is a 
`StartupValue` then. A micro-batch folds `current_user()` to `'alice'`, 
rewrites `owner <> ''` to true, and evaluates `owner = 'alice'` first, so Spark 
only casts the payloads of alice, while the stream casts those of every owner 
and fails with `CAST_INVALID_INPUT` on a payload `'abc'` of bob. Without the p
 ushdown the query succeeds, and `checkPushedFilters` lets the micro-batch run, 
since `owner = 'alice'` implies `owner <> ''`. Before SPARK-61033, Spark cast 
the payloads of every owner too, so this comes with the rebase, which has no 
conflict. An equality that a micro-batch infers through a stream-static join is 
moved in the same way. As in my comment at L193, could the Javadoc of 
`STREAMING_FILTER_PUSHDOWN` or the check cover this order too?



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

Review Comment:
   Minor: following up on item 55 
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499818897)): 
these attempts come in the same order whatever made the first one fail. When 
`(requiredOutput, filters)` fails because of its read schema 
(`Success(Left(reason))` at L546), `(requiredOutput, Nil)` keeps the same 
column pruning, which a table with `SIMULATE_INCOMPLETE_COLUMN_PRUNING` rejects 
for the same reason, so the query builds one more scan from a new builder and 
logs one more warning before it tries `(output, filters)`. Could `firstScan` 
skip the attempts with the same columns after a read schema that does not 
follow them?



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

Review Comment:
   **Following up on item 58 
([thread](https://github.com/apache/spark/pull/60129#discussion_r4500146444)): 
`hasExactEquality` rejects a struct or an array with a double or float field, 
and `isFloating` only takes the top-level types, so such a column gets no value 
here, while `ConstantPropagation` puts its value in place of the column, as 
`isBinaryStable` only checks the collations of strings.** For example, with `k 
struct<a: double>`, `source.where("k.a > 0")` joined on `k = sk` with a static 
side filtered by `sk = named_struct('a', 1.0D)` pushes `k.a > 0` when the query 
starts. A micro-batch infers `k = {1.0}`, rewrites `k.a > 0` to `1.0 > 0.0` and 
folds it to true, which drops it from its conditions, so every micro-batch with 
data fails with `STREAMING_SCAN_FILTERS_CHANGED`. The struct test at 
StreamingV2ScanPushDownSuite.scala:1121 only has `struct<a: int>`. Could a 
struct or an array whose floating fields hold no 0.0 or -0.0 get its value too, 
or could its zeros be tried both w
 ays, as L768-L778 do for the top-level types?



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