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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,773 @@
+/*
+ * 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.SparkException
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, Expression, 
ExpressionSet, Generator, OuterReference, PredicateHelper, SubqueryExpression, 
Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
+import org.apache.spark.sql.catalyst.optimizer.{InferFiltersFromConstraints, 
InferFiltersFromGenerate, ReplaceExpressions}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
EventTimeWatermark, Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, 
SetOperation, Statistics, SubqueryAlias}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.{truncatedString, CharVarcharUtils}
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, 
SupportsRead, Table, 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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.execution.datasources.v2.{PushDownUtils, 
StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.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 applies the filters that the scan builder got 
to the rows of the
+ * relation, which the query applies anyway, so that the scan cannot drop a 
row that the plan keeps
+ * (see `withPushedFilters`), and its optimized plan drops the copies of these 
filters that the
+ * query applies above them (see `withoutRepeatedPushedFilters`). Otherwise, 
it is the plan without
+ * these pushdowns: the optimizer keeps deciding which columns every operator 
gets, and in which
+ * order, including the stateful ones. Only the scan node of the physical plan 
outputs the columns
+ * that the scan reads, and the planner checks that the micro-batch reads no 
other column of the
+ * relation. A scan cannot read other columns once its stream exists, so a 
micro-batch that does
+ * fails with STREAMING_SCAN_MISSING_COLUMNS, as when the configuration of the 
optimizer changes in
+ * the session of the query after it starts so that its plan reads other 
columns of a source.
+ *
+ * The other operations that the scans of batch queries can apply, such as 
aggregates and limits,
+ * apply to the data of all the micro-batches of a streaming query, which the 
scan of a micro-batch
+ * does not read, so they are not pushed down.
+ */
+private[sql] object StreamingV2ScanPushDown extends Logging with 
PredicateHelper {
+
+  /**
+   * 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 scanOutput the columns of the relation that the scan reads, in the 
order of its read
+   *                   schema, unless these are all its columns in their order
+   * @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,
+      scanOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression])
+
+  /**
+   * Returns the name of a streaming source in the errors of its scan: the 
parts of its identifier,
+   * with its catalog, or the name of its table.
+   */
+  def sourceName(
+      table: Table,
+      catalog: Option[CatalogPlugin],
+      identifier: Option[Identifier]): Seq[String] = (catalog, identifier) 
match {
+    case (Some(catalog), Some(identifier)) =>
+      (catalog.name +: identifier.namespace.toSeq) :+ identifier.name
+    case _ => Seq(table.name())
+  }
+
+  /**
+   * 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 of these pushdowns. 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 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, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    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) {
+        // The plan of a micro-batch is normalized before it is optimized, see 
`QueryExecution`.
+        val normalized = QueryExecution.normalize(session, plan)
+        val optimized = 
session.sessionState.optimizer.execute(forStartup(normalized))
+        val planned = forPlanning(optimized)
+        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. This must match
+        // the nodes that `DataSourceV2Strategy` plans the scans of streaming 
relations with.
+        def visit(node: LogicalPlan): Unit = node match {
+          case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+            occurrences += relation -> Reads(
+              AttributeSet((project ++ filters).flatMap(_.references)),
+              Seq(filters.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.
+          throw SparkException.internalError("The optimized streaming query 
reads the " +
+            s"streaming relations ${unknown.distinct.mkString(", ")} that its 
plan does not have.")
+        } else {
+          // 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`).
+          occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) 
=>
+            relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)),
+              reads.flatMap(_.occurrenceFilters))
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Checks that the query still applies the filters that the scans of its 
sources got when it
+   * started to all the rows that it reads from them, before a micro-batch 
reads its data: the plan
+   * is optimized again as when the query started (see 
`columnsAndFiltersOfSources`), with the
+   * configuration of the micro-batch, and each pushed filter must be one of 
the filters that all
+   * the reads of its relation apply. 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: the scan may
+   * drop rows that the query keeps, so the query fails before it reads them.
+   *
+   * @param pushedFilters the streaming relations whose scans got filters, 
with these filters, and
+   *                      the names of their sources in the errors (see 
`sourceName`)
+   */
+  def checkPushedFilters(
+      session: SparkSession,
+      plan: LogicalPlan,
+      pushedFilters: Seq[(StreamingRelationV2, Seq[Expression], 
Seq[String])]): Unit = {
+    if (pushedFilters.nonEmpty) {
+      val reads = readsOfSources(session, plan, None)

Review Comment:
   Done in 7b39a35: each micro-batch now checks the optimized plan that it 
runs, in `IncrementalExecution.optimizedPlan`, after `CurrentBatchTimestamp` 
gets its value. There is no second optimization anymore, so nothing can change 
between the check and the execution. For each occurrence of a relation whose 
scan got filters, the deterministic conditions of the filters over it, through 
deterministic projections with their aliases replaced (as `PhysicalOperation` 
finds them), must imply each pushed filter 
(`StreamingV2ScanPushDown.checkPushedFilters`). The `ChangingValue` test now 
uses `extra < v`. The micro-batch's plan has a larger value than the scan's 
`extra < 1`, so it would keep rows that the scan drops, and the micro-batch 
fails with `STREAMING_SCAN_FILTERS_CHANGED`. A new test calls 
`checkPushedFilters` directly on plans that apply a pushed filter or don't.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,773 @@
+/*
+ * 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.SparkException
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, Expression, 
ExpressionSet, Generator, OuterReference, PredicateHelper, SubqueryExpression, 
Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
+import org.apache.spark.sql.catalyst.optimizer.{InferFiltersFromConstraints, 
InferFiltersFromGenerate, ReplaceExpressions}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
EventTimeWatermark, Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, 
SetOperation, Statistics, SubqueryAlias}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.{truncatedString, CharVarcharUtils}
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, 
SupportsRead, Table, 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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.execution.datasources.v2.{PushDownUtils, 
StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.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 applies the filters that the scan builder got 
to the rows of the
+ * relation, which the query applies anyway, so that the scan cannot drop a 
row that the plan keeps
+ * (see `withPushedFilters`), and its optimized plan drops the copies of these 
filters that the
+ * query applies above them (see `withoutRepeatedPushedFilters`). Otherwise, 
it is the plan without
+ * these pushdowns: the optimizer keeps deciding which columns every operator 
gets, and in which
+ * order, including the stateful ones. Only the scan node of the physical plan 
outputs the columns
+ * that the scan reads, and the planner checks that the micro-batch reads no 
other column of the
+ * relation. A scan cannot read other columns once its stream exists, so a 
micro-batch that does
+ * fails with STREAMING_SCAN_MISSING_COLUMNS, as when the configuration of the 
optimizer changes in
+ * the session of the query after it starts so that its plan reads other 
columns of a source.
+ *
+ * The other operations that the scans of batch queries can apply, such as 
aggregates and limits,
+ * apply to the data of all the micro-batches of a streaming query, which the 
scan of a micro-batch
+ * does not read, so they are not pushed down.
+ */
+private[sql] object StreamingV2ScanPushDown extends Logging with 
PredicateHelper {
+
+  /**
+   * 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 scanOutput the columns of the relation that the scan reads, in the 
order of its read
+   *                   schema, unless these are all its columns in their order
+   * @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,
+      scanOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression])
+
+  /**
+   * Returns the name of a streaming source in the errors of its scan: the 
parts of its identifier,
+   * with its catalog, or the name of its table.
+   */
+  def sourceName(
+      table: Table,
+      catalog: Option[CatalogPlugin],
+      identifier: Option[Identifier]): Seq[String] = (catalog, identifier) 
match {
+    case (Some(catalog), Some(identifier)) =>
+      (catalog.name +: identifier.namespace.toSeq) :+ identifier.name
+    case _ => Seq(table.name())
+  }
+
+  /**
+   * 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 of these pushdowns. 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 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, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    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) {
+        // The plan of a micro-batch is normalized before it is optimized, see 
`QueryExecution`.
+        val normalized = QueryExecution.normalize(session, plan)
+        val optimized = 
session.sessionState.optimizer.execute(forStartup(normalized))
+        val planned = forPlanning(optimized)
+        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. This must match
+        // the nodes that `DataSourceV2Strategy` plans the scans of streaming 
relations with.
+        def visit(node: LogicalPlan): Unit = node match {
+          case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+            occurrences += relation -> Reads(
+              AttributeSet((project ++ filters).flatMap(_.references)),
+              Seq(filters.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.
+          throw SparkException.internalError("The optimized streaming query 
reads the " +
+            s"streaming relations ${unknown.distinct.mkString(", ")} that its 
plan does not have.")
+        } else {
+          // 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`).
+          occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) 
=>
+            relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)),
+              reads.flatMap(_.occurrenceFilters))
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Checks that the query still applies the filters that the scans of its 
sources got when it
+   * started to all the rows that it reads from them, before a micro-batch 
reads its data: the plan
+   * is optimized again as when the query started (see 
`columnsAndFiltersOfSources`), with the
+   * configuration of the micro-batch, and each pushed filter must be one of 
the filters that all
+   * the reads of its relation apply. 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: the scan may
+   * drop rows that the query keeps, so the query fails before it reads them.
+   *
+   * @param pushedFilters the streaming relations whose scans got filters, 
with these filters, and
+   *                      the names of their sources in the errors (see 
`sourceName`)
+   */
+  def checkPushedFilters(
+      session: SparkSession,
+      plan: LogicalPlan,
+      pushedFilters: Seq[(StreamingRelationV2, Seq[Expression], 
Seq[String])]): Unit = {
+    if (pushedFilters.nonEmpty) {
+      val reads = readsOfSources(session, plan, None)
+      pushedFilters.foreach { case (relation, filters, source) =>
+        val applied = ExpressionSet(reads.get(relation).toSeq.flatMap { read =>
+          DataSourceStrategy.normalizeExprs(read.filtersInAnyOrder, 
relation.output)

Review Comment:
   In 7b39a35 the check runs on the plan that runs, and it checks the rows, not 
the order: the conditions of the plan over each read must imply each pushed 
filter. I left the order out for two reasons:
   
   - A micro-batch's plan doesn't keep the order of the start, even when 
nothing changes. Its optimizer puts the filters that 
`InferFiltersFromConstraints` adds in front of the query's filters, and the 
optimization at the start excludes that rule. Examples are `isnotnull(payload)` 
before the cast, or `k > 5` inferred from the static side of a stream-static 
join. An order check would fail most queries with these builders, and I don't 
see a reliable way to tell the inferred filters apart in the optimized plan.
   - The order only decides whether the scan evaluates a pushed filter that may 
fail on a row that another filter would drop. In your example, that makes the 
micro-batch fail with `CAST_INVALID_INPUT`; it doesn't change which rows it 
returns, which is what the check guards.
   
   So the order is decided once, when the query starts, from the filters as the 
query applies them (`Reads.filters`). The case is written up as an open item in 
the PR description, linking this thread.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,773 @@
+/*
+ * 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.SparkException
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, Expression, 
ExpressionSet, Generator, OuterReference, PredicateHelper, SubqueryExpression, 
Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
+import org.apache.spark.sql.catalyst.optimizer.{InferFiltersFromConstraints, 
InferFiltersFromGenerate, ReplaceExpressions}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
EventTimeWatermark, Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, 
SetOperation, Statistics, SubqueryAlias}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.{truncatedString, CharVarcharUtils}
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, 
SupportsRead, Table, 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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.execution.datasources.v2.{PushDownUtils, 
StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.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 applies the filters that the scan builder got 
to the rows of the
+ * relation, which the query applies anyway, so that the scan cannot drop a 
row that the plan keeps
+ * (see `withPushedFilters`), and its optimized plan drops the copies of these 
filters that the
+ * query applies above them (see `withoutRepeatedPushedFilters`). Otherwise, 
it is the plan without
+ * these pushdowns: the optimizer keeps deciding which columns every operator 
gets, and in which
+ * order, including the stateful ones. Only the scan node of the physical plan 
outputs the columns
+ * that the scan reads, and the planner checks that the micro-batch reads no 
other column of the
+ * relation. A scan cannot read other columns once its stream exists, so a 
micro-batch that does
+ * fails with STREAMING_SCAN_MISSING_COLUMNS, as when the configuration of the 
optimizer changes in
+ * the session of the query after it starts so that its plan reads other 
columns of a source.
+ *
+ * The other operations that the scans of batch queries can apply, such as 
aggregates and limits,
+ * apply to the data of all the micro-batches of a streaming query, which the 
scan of a micro-batch
+ * does not read, so they are not pushed down.
+ */
+private[sql] object StreamingV2ScanPushDown extends Logging with 
PredicateHelper {
+
+  /**
+   * 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 scanOutput the columns of the relation that the scan reads, in the 
order of its read
+   *                   schema, unless these are all its columns in their order
+   * @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,
+      scanOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression])
+
+  /**
+   * Returns the name of a streaming source in the errors of its scan: the 
parts of its identifier,
+   * with its catalog, or the name of its table.
+   */
+  def sourceName(
+      table: Table,
+      catalog: Option[CatalogPlugin],
+      identifier: Option[Identifier]): Seq[String] = (catalog, identifier) 
match {
+    case (Some(catalog), Some(identifier)) =>
+      (catalog.name +: identifier.namespace.toSeq) :+ identifier.name
+    case _ => Seq(table.name())
+  }
+
+  /**
+   * 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 of these pushdowns. 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 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, Reads] = {
+    val conf = session.sessionState.conf.clone()
+    offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf))
+    conf.setConf(SQLConf.CBO_ENABLED, false)
+    conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+      (conf.optimizerExcludedRules.toSeq ++
+        Seq(InferFiltersFromConstraints.ruleName, 
InferFiltersFromGenerate.ruleName)).mkString(","))
+    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) {
+        // The plan of a micro-batch is normalized before it is optimized, see 
`QueryExecution`.
+        val normalized = QueryExecution.normalize(session, plan)
+        val optimized = 
session.sessionState.optimizer.execute(forStartup(normalized))
+        val planned = forPlanning(optimized)
+        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. This must match
+        // the nodes that `DataSourceV2Strategy` plans the scans of streaming 
relations with.
+        def visit(node: LogicalPlan): Unit = node match {
+          case PhysicalOperation(project, filters, relation: 
StreamingRelationV2) =>
+            occurrences += relation -> Reads(
+              AttributeSet((project ++ filters).flatMap(_.references)),
+              Seq(filters.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.
+          throw SparkException.internalError("The optimized streaming query 
reads the " +
+            s"streaming relations ${unknown.distinct.mkString(", ")} that its 
plan does not have.")
+        } else {
+          // 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`).
+          occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) 
=>
+            relation -> 
Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)),
+              reads.flatMap(_.occurrenceFilters))
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * Checks that the query still applies the filters that the scans of its 
sources got when it
+   * started to all the rows that it reads from them, before a micro-batch 
reads its data: the plan
+   * is optimized again as when the query started (see 
`columnsAndFiltersOfSources`), with the
+   * configuration of the micro-batch, and each pushed filter must be one of 
the filters that all
+   * the reads of its relation apply. 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: the scan may
+   * drop rows that the query keeps, so the query fails before it reads them.
+   *
+   * @param pushedFilters the streaming relations whose scans got filters, 
with these filters, and
+   *                      the names of their sources in the errors (see 
`sourceName`)
+   */
+  def checkPushedFilters(
+      session: SparkSession,
+      plan: LogicalPlan,
+      pushedFilters: Seq[(StreamingRelationV2, Seq[Expression], 
Seq[String])]): Unit = {
+    if (pushedFilters.nonEmpty) {
+      val reads = readsOfSources(session, plan, None)

Review Comment:
   This is moot in 7b39a35: the check no longer optimizes anything. It only 
walks the optimized plan of the micro-batch, so the optimizer and its 
extensions can't fail inside it, and the `internalError` of `readsOfSources` 
only runs when the query starts. The only error it raises is 
`STREAMING_SCAN_FILTERS_CHANGED`, which names 
`spark.sql.streaming.v2FilterPushdown.enabled`. As you say, a micro-batch can't 
fall back to no filter, because the scan already has the filters, so the way 
back is to disable the configuration and restart the query, and the error says 
so.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,773 @@
+/*
+ * 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.SparkException
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, Expression, 
ExpressionSet, Generator, OuterReference, PredicateHelper, SubqueryExpression, 
Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
+import org.apache.spark.sql.catalyst.optimizer.{InferFiltersFromConstraints, 
InferFiltersFromGenerate, ReplaceExpressions}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
EventTimeWatermark, Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, 
SetOperation, Statistics, SubqueryAlias}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.{truncatedString, CharVarcharUtils}
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, 
SupportsRead, Table, 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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.execution.datasources.v2.{PushDownUtils, 
StreamingDataSourceV2ScanRelation}
+import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.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 applies the filters that the scan builder got 
to the rows of the
+ * relation, which the query applies anyway, so that the scan cannot drop a 
row that the plan keeps
+ * (see `withPushedFilters`), and its optimized plan drops the copies of these 
filters that the
+ * query applies above them (see `withoutRepeatedPushedFilters`). Otherwise, 
it is the plan without
+ * these pushdowns: the optimizer keeps deciding which columns every operator 
gets, and in which
+ * order, including the stateful ones. Only the scan node of the physical plan 
outputs the columns
+ * that the scan reads, and the planner checks that the micro-batch reads no 
other column of the
+ * relation. A scan cannot read other columns once its stream exists, so a 
micro-batch that does
+ * fails with STREAMING_SCAN_MISSING_COLUMNS, as when the configuration of the 
optimizer changes in
+ * the session of the query after it starts so that its plan reads other 
columns of a source.
+ *
+ * The other operations that the scans of batch queries can apply, such as 
aggregates and limits,
+ * apply to the data of all the micro-batches of a streaming query, which the 
scan of a micro-batch
+ * does not read, so they are not pushed down.
+ */
+private[sql] object StreamingV2ScanPushDown extends Logging with 
PredicateHelper {
+
+  /**
+   * 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 scanOutput the columns of the relation that the scan reads, in the 
order of its read
+   *                   schema, unless these are all its columns in their order
+   * @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,
+      scanOutput: Option[Seq[AttributeReference]],
+      pushedFilters: Seq[Expression])
+
+  /**
+   * Returns the name of a streaming source in the errors of its scan: the 
parts of its identifier,
+   * with its catalog, or the name of its table.
+   */
+  def sourceName(
+      table: Table,
+      catalog: Option[CatalogPlugin],
+      identifier: Option[Identifier]): Seq[String] = (catalog, identifier) 
match {
+    case (Some(catalog), Some(identifier)) =>
+      (catalog.name +: identifier.namespace.toSeq) :+ identifier.name
+    case _ => Seq(table.name())
+  }
+
+  /**
+   * 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 of these pushdowns. 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 columnsAndFiltersOfSources(
+      session: SparkSession,
+      plan: LogicalPlan,
+      offsetLogMetadata: Option[OffsetSeqMetadataBase]): 
Map[StreamingRelationV2, Reads] = {
+    try {
+      readsOfSources(session, plan, offsetLogMetadata)
+    } catch {
+      case NonFatal(e)

Review Comment:
   Done in 7b39a35: the internal configuration now defaults to 
`Utils.isTesting`. The other suites that enable the pushdowns, such as 
`PythonStreamingDataSourceSuite` and `StreamingV2ScanPushDownRealTimeSuite`, 
now fail when the optimization at the start fails, and 
`StreamingV2ScanPushDownSuite` no longer sets it. The test of the fallback 
still sets it to false.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -1361,6 +1377,7 @@ class MicroBatchExecution(
     loggingThreadContext.put(LogKeys.BATCH_ID.name, execCtx.batchId.toString)
 
     execCtx.reportTimeTaken("queryPlanning") {
+      checkPushedFilters(sparkSessionToRunBatch)

Review Comment:
   This is gone in 7b39a35 along with the re-optimization. The check walks the 
optimized plan that `IncrementalExecution` already has. It returns right away 
when no scan got filters, otherwise visits each node once, and folds constants 
only for a read whose conditions make a column equal to a literal.
   



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