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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,565 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation, 
ResolvedInlineTable}
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeReference, AttributeSet, Cast, Expression, ExpressionSet, 
SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.optimizer.{ComputeCurrentTime, 
InferFiltersFromConstraints, InferFiltersFromGenerate, PruneFilters, 
ReplaceExpressions, SpecialDatetimeValues}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, Filter, Join, 
LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, Statistics}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CAST, CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+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.execution.datasources.{DataSourceStrategy, 
LogicalRelation}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
PushDownUtils, StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType, 
StructType, TimestampLTZNanosType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * 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
+ * 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 these pushdowns, but for a 
filter of the rows
+ * of the relation with the filters that the scan builder got, which the query 
applies anyway, so
+ * that the scan cannot drop a row that the plan keeps (see 
`withPushedFilters`). The optimizer
+ * keeps deciding which columns every operator gets, and in which order, 
including the stateful
+ * ones, and Spark still evaluates all the filters over the relation. 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.
+ *
+ * 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 {
+
+  /**
+   * 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. Each 
micro-batch evaluates the
+     * pushed filters first, over the relation (see `withPushedFilters`), 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) =>
+        left.zip(right).takeWhile { case (l, r) => l.semanticEquals(r) 
}.map(_._1)
+      }.getOrElse(Nil)
+    }
+
+    /**
+     * The pushable filters that every occurrence applies, in the order of the 
first occurrence,
+     * wherever they are. These are the filters for a scan builder whose 
filters cannot fail, which
+     * may run before the filters written before them.
+     */
+    def filtersInAnyOrder: Seq[Expression] = {
+      occurrenceFilters.map(_.filter(isPushable)) match {
+        case Seq() => Nil
+        case first +: others =>
+          val sets = others.map(ExpressionSet(_))
+          first.filter(filter => sets.forall(_.contains(filter)))
+      }
+    }
+  }
+
+  /**
+   * Returns whether the scan of a relation may get `filter`, a deterministic 
filter over the
+   * relation: if it has no subquery and no placeholder, whose value each 
micro-batch gets on its
+   * own (see `forStartup`).
+   */
+  private def isPushable(filter: Expression): Boolean = {
+    !SubqueryExpression.hasSubquery(filter) && 
!filter.exists(_.isInstanceOf[StartupValue])
+  }
+
+  /**
+   * The scan of a streaming source, and its stream.
+   *
+   * @param prunedOutput the columns of the relation that the scan reads, in 
the order of its read
+   *                     schema, unless these are all its columns
+   * @param pushedFilters the filters that the scan builder got, which the 
scan may apply in any
+   *                      form, so the plan of each micro-batch applies them 
over the relation
+   */
+  case class StreamingScan(
+      scan: Scan,
+      stream: SparkDataStream,
+      prunedOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression]) {
+
+    /** Returns the scan relation of the source whose relation is `relation`. 
*/
+    def toRelation(
+        relation: StreamingDataSourceV2Relation): 
StreamingDataSourceV2ScanRelation = {
+      StreamingDataSourceV2ScanRelation(relation, scan, relation.output, 
stream,
+        prunedOutput = prunedOutput, pushedFilters = pushedFilters)
+    }
+  }
+
+  /**
+   * Returns what the optimized `plan` reads from each of its streaming 
relations of Data Source
+   * V2: what the planner takes from the projections and the filters over each 
occurrence of the
+   * relation, or all its columns and no filter where nothing is projected or 
filtered over it. A
+   * relation that the optimized plan does not have has no entry, so that its 
scan reads all its
+   * columns and gets no filter, as no relation has if the optimizer fails, or 
if the optimized
+   * plan has a streaming relation that `plan` does not have.
+   *
+   * The plan is optimized as the micro-batches are: with the optimizer and 
the configuration of
+   * the stream, the values of the configurations that the offset log of a 
restarted query pins, and
+   * without the cost-based reordering of joins, which `StreamExecution` 
disables for its queries.
+   * The plan does not depend on when it is optimized, and the scan of a 
relation only gets what the
+   * query reads from that relation:
+   *  - The expressions whose values depend on when they are evaluated or on 
the state of the
+   *    session, such as the current time, the casts of special strings such 
as 'today' or 'now'
+   *    to dates and timestamps, the casts of strings to timestamps with local 
time zone, which take
+   *    the current date for a string with only a time, or the current 
database, which each
+   *    micro-batch gets the values of, become placeholders that the optimizer 
does not take as
+   *    deterministic, as the current time of a micro-batch, so neither its 
filters nor its columns
+   *    depend on them, and no filter on them is pushed down.
+   *  - The filters that the optimizer infers from the constraints of the 
plan, such as those of the
+   *    filters over another relation joined with the relation, or from a 
generator, such as the
+   *    `isnotnull` of the array of an `explode`, are not inferred, so that 
the scan only gets the
+   *    filters that the query applies to the relation itself, whatever else 
the plan has.
+   *  - The relations of batch scans become placeholders, so that their scans 
are neither built
+   *    nor planned: they do not change what the plan reads from its streaming 
relations.
+   *
+   * @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 reads(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setSessionConf(_, conf, 
logChanges = false))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    // Without a source that prunes its columns, the scans can only get 
filters, which come from a
+    // condition of the plan: without one, nothing can be pushed down, and the 
plan is not
+    // optimized.
+    val prunesColumns = conf.streamingV2ColumnPruningEnabled && plan.exists {
+      case relation: StreamingRelationV2 =>
+        
relation.table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+      case _ => false
+    }
+    if (!prunesColumns && !mayHaveConditions(plan)) {
+      return Map.empty
+    }
+    session.withActive {
+      SQLConf.withExistingConf(conf) {
+        try {
+          val optimized = 
session.sessionState.optimizer.execute(forStartup(plan))
+          // The planner of a micro-batch gets the values of the expressions 
that depend on when
+          // they are evaluated, which are deterministic.
+          val planned = optimized.transformUpWithSubqueries {
+            case node => node.transformExpressions {
+              case value: StartupValue => value.copy(planned = true)
+            }
+          }
+          val occurrences = mutable.ArrayBuffer.empty[(StreamingRelationV2, 
Reads)]
+          // Visits the nodes as the planner plans them: the projections and 
the filters over a
+          // relation are planned with its scan, and the other nodes on their 
own.
+          def visit(node: LogicalPlan): Unit = node match {
+            case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+              occurrences += relation -> Reads(
+                AttributeSet((project ++ filters).flatMap(_.references)),
+                Seq(filtersEvaluatedOnce(node, filters, 
conf).takeWhile(_.deterministic)))
+            case _ =>
+              node.children.foreach(visit)
+          }
+          visit(planned)
+          val relations = plan.collect { case relation: StreamingRelationV2 => 
relation }.toSet
+          val unknown = occurrences.map(_._1).filterNot(relations.contains)
+          if (unknown.nonEmpty) {
+            // The optimizer does not copy streaming relations: 
`DeduplicateRelations` keeps
+            // streaming plans as they are, so all the references to a common 
table expression,
+            // for example, have the same relation. A copy would share the 
scan of its relation in
+            // the micro-batches, so the scan would have to read what the copy 
reads too.
+            logWarning(log"The optimized streaming query reads the streaming 
relations " +
+              log"${MDC(LogKeys.STREAMING_TABLE, unknown.distinct.mkString(", 
"))} that its " +
+              log"plan does not have, so the scans of its sources read all 
their columns with " +
+              log"no filter.")
+            Map.empty
+          } else {
+            combine(occurrences.toSeq)
+          }
+        } catch {
+          case NonFatal(e) =>
+            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
+        }
+      }
+    }
+  }
+
+  /**
+   * Returns what the occurrences of each relation read, combined: the scan of 
a relation reads the
+   * rows of all its occurrences, so it reads the columns that any of them 
reads, and can only
+   * apply the filters that all of them apply (see `Reads`).
+   */
+  private def combine(
+      occurrences: Seq[(StreamingRelationV2, Reads)]): 
Map[StreamingRelationV2, Reads] = {
+    occurrences.groupBy(_._1).map { case (relation, reads) =>
+      relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_._2.requiredColumns)),
+        reads.flatMap(_._2.occurrenceFilters))
+    }
+  }
+
+  /**
+   * Returns whether `plan` has a node with a condition that the optimizer 
could push down to a
+   * relation: a filter, or a join, an as-of or a lateral join, or a set 
operation, which it may
+   * turn into one.
+   */
+  private def mayHaveConditions(plan: LogicalPlan): Boolean = plan.exists {
+    case _: Filter | _: Join | _: AsOfJoin | _: LateralJoin | _: SetOperation 
=> true
+    case _ => false
+  }
+
+  /**
+   * Returns the filters of `filters`, those of the projections and the 
filters of `node` over a
+   * relation, that each micro-batch evaluates once if they are pushed down. A 
micro-batch keeps a
+   * filter above a projection of a value of its own, such as 
`current_timestamp()`, which is not
+   * deterministic until its optimization ends, so it cannot merge it with the 
filter of the pushed
+   * filters below the projection, and only `PruneFilters`, with the 
constraints of the plan, prunes
+   * the copy above. Without the propagation of the constraints, or with 
`PruneFilters` excluded,
+   * the filters above such a projection are not pushed down.
+   */
+  private def filtersEvaluatedOnce(
+      node: LogicalPlan,
+      filters: Seq[Expression],
+      conf: SQLConf): Seq[Expression] = {
+    if (conf.constraintPropagationEnabled &&
+        !conf.optimizerExcludedRules.toSeq.flatMap(_.split(",")).map(_.trim)
+          .contains(PruneFilters.ruleName)) {
+      filters
+    } else {
+      // The lowest projection of a placeholder, the nodes of `node` being 
projections and
+      // filters over the relation, from the top.
+      node.collect {

Review Comment:
   Thank you for the precise example. Following your design question (item 22, 
[thread](https://github.com/apache/spark/pull/60129#discussion_r4488857981)), 
this is now fixed where the copy is made, not by changing which filters are 
pushed. Each micro-batch drops the conjuncts of a filter that are semantically 
equal to the filters pushed below it, through other filters, aliases and 
projections that keep the columns 
(`StreamingV2ScanPushDown.withoutRepeatedPushedFilters`). So `where("ts < 
current_timestamp()").where("extra > 10")` still gives `extra > 10` to the V1 
builder, and the micro-batch evaluates it once.
   
   New tests:
   - "evaluate a pushed filter once after a separate filter that is not pushed 
down": your example, with the default confs, with 
`spark.sql.constraintPropagation.enabled=false`, and with `PruneFilters` 
excluded. It checks the pushed filter, the answer, and that the optimized plan 
of the micro-batch has one `extra > 10`.
   - "evaluate a pushed filter once above a projection of a value of each 
micro-batch": replaces the earlier constraint-propagation test, under the same 
three confs.
   
   Both fail without the change.
   



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java:
##########
@@ -170,5 +170,44 @@ public enum TableCapability {
    *
    * @since 4.4.0
    */
-  EXTERNAL_LOOKUP
+  EXTERNAL_LOOKUP,
+
+  /**
+   * Signals that the scans of the streaming reads of the table may only read 
the columns that the
+   * streaming query reads, which Spark asks a scan builder that implements
+   * {@link 
org.apache.spark.sql.connector.read.SupportsPushDownRequiredColumns} for, as it 
does
+   * for the scans of batch reads.
+   * <p>
+   * Spark builds the scan of a streaming read once, when the query starts, 
from the plan of the
+   * query optimized then, and creates the micro-batch or continuous stream of 
the read from that
+   * scan. By returning this capability, a table declares that the partition 
readers of such a
+   * stream return the columns of {@link 
org.apache.spark.sql.connector.read.Scan#readSchema()},
+   * as those of the batches of the scan do. Spark asks a pruned scan for its 
read schema before it
+   * creates the stream. Without this capability, the scans of streaming reads 
read all the
+   * columns of the table.
+   *
+   * @since 4.4.0
+   */
+  STREAMING_COLUMN_PRUNING,
+
+  /**
+   * Signals that the scans of the streaming reads of the table may get the 
filters that the
+   * streaming query applies first to all the rows that it reads from the 
table, before any other

Review Comment:
   Thank you, done. The Javadoc of `TableCapability.STREAMING_FILTER_PUSHDOWN` 
and the doc of `spark.sql.streaming.v2FilterPushdown.enabled` now say that a 
scan gets the filters the query applies to all the rows it reads from the 
table. A `SupportsPushDownFilters` builder, whose filters compare columns with 
values and cannot fail, gets them wherever the query applies them. A builder 
whose filters may fail, e.g. a cast under ANSI, only gets those the query 
applies before any other filter.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,565 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation, 
ResolvedInlineTable}
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeReference, AttributeSet, Cast, Expression, ExpressionSet, 
SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.optimizer.{ComputeCurrentTime, 
InferFiltersFromConstraints, InferFiltersFromGenerate, PruneFilters, 
ReplaceExpressions, SpecialDatetimeValues}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, Filter, Join, 
LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, Statistics}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CAST, CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+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.execution.datasources.{DataSourceStrategy, 
LogicalRelation}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
PushDownUtils, StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType, 
StructType, TimestampLTZNanosType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * 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
+ * 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 these pushdowns, but for a 
filter of the rows
+ * of the relation with the filters that the scan builder got, which the query 
applies anyway, so
+ * that the scan cannot drop a row that the plan keeps (see 
`withPushedFilters`). The optimizer
+ * keeps deciding which columns every operator gets, and in which order, 
including the stateful
+ * ones, and Spark still evaluates all the filters over the relation. 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.
+ *
+ * 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 {
+
+  /**
+   * 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. Each 
micro-batch evaluates the
+     * pushed filters first, over the relation (see `withPushedFilters`), 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) =>
+        left.zip(right).takeWhile { case (l, r) => l.semanticEquals(r) 
}.map(_._1)
+      }.getOrElse(Nil)
+    }
+
+    /**
+     * The pushable filters that every occurrence applies, in the order of the 
first occurrence,
+     * wherever they are. These are the filters for a scan builder whose 
filters cannot fail, which
+     * may run before the filters written before them.
+     */
+    def filtersInAnyOrder: Seq[Expression] = {
+      occurrenceFilters.map(_.filter(isPushable)) match {
+        case Seq() => Nil
+        case first +: others =>
+          val sets = others.map(ExpressionSet(_))
+          first.filter(filter => sets.forall(_.contains(filter)))
+      }
+    }
+  }
+
+  /**
+   * Returns whether the scan of a relation may get `filter`, a deterministic 
filter over the
+   * relation: if it has no subquery and no placeholder, whose value each 
micro-batch gets on its
+   * own (see `forStartup`).
+   */
+  private def isPushable(filter: Expression): Boolean = {
+    !SubqueryExpression.hasSubquery(filter) && 
!filter.exists(_.isInstanceOf[StartupValue])
+  }
+
+  /**
+   * The scan of a streaming source, and its stream.
+   *
+   * @param prunedOutput the columns of the relation that the scan reads, in 
the order of its read
+   *                     schema, unless these are all its columns
+   * @param pushedFilters the filters that the scan builder got, which the 
scan may apply in any
+   *                      form, so the plan of each micro-batch applies them 
over the relation
+   */
+  case class StreamingScan(
+      scan: Scan,
+      stream: SparkDataStream,
+      prunedOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression]) {
+
+    /** Returns the scan relation of the source whose relation is `relation`. 
*/
+    def toRelation(
+        relation: StreamingDataSourceV2Relation): 
StreamingDataSourceV2ScanRelation = {
+      StreamingDataSourceV2ScanRelation(relation, scan, relation.output, 
stream,
+        prunedOutput = prunedOutput, pushedFilters = pushedFilters)
+    }
+  }
+
+  /**
+   * Returns what the optimized `plan` reads from each of its streaming 
relations of Data Source
+   * V2: what the planner takes from the projections and the filters over each 
occurrence of the
+   * relation, or all its columns and no filter where nothing is projected or 
filtered over it. A
+   * relation that the optimized plan does not have has no entry, so that its 
scan reads all its
+   * columns and gets no filter, as no relation has if the optimizer fails, or 
if the optimized
+   * plan has a streaming relation that `plan` does not have.
+   *
+   * The plan is optimized as the micro-batches are: with the optimizer and 
the configuration of
+   * the stream, the values of the configurations that the offset log of a 
restarted query pins, and
+   * without the cost-based reordering of joins, which `StreamExecution` 
disables for its queries.
+   * The plan does not depend on when it is optimized, and the scan of a 
relation only gets what the
+   * query reads from that relation:
+   *  - The expressions whose values depend on when they are evaluated or on 
the state of the
+   *    session, such as the current time, the casts of special strings such 
as 'today' or 'now'
+   *    to dates and timestamps, the casts of strings to timestamps with local 
time zone, which take
+   *    the current date for a string with only a time, or the current 
database, which each
+   *    micro-batch gets the values of, become placeholders that the optimizer 
does not take as
+   *    deterministic, as the current time of a micro-batch, so neither its 
filters nor its columns
+   *    depend on them, and no filter on them is pushed down.
+   *  - The filters that the optimizer infers from the constraints of the 
plan, such as those of the
+   *    filters over another relation joined with the relation, or from a 
generator, such as the
+   *    `isnotnull` of the array of an `explode`, are not inferred, so that 
the scan only gets the
+   *    filters that the query applies to the relation itself, whatever else 
the plan has.
+   *  - The relations of batch scans become placeholders, so that their scans 
are neither built
+   *    nor planned: they do not change what the plan reads from its streaming 
relations.
+   *
+   * @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 reads(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setSessionConf(_, conf, 
logChanges = false))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    // Without a source that prunes its columns, the scans can only get 
filters, which come from a
+    // condition of the plan: without one, nothing can be pushed down, and the 
plan is not
+    // optimized.
+    val prunesColumns = conf.streamingV2ColumnPruningEnabled && plan.exists {
+      case relation: StreamingRelationV2 =>
+        
relation.table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+      case _ => false
+    }
+    if (!prunesColumns && !mayHaveConditions(plan)) {
+      return Map.empty
+    }
+    session.withActive {
+      SQLConf.withExistingConf(conf) {
+        try {
+          val optimized = 
session.sessionState.optimizer.execute(forStartup(plan))
+          // The planner of a micro-batch gets the values of the expressions 
that depend on when
+          // they are evaluated, which are deterministic.
+          val planned = optimized.transformUpWithSubqueries {
+            case node => node.transformExpressions {
+              case value: StartupValue => value.copy(planned = true)
+            }
+          }
+          val occurrences = mutable.ArrayBuffer.empty[(StreamingRelationV2, 
Reads)]
+          // Visits the nodes as the planner plans them: the projections and 
the filters over a
+          // relation are planned with its scan, and the other nodes on their 
own.
+          def visit(node: LogicalPlan): Unit = node match {
+            case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+              occurrences += relation -> Reads(
+                AttributeSet((project ++ filters).flatMap(_.references)),
+                Seq(filtersEvaluatedOnce(node, filters, 
conf).takeWhile(_.deterministic)))
+            case _ =>
+              node.children.foreach(visit)
+          }
+          visit(planned)
+          val relations = plan.collect { case relation: StreamingRelationV2 => 
relation }.toSet
+          val unknown = occurrences.map(_._1).filterNot(relations.contains)
+          if (unknown.nonEmpty) {
+            // The optimizer does not copy streaming relations: 
`DeduplicateRelations` keeps
+            // streaming plans as they are, so all the references to a common 
table expression,
+            // for example, have the same relation. A copy would share the 
scan of its relation in
+            // the micro-batches, so the scan would have to read what the copy 
reads too.
+            logWarning(log"The optimized streaming query reads the streaming 
relations " +
+              log"${MDC(LogKeys.STREAMING_TABLE, unknown.distinct.mkString(", 
"))} that its " +
+              log"plan does not have, so the scans of its sources read all 
their columns with " +
+              log"no filter.")
+            Map.empty
+          } else {
+            combine(occurrences.toSeq)
+          }
+        } catch {
+          case NonFatal(e) =>
+            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
+        }
+      }
+    }
+  }
+
+  /**
+   * Returns what the occurrences of each relation read, combined: the scan of 
a relation reads the
+   * rows of all its occurrences, so it reads the columns that any of them 
reads, and can only
+   * apply the filters that all of them apply (see `Reads`).
+   */
+  private def combine(
+      occurrences: Seq[(StreamingRelationV2, Reads)]): 
Map[StreamingRelationV2, Reads] = {
+    occurrences.groupBy(_._1).map { case (relation, reads) =>
+      relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_._2.requiredColumns)),
+        reads.flatMap(_._2.occurrenceFilters))
+    }
+  }
+
+  /**
+   * Returns whether `plan` has a node with a condition that the optimizer 
could push down to a
+   * relation: a filter, or a join, an as-of or a lateral join, or a set 
operation, which it may
+   * turn into one.
+   */
+  private def mayHaveConditions(plan: LogicalPlan): Boolean = plan.exists {
+    case _: Filter | _: Join | _: AsOfJoin | _: LateralJoin | _: SetOperation 
=> true
+    case _ => false
+  }
+
+  /**
+   * Returns the filters of `filters`, those of the projections and the 
filters of `node` over a
+   * relation, that each micro-batch evaluates once if they are pushed down. A 
micro-batch keeps a
+   * filter above a projection of a value of its own, such as 
`current_timestamp()`, which is not
+   * deterministic until its optimization ends, so it cannot merge it with the 
filter of the pushed
+   * filters below the projection, and only `PruneFilters`, with the 
constraints of the plan, prunes
+   * the copy above. Without the propagation of the constraints, or with 
`PruneFilters` excluded,
+   * the filters above such a projection are not pushed down.
+   */
+  private def filtersEvaluatedOnce(

Review Comment:
   Agreed, that is better, thank you. `filtersEvaluatedOnce` is gone. After the 
scans are built, `MicroBatchExecution` and `ContinuousExecution` run the plan 
through `StreamingV2ScanPushDown.withoutRepeatedPushedFilters`. For each 
`Filter`, it removes the conjuncts that are semantically equal 
(`ExpressionSet`) to the filters pushed to a relation below it. It looks 
through other `Filter`s, `SubqueryAlias`es, and `Project`s, keeping only the 
pushed filters whose columns the projection passes on unchanged. The 
micro-batch evaluates the pushed filters over the relation 
(`withPushedFilters`), so a removed conjunct is still applied, once, to the 
same rows. This covers every shape, with or without `PruneFilters` and 
constraint propagation, and fixes items 2, 16 and 20 the same way. The 
constraint-propagation test now checks that the filter is pushed and evaluated 
once in all three settings.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,565 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation, 
ResolvedInlineTable}
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeReference, AttributeSet, Cast, Expression, ExpressionSet, 
SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.optimizer.{ComputeCurrentTime, 
InferFiltersFromConstraints, InferFiltersFromGenerate, PruneFilters, 
ReplaceExpressions, SpecialDatetimeValues}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, Filter, Join, 
LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, Statistics}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CAST, CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+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.execution.datasources.{DataSourceStrategy, 
LogicalRelation}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
PushDownUtils, StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType, 
StructType, TimestampLTZNanosType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * 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
+ * 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 these pushdowns, but for a 
filter of the rows
+ * of the relation with the filters that the scan builder got, which the query 
applies anyway, so
+ * that the scan cannot drop a row that the plan keeps (see 
`withPushedFilters`). The optimizer
+ * keeps deciding which columns every operator gets, and in which order, 
including the stateful
+ * ones, and Spark still evaluates all the filters over the relation. 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.
+ *
+ * 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 {
+
+  /**
+   * 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. Each 
micro-batch evaluates the
+     * pushed filters first, over the relation (see `withPushedFilters`), 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) =>
+        left.zip(right).takeWhile { case (l, r) => l.semanticEquals(r) 
}.map(_._1)
+      }.getOrElse(Nil)
+    }
+
+    /**
+     * The pushable filters that every occurrence applies, in the order of the 
first occurrence,
+     * wherever they are. These are the filters for a scan builder whose 
filters cannot fail, which
+     * may run before the filters written before them.
+     */
+    def filtersInAnyOrder: Seq[Expression] = {
+      occurrenceFilters.map(_.filter(isPushable)) match {
+        case Seq() => Nil
+        case first +: others =>
+          val sets = others.map(ExpressionSet(_))
+          first.filter(filter => sets.forall(_.contains(filter)))
+      }
+    }
+  }
+
+  /**
+   * Returns whether the scan of a relation may get `filter`, a deterministic 
filter over the
+   * relation: if it has no subquery and no placeholder, whose value each 
micro-batch gets on its
+   * own (see `forStartup`).
+   */
+  private def isPushable(filter: Expression): Boolean = {
+    !SubqueryExpression.hasSubquery(filter) && 
!filter.exists(_.isInstanceOf[StartupValue])
+  }
+
+  /**
+   * The scan of a streaming source, and its stream.
+   *
+   * @param prunedOutput the columns of the relation that the scan reads, in 
the order of its read
+   *                     schema, unless these are all its columns
+   * @param pushedFilters the filters that the scan builder got, which the 
scan may apply in any
+   *                      form, so the plan of each micro-batch applies them 
over the relation
+   */
+  case class StreamingScan(
+      scan: Scan,
+      stream: SparkDataStream,
+      prunedOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression]) {
+
+    /** Returns the scan relation of the source whose relation is `relation`. 
*/
+    def toRelation(
+        relation: StreamingDataSourceV2Relation): 
StreamingDataSourceV2ScanRelation = {
+      StreamingDataSourceV2ScanRelation(relation, scan, relation.output, 
stream,
+        prunedOutput = prunedOutput, pushedFilters = pushedFilters)
+    }
+  }
+
+  /**
+   * Returns what the optimized `plan` reads from each of its streaming 
relations of Data Source
+   * V2: what the planner takes from the projections and the filters over each 
occurrence of the
+   * relation, or all its columns and no filter where nothing is projected or 
filtered over it. A
+   * relation that the optimized plan does not have has no entry, so that its 
scan reads all its
+   * columns and gets no filter, as no relation has if the optimizer fails, or 
if the optimized
+   * plan has a streaming relation that `plan` does not have.
+   *
+   * The plan is optimized as the micro-batches are: with the optimizer and 
the configuration of
+   * the stream, the values of the configurations that the offset log of a 
restarted query pins, and
+   * without the cost-based reordering of joins, which `StreamExecution` 
disables for its queries.
+   * The plan does not depend on when it is optimized, and the scan of a 
relation only gets what the
+   * query reads from that relation:
+   *  - The expressions whose values depend on when they are evaluated or on 
the state of the
+   *    session, such as the current time, the casts of special strings such 
as 'today' or 'now'
+   *    to dates and timestamps, the casts of strings to timestamps with local 
time zone, which take
+   *    the current date for a string with only a time, or the current 
database, which each
+   *    micro-batch gets the values of, become placeholders that the optimizer 
does not take as
+   *    deterministic, as the current time of a micro-batch, so neither its 
filters nor its columns
+   *    depend on them, and no filter on them is pushed down.
+   *  - The filters that the optimizer infers from the constraints of the 
plan, such as those of the
+   *    filters over another relation joined with the relation, or from a 
generator, such as the
+   *    `isnotnull` of the array of an `explode`, are not inferred, so that 
the scan only gets the
+   *    filters that the query applies to the relation itself, whatever else 
the plan has.
+   *  - The relations of batch scans become placeholders, so that their scans 
are neither built
+   *    nor planned: they do not change what the plan reads from its streaming 
relations.
+   *
+   * @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 reads(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setSessionConf(_, conf, 
logChanges = false))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    // Without a source that prunes its columns, the scans can only get 
filters, which come from a
+    // condition of the plan: without one, nothing can be pushed down, and the 
plan is not
+    // optimized.
+    val prunesColumns = conf.streamingV2ColumnPruningEnabled && plan.exists {
+      case relation: StreamingRelationV2 =>
+        
relation.table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+      case _ => false
+    }
+    if (!prunesColumns && !mayHaveConditions(plan)) {
+      return Map.empty
+    }
+    session.withActive {
+      SQLConf.withExistingConf(conf) {
+        try {
+          val optimized = 
session.sessionState.optimizer.execute(forStartup(plan))
+          // The planner of a micro-batch gets the values of the expressions 
that depend on when
+          // they are evaluated, which are deterministic.
+          val planned = optimized.transformUpWithSubqueries {
+            case node => node.transformExpressions {
+              case value: StartupValue => value.copy(planned = true)
+            }
+          }
+          val occurrences = mutable.ArrayBuffer.empty[(StreamingRelationV2, 
Reads)]
+          // Visits the nodes as the planner plans them: the projections and 
the filters over a
+          // relation are planned with its scan, and the other nodes on their 
own.
+          def visit(node: LogicalPlan): Unit = node match {
+            case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+              occurrences += relation -> Reads(
+                AttributeSet((project ++ filters).flatMap(_.references)),
+                Seq(filtersEvaluatedOnce(node, filters, 
conf).takeWhile(_.deterministic)))
+            case _ =>
+              node.children.foreach(visit)
+          }
+          visit(planned)
+          val relations = plan.collect { case relation: StreamingRelationV2 => 
relation }.toSet
+          val unknown = occurrences.map(_._1).filterNot(relations.contains)
+          if (unknown.nonEmpty) {
+            // The optimizer does not copy streaming relations: 
`DeduplicateRelations` keeps
+            // streaming plans as they are, so all the references to a common 
table expression,
+            // for example, have the same relation. A copy would share the 
scan of its relation in
+            // the micro-batches, so the scan would have to read what the copy 
reads too.
+            logWarning(log"The optimized streaming query reads the streaming 
relations " +
+              log"${MDC(LogKeys.STREAMING_TABLE, unknown.distinct.mkString(", 
"))} that its " +
+              log"plan does not have, so the scans of its sources read all 
their columns with " +
+              log"no filter.")
+            Map.empty
+          } else {
+            combine(occurrences.toSeq)
+          }
+        } catch {
+          case NonFatal(e) =>
+            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
+        }
+      }
+    }
+  }
+
+  /**
+   * Returns what the occurrences of each relation read, combined: the scan of 
a relation reads the
+   * rows of all its occurrences, so it reads the columns that any of them 
reads, and can only
+   * apply the filters that all of them apply (see `Reads`).
+   */
+  private def combine(
+      occurrences: Seq[(StreamingRelationV2, Reads)]): 
Map[StreamingRelationV2, Reads] = {
+    occurrences.groupBy(_._1).map { case (relation, reads) =>
+      relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_._2.requiredColumns)),
+        reads.flatMap(_._2.occurrenceFilters))
+    }
+  }
+
+  /**
+   * Returns whether `plan` has a node with a condition that the optimizer 
could push down to a
+   * relation: a filter, or a join, an as-of or a lateral join, or a set 
operation, which it may
+   * turn into one.
+   */
+  private def mayHaveConditions(plan: LogicalPlan): Boolean = plan.exists {
+    case _: Filter | _: Join | _: AsOfJoin | _: LateralJoin | _: SetOperation 
=> true
+    case _ => false
+  }
+
+  /**
+   * Returns the filters of `filters`, those of the projections and the 
filters of `node` over a
+   * relation, that each micro-batch evaluates once if they are pushed down. A 
micro-batch keeps a
+   * filter above a projection of a value of its own, such as 
`current_timestamp()`, which is not
+   * deterministic until its optimization ends, so it cannot merge it with the 
filter of the pushed
+   * filters below the projection, and only `PruneFilters`, with the 
constraints of the plan, prunes
+   * the copy above. Without the propagation of the constraints, or with 
`PruneFilters` excluded,
+   * the filters above such a projection are not pushed down.
+   */
+  private def filtersEvaluatedOnce(
+      node: LogicalPlan,
+      filters: Seq[Expression],
+      conf: SQLConf): Seq[Expression] = {
+    if (conf.constraintPropagationEnabled &&
+        !conf.optimizerExcludedRules.toSeq.flatMap(_.split(",")).map(_.trim)
+          .contains(PruneFilters.ruleName)) {
+      filters
+    } else {
+      // The lowest projection of a placeholder, the nodes of `node` being 
projections and
+      // filters over the relation, from the top.
+      node.collect {
+        case project: Project
+            if 
project.projectList.exists(_.exists(_.isInstanceOf[StartupValue])) =>
+          project.child
+      }.lastOption match {
+        case Some(PhysicalOperation(_, below, _: StreamingRelationV2)) => below
+        case Some(_) => Nil
+        case None => filters
+      }
+    }
+  }
+
+  /**
+   * Returns `plan` for the optimization when the query starts, see `reads`, 
with its subqueries.
+   * The expressions that are replaced keep their children, so that the plan 
still reads the same
+   * columns. Visible for tests.
+   */
+  private[sql] def forStartup(plan: LogicalPlan): LogicalPlan = 
plan.transformUpWithSubqueries {
+    case relation: DataSourceV2Relation => BatchRelation(relation.output)
+    case relation: LogicalRelation if !relation.isStreaming => 
BatchRelation(relation.output)
+    case relation: HiveTableRelation => BatchRelation(relation.output)
+    // The rows of an inline table may have values of the current time, which 
the optimizer
+    // evaluates.
+    case table: ResolvedInlineTable => BatchRelation(table.output)
+    case node =>
+      // The expressions that ReplaceExpressions replaces with others when the 
optimization starts
+      // are replaced first, as the optimizer does, so that the casts that 
they stand for, such as
+      // the one of to_date('today'), are replaced below.
+      val replaced = if (node.containsPattern(RUNTIME_REPLACEABLE)) {
+        node.mapExpressions(ReplaceExpressions.replace)
+      } else {
+        node
+      }
+      replaced.transformExpressionsUpWithPruning(
+          bits => bits.containsPattern(CURRENT_LIKE) || 
bits.containsPattern(CAST)) {
+        // The children of an expression are replaced before it, as are the 
subqueries, so an
+        // expression that still has the pattern CURRENT_LIKE has it itself: 
its value is the
+        // current time, or comes from the state of the session, as the 
current database does.
+        case e if e.containsPattern(CURRENT_LIKE) => StartupValue(e, 
e.children)
+        // So does a cast that ComputeCurrentTime or SpecialDatetimeValues 
rewrites: a cast of a
+        // time to a timestamp, which takes the current date, or a cast of a 
special string, such
+        // as 'today' or 'now', to a date or a timestamp. These rules only 
rewrite casts besides
+        // the expressions with the pattern CURRENT_LIKE. A cast of a string 
to a timestamp with
+        // local time zone takes the current date too, for a string with only 
a time such as
+        // '12:00:00': the optimizer folds the date in once the string is a 
literal, which it may
+        // only become during the optimization, as when an alias or an 
equality propagates it, so
+        // such a cast is replaced whatever its child is.
+        case cast: Cast if ComputeCurrentTime.applyForExpression(cast) != cast 
||
+            SpecialDatetimeValues.applyForExpression(cast) != cast ||
+            castsStringToTimestampLTZ(cast.child.dataType, cast.dataType) =>
+          StartupValue(cast, cast.children)
+      }
+  }
+
+  /**
+   * Returns whether a cast from `from` to `to` casts a string to a timestamp 
with local time zone,
+   * of any precision, at any depth of the types: also the elements of an 
array, the keys or the
+   * values of a map, or the fields of a struct. Such a cast takes the date of 
when it is evaluated
+   * for a string with only a time. A cast to a timestamp without time zone or 
to a date does not:
+   * it rejects such a string.
+   */
+  private def castsStringToTimestampLTZ(from: DataType, to: DataType): Boolean 
= (from, to) match {
+    case (_: StringType, TimestampType | _: TimestampLTZNanosType) => true
+    case (ArrayType(fromElement, _), ArrayType(toElement, _)) =>
+      castsStringToTimestampLTZ(fromElement, toElement)
+    case (MapType(fromKey, fromValue, _), MapType(toKey, toValue, _)) =>
+      castsStringToTimestampLTZ(fromKey, toKey) || 
castsStringToTimestampLTZ(fromValue, toValue)
+    case (StructType(fromFields), StructType(toFields)) =>
+      fromFields.zip(toFields).exists { case (fromField, toField) =>
+        castsStringToTimestampLTZ(fromField.dataType, toField.dataType)
+      }
+    case _ => false
+  }
+
+  /**
+   * 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` 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 
`reads`). `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.
+   *
+   * A pruned scan must read the required columns and only columns of 
`output`, each once, as
+   * `SupportsPushDownRequiredColumns` requires. Spark asks a pruned scan for 
its read schema
+   * before it creates its stream. If the scan builder, the scan or its stream 
fails with the
+   * pushdowns, or the read schema of a pruned scan cannot be read or does not 
follow
+   * `SupportsPushDownRequiredColumns`, a scan of all the columns with no 
filter is built instead,
+   * from a new scan builder, as 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 reads what the query reads from the relation, or None to read all 
its columns with no
+   *              filter
+   */
+  def buildScan(
+      table: SupportsRead,
+      options: CaseInsensitiveStringMap,
+      output: Seq[AttributeReference],
+      conf: SQLConf,
+      reads: => Option[Reads])(
+      createStream: Scan => SparkDataStream): StreamingScan = {
+    val builder = table.newScanBuilder(options)
+    val capabilities = table.capabilities()
+    val prunesColumns = conf.streamingV2ColumnPruningEnabled &&
+      capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING) &&
+      builder.isInstanceOf[SupportsPushDownRequiredColumns]
+    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: none runs before a filter 
written before it. The
+    // builders are matched in the order of `PushDownUtils.pushFilters`.
+    def gets(filter: Expression): Boolean =
+      PushDownUtils.filtersOfScanBuilder(builder, Seq(filter)).nonEmpty
+    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`, once it pushed `filters` 
down to it.
+    def build(
+        builder: ScanBuilder,
+        columns: Seq[AttributeReference],
+        filters: Seq[Expression]): Scan = {
+      if (filters.nonEmpty) {
+        // The plan of each micro-batch applies these filters to the rows of 
the source, see
+        // `withPushedFilters`, 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 with no filter, as without these pushdowns.
+    def scanOfAllColumns(builder: ScanBuilder): StreamingScan = {
+      val scan = build(builder, output, Nil)
+      StreamingScan(scan, createStream(scan), None, Nil)
+    }
+
+    if (requiredOutput.length == output.length && filters.isEmpty) {
+      scanOfAllColumns(builder)
+    } else {
+      // Logs why the scan with the pushdowns could not be built, and builds 
the scan of all the
+      // columns with no filter instead.
+      def fallBack(reason: String, cause: Option[Throwable]): StreamingScan = {
+        val columns = if (requiredOutput.length < output.length) {
+          requiredOutput.map(_.name).mkString(", ")
+        } else {
+          "all"
+        }
+        val filterList = if (filters.nonEmpty) filters.map(_.sql).mkString(", 
") else "none"
+        val message = log"The scan of the streaming table " +
+          log"${MDC(LogKeys.STREAMING_TABLE, table)} could not be built with 
the pushdowns " +
+          log"(columns: ${MDC(LogKeys.COLUMN_NAMES, columns)}, filters: " +
+          log"${MDC(LogKeys.FILTER, filterList)}): ${MDC(LogKeys.REASON, 
reason)}. It reads all " +
+          log"the columns with no filter instead."
+        cause match {
+          case Some(e) => logWarning(message, e)
+          case None => logWarning(message)
+        }
+        scanOfAllColumns(table.newScanBuilder(options))

Review Comment:
   Good point, done. When the scan with both pushdowns fails, it is now built 
again from a new scan builder with the column pruning alone, before falling 
back to all the columns with no filter. The warning says which one it reads. 
The failing-step test is now "read with fewer pushdowns when the scan fails 
with the pushdowns". For `pushFilters` it expects a read schema of `_2, _3` 
with no filter and no second warning. For `pruneColumns` and `build` it expects 
all the columns, with both warnings. To return the pruned columns correctly, 
`FailingPushDownTable` now reads from a `ProjectingMemoryStream`. 
`toMicroBatchStream` still fails the query, as in #59943.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,565 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation, 
ResolvedInlineTable}
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeReference, AttributeSet, Cast, Expression, ExpressionSet, 
SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.optimizer.{ComputeCurrentTime, 
InferFiltersFromConstraints, InferFiltersFromGenerate, PruneFilters, 
ReplaceExpressions, SpecialDatetimeValues}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, Filter, Join, 
LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, Statistics}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CAST, CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+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.execution.datasources.{DataSourceStrategy, 
LogicalRelation}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
PushDownUtils, StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType, 
StructType, TimestampLTZNanosType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * 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
+ * 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 these pushdowns, but for a 
filter of the rows
+ * of the relation with the filters that the scan builder got, which the query 
applies anyway, so
+ * that the scan cannot drop a row that the plan keeps (see 
`withPushedFilters`). The optimizer
+ * keeps deciding which columns every operator gets, and in which order, 
including the stateful
+ * ones, and Spark still evaluates all the filters over the relation. 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.
+ *
+ * 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 {
+
+  /**
+   * 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. Each 
micro-batch evaluates the
+     * pushed filters first, over the relation (see `withPushedFilters`), 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) =>
+        left.zip(right).takeWhile { case (l, r) => l.semanticEquals(r) 
}.map(_._1)
+      }.getOrElse(Nil)
+    }
+
+    /**
+     * The pushable filters that every occurrence applies, in the order of the 
first occurrence,
+     * wherever they are. These are the filters for a scan builder whose 
filters cannot fail, which
+     * may run before the filters written before them.
+     */
+    def filtersInAnyOrder: Seq[Expression] = {
+      occurrenceFilters.map(_.filter(isPushable)) match {
+        case Seq() => Nil
+        case first +: others =>
+          val sets = others.map(ExpressionSet(_))
+          first.filter(filter => sets.forall(_.contains(filter)))
+      }
+    }
+  }
+
+  /**
+   * Returns whether the scan of a relation may get `filter`, a deterministic 
filter over the
+   * relation: if it has no subquery and no placeholder, whose value each 
micro-batch gets on its
+   * own (see `forStartup`).
+   */
+  private def isPushable(filter: Expression): Boolean = {
+    !SubqueryExpression.hasSubquery(filter) && 
!filter.exists(_.isInstanceOf[StartupValue])
+  }
+
+  /**
+   * The scan of a streaming source, and its stream.
+   *
+   * @param prunedOutput the columns of the relation that the scan reads, in 
the order of its read
+   *                     schema, unless these are all its columns
+   * @param pushedFilters the filters that the scan builder got, which the 
scan may apply in any
+   *                      form, so the plan of each micro-batch applies them 
over the relation
+   */
+  case class StreamingScan(
+      scan: Scan,
+      stream: SparkDataStream,
+      prunedOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression]) {
+
+    /** Returns the scan relation of the source whose relation is `relation`. 
*/
+    def toRelation(
+        relation: StreamingDataSourceV2Relation): 
StreamingDataSourceV2ScanRelation = {
+      StreamingDataSourceV2ScanRelation(relation, scan, relation.output, 
stream,
+        prunedOutput = prunedOutput, pushedFilters = pushedFilters)
+    }
+  }
+
+  /**
+   * Returns what the optimized `plan` reads from each of its streaming 
relations of Data Source
+   * V2: what the planner takes from the projections and the filters over each 
occurrence of the
+   * relation, or all its columns and no filter where nothing is projected or 
filtered over it. A
+   * relation that the optimized plan does not have has no entry, so that its 
scan reads all its
+   * columns and gets no filter, as no relation has if the optimizer fails, or 
if the optimized
+   * plan has a streaming relation that `plan` does not have.
+   *
+   * The plan is optimized as the micro-batches are: with the optimizer and 
the configuration of
+   * the stream, the values of the configurations that the offset log of a 
restarted query pins, and
+   * without the cost-based reordering of joins, which `StreamExecution` 
disables for its queries.
+   * The plan does not depend on when it is optimized, and the scan of a 
relation only gets what the
+   * query reads from that relation:
+   *  - The expressions whose values depend on when they are evaluated or on 
the state of the
+   *    session, such as the current time, the casts of special strings such 
as 'today' or 'now'
+   *    to dates and timestamps, the casts of strings to timestamps with local 
time zone, which take
+   *    the current date for a string with only a time, or the current 
database, which each
+   *    micro-batch gets the values of, become placeholders that the optimizer 
does not take as
+   *    deterministic, as the current time of a micro-batch, so neither its 
filters nor its columns
+   *    depend on them, and no filter on them is pushed down.
+   *  - The filters that the optimizer infers from the constraints of the 
plan, such as those of the
+   *    filters over another relation joined with the relation, or from a 
generator, such as the
+   *    `isnotnull` of the array of an `explode`, are not inferred, so that 
the scan only gets the
+   *    filters that the query applies to the relation itself, whatever else 
the plan has.
+   *  - The relations of batch scans become placeholders, so that their scans 
are neither built
+   *    nor planned: they do not change what the plan reads from its streaming 
relations.
+   *
+   * @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 reads(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setSessionConf(_, conf, 
logChanges = false))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    // Without a source that prunes its columns, the scans can only get 
filters, which come from a
+    // condition of the plan: without one, nothing can be pushed down, and the 
plan is not
+    // optimized.
+    val prunesColumns = conf.streamingV2ColumnPruningEnabled && plan.exists {
+      case relation: StreamingRelationV2 =>
+        
relation.table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+      case _ => false
+    }
+    if (!prunesColumns && !mayHaveConditions(plan)) {
+      return Map.empty
+    }
+    session.withActive {
+      SQLConf.withExistingConf(conf) {
+        try {
+          val optimized = 
session.sessionState.optimizer.execute(forStartup(plan))
+          // The planner of a micro-batch gets the values of the expressions 
that depend on when
+          // they are evaluated, which are deterministic.
+          val planned = optimized.transformUpWithSubqueries {
+            case node => node.transformExpressions {
+              case value: StartupValue => value.copy(planned = true)
+            }
+          }
+          val occurrences = mutable.ArrayBuffer.empty[(StreamingRelationV2, 
Reads)]
+          // Visits the nodes as the planner plans them: the projections and 
the filters over a
+          // relation are planned with its scan, and the other nodes on their 
own.
+          def visit(node: LogicalPlan): Unit = node match {
+            case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+              occurrences += relation -> Reads(
+                AttributeSet((project ++ filters).flatMap(_.references)),
+                Seq(filtersEvaluatedOnce(node, filters, 
conf).takeWhile(_.deterministic)))
+            case _ =>
+              node.children.foreach(visit)
+          }
+          visit(planned)
+          val relations = plan.collect { case relation: StreamingRelationV2 => 
relation }.toSet
+          val unknown = occurrences.map(_._1).filterNot(relations.contains)
+          if (unknown.nonEmpty) {
+            // The optimizer does not copy streaming relations: 
`DeduplicateRelations` keeps
+            // streaming plans as they are, so all the references to a common 
table expression,
+            // for example, have the same relation. A copy would share the 
scan of its relation in
+            // the micro-batches, so the scan would have to read what the copy 
reads too.
+            logWarning(log"The optimized streaming query reads the streaming 
relations " +
+              log"${MDC(LogKeys.STREAMING_TABLE, unknown.distinct.mkString(", 
"))} that its " +
+              log"plan does not have, so the scans of its sources read all 
their columns with " +
+              log"no filter.")
+            Map.empty
+          } else {
+            combine(occurrences.toSeq)
+          }
+        } catch {
+          case NonFatal(e) =>
+            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
+        }
+      }
+    }
+  }
+
+  /**
+   * Returns what the occurrences of each relation read, combined: the scan of 
a relation reads the
+   * rows of all its occurrences, so it reads the columns that any of them 
reads, and can only
+   * apply the filters that all of them apply (see `Reads`).
+   */
+  private def combine(
+      occurrences: Seq[(StreamingRelationV2, Reads)]): 
Map[StreamingRelationV2, Reads] = {
+    occurrences.groupBy(_._1).map { case (relation, reads) =>
+      relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_._2.requiredColumns)),
+        reads.flatMap(_._2.occurrenceFilters))
+    }
+  }
+
+  /**
+   * Returns whether `plan` has a node with a condition that the optimizer 
could push down to a
+   * relation: a filter, or a join, an as-of or a lateral join, or a set 
operation, which it may
+   * turn into one.
+   */
+  private def mayHaveConditions(plan: LogicalPlan): Boolean = plan.exists {
+    case _: Filter | _: Join | _: AsOfJoin | _: LateralJoin | _: SetOperation 
=> true
+    case _ => false
+  }
+
+  /**
+   * Returns the filters of `filters`, those of the projections and the 
filters of `node` over a
+   * relation, that each micro-batch evaluates once if they are pushed down. A 
micro-batch keeps a
+   * filter above a projection of a value of its own, such as 
`current_timestamp()`, which is not
+   * deterministic until its optimization ends, so it cannot merge it with the 
filter of the pushed
+   * filters below the projection, and only `PruneFilters`, with the 
constraints of the plan, prunes
+   * the copy above. Without the propagation of the constraints, or with 
`PruneFilters` excluded,
+   * the filters above such a projection are not pushed down.
+   */
+  private def filtersEvaluatedOnce(
+      node: LogicalPlan,
+      filters: Seq[Expression],
+      conf: SQLConf): Seq[Expression] = {
+    if (conf.constraintPropagationEnabled &&
+        !conf.optimizerExcludedRules.toSeq.flatMap(_.split(",")).map(_.trim)

Review Comment:
   Thank you. This one is moot now: following item 22, the function that 
predicted `PruneFilters` is gone, so nothing here reads 
`spark.sql.optimizer.excludedRules` any more.
   



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