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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,740 @@
+/*
+ * 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, NamedExpression, 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
+import org.apache.spark.util.Utils
+
+/**
+ * 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. 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] = {
+    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) {
+        try {
+          // 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.
+          def visit(node: LogicalPlan): Unit = node match {
+            case ScanOfStream(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.
+            val message = 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."
+            if (Utils.isTesting) {
+              throw SparkException.internalError(message.message)
+            }
+            logWarning(message)
+            Map.empty
+          } 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))
+            }
+          }
+        } catch {
+          // The tests fail instead, so that they catch a regression of the 
optimization.
+          case NonFatal(e) if !Utils.isTesting =>
+            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 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 `plan` for the optimization when the query starts, so that the 
columns that it reads
+   * from its streaming relations do not depend on when it is optimized:
+   *  - The subtrees without a streaming relation, such as the static side of 
a join or the plan
+   *    of a static common table expression, and the subtrees of the plans of 
subqueries without
+   *    an outer reference, become placeholders of their outputs, so that 
nothing of them folds
+   *    into the plan: a micro-batch applies the cache, which may change after 
the query starts,
+   *    and their scans are neither built nor planned.
+   *  - The expressions whose values may depend on when they are evaluated or 
on the state of the
+   *    session, such as the current time or the conversions to dates and 
timestamps (see
+   *    `makesDateOrTimestamp`), become placeholders that are not 
deterministic for the optimizer,
+   *    as the current time of a micro-batch, and keep their children.
+   * Visible for tests.
+   */
+  private[sql] def forStartup(plan: LogicalPlan): LogicalPlan = 
withOpaqueSubqueries(
+    plan.transformDown {
+      case relation: BatchRelation => relation
+      // `WithCTE` keeps the definitions of its common table expressions as 
they are.
+      case definition: CTERelationDef if !definition.isStreaming =>
+        definition.copy(child = BatchRelation(definition.child))
+      case node if !node.isStreaming => BatchRelation(node)
+    }).transformUpWithSubqueries {
+    case node =>
+      // The expressions that ReplaceExpressions replaces with others when the 
optimization starts
+      // are replaced first, as the optimizer does, so that the conversions 
that they stand for,
+      // such as the cast of to_date('today'), are replaced below.
+      val replaced = if (node.containsPattern(RUNTIME_REPLACEABLE)) {
+        node.mapExpressions(ReplaceExpressions.replace)
+      } else {
+        node
+      }
+      replaced.transformExpressionsUp {
+        // 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)
+        case e if makesDateOrTimestamp(e) => StartupValue(e, e.children)
+      }
+  }
+
+  /**
+   * Returns `plan`, optimized when the query starts, as the planner of a 
micro-batch gets it: with
+   * the values of the expressions that depend on when they are evaluated, 
which are deterministic.
+   * Visible for tests.
+   */
+  private[sql] def forPlanning(plan: LogicalPlan): LogicalPlan = 
plan.transformUpWithSubqueries {
+    case node => node.transformExpressions {
+      case value: StartupValue => value.asPlanned
+    }
+  }
+
+  /**
+   * Returns `plan` with the subtrees of the plans of its subqueries that have 
no outer reference
+   * replaced by placeholders of their outputs, also in the subqueries of the 
others. The others
+   * keep the columns of the plan that they reference, which the plan reads.
+   */
+  private def withOpaqueSubqueries(plan: LogicalPlan): LogicalPlan = 
plan.transformUp {
+    case node => node.transformExpressions {
+      case subquery: SubqueryExpression =>
+        
subquery.withNewPlan(withOpaqueSubqueries(withOpaqueSubtrees(subquery.plan)._1))
+    }
+  }
+
+  // Returns `plan` with its subtrees that have no outer reference replaced by 
placeholders, and
+  // whether it has one, which each node finds once, from its children.
+  private def withOpaqueSubtrees(plan: LogicalPlan): (LogicalPlan, Boolean) = {
+    val (children, outer) = plan.children.map(withOpaqueSubtrees).unzip
+    if (outer.contains(true) || plan.expressions.exists(hasOuterReference)) {
+      plan.withNewChildren(children) -> true
+    } else {
+      BatchRelation(plan) -> false
+    }
+  }
+
+  // Whether `expression` references the columns of an outer query, also in 
its subqueries.
+  private def hasOuterReference(expression: Expression): Boolean = 
expression.exists {
+    case _: OuterReference => true
+    case subquery: SubqueryExpression =>
+      subquery.plan.exists(_.expressions.exists(hasOuterReference))
+    case _ => false
+  }
+
+  /**
+   * Matches the projections and the filters over a relation that the planner 
plans with the scan
+   * of the relation, as `DataSourceV2Strategy` does for the scans of 
streaming sources, so that
+   * the columns that a scan reads are those that its micro-batches plan.
+   */
+  private[sql] object ScanOfStream {
+    def unapply(plan: LogicalPlan): Option[(Seq[NamedExpression], 
Seq[Expression], LogicalPlan)] =
+      PhysicalOperation.unapply(plan)
+  }
+
+  /**
+   * Returns whether `expression` may make a date or a timestamp of a value 
without a date, which
+   * takes the date of when it is evaluated: a string with only a time such as 
'12:00:00', a
+   * special string such as 'today' or 'now', a time, or a variant with such a 
string. The
+   * optimizer evaluates such an expression once its children are constant, 
which they may only
+   * become during the optimization, as when an alias or an equality 
propagates a string, so the
+   * expression counts whatever its children are, if its type has a date or a 
timestamp, of any
+   * precision and time zone, at any depth: also the elements of an array, the 
keys or the values
+   * of a map, or the fields of a struct, and the type of one of its children 
has a string, a time
+   * or a variant at any depth.
+   *
+   * These are the casts, and the other conversions, such as `from_json` or 
`variant_get`, which
+   * only count if no child has a date or a timestamp: the expressions that 
have one, such as
+   * `named_struct`, `element_at` or an alias, pass on the dates and the 
timestamps of their
+   * children, whose own conversions are replaced. The expressions that the 
optimizer does not
+   * evaluate, such as aggregate functions or generators, which their 
operators need as they are,
+   * do not count.
+   */
+  private def makesDateOrTimestamp(expression: Expression): Boolean = 
expression match {
+    case _: Unevaluable | _: AggregateFunction | _: Generator => false
+    case cast: Cast =>
+      hasDateOrTimestamp(cast.dataType) && 
hasStringTimeOrVariant(cast.child.dataType)
+    case e =>
+      e.children.nonEmpty && hasDateOrTimestamp(e.dataType) &&
+        !e.children.exists(child => hasDateOrTimestamp(child.dataType)) &&
+        e.children.exists(child => hasStringTimeOrVariant(child.dataType))
+  }
+
+  private def hasDateOrTimestamp(dataType: DataType): Boolean = 
dataType.existsRecursively {
+    case _: AnyTimeType => false
+    case _: DatetimeType => true
+    case _ => false
+  }
+
+  private def hasStringTimeOrVariant(dataType: DataType): Boolean = 
dataType.existsRecursively {
+    case _: StringType | _: AnyTimeType | VariantType => true
+    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 
`columnsAndFiltersOfSources`).
+   * `reads` is only evaluated for such a scan. Otherwise, the scan reads all 
the columns of
+   * `output` with no filter, as the scans of streaming queries did before 
these pushdowns.
+   *
+   * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING` 
return the columns of the
+   * read schemas of the scans, in their order, so Spark asks each scan of 
such a table for its read
+   * schema before it creates the stream, whether the scan reads all the 
columns or not. A pruned
+   * scan must read the required columns and only columns of `output`, each 
once and with its
+   * type, as `SupportsPushDownRequiredColumns` requires. If the scan builder 
or the scan fails
+   * with the pushdowns, or the read schema of a pruned scan cannot be read or 
does not follow
+   * `SupportsPushDownRequiredColumns`, the scan is built again from a new 
scan builder: with the
+   * column pruning alone and then with the filters alone if it had both, and 
then with all the
+   * columns and no filter, as without these pushdowns. If the read schema of 
a scan of all the
+   * columns of such a table, with or without filters, does not follow the 
relation, the query
+   * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the 
column pruning, with
+   * which the scan node outputs the columns of the relation, as it did before 
the capability.
+   *
+   * The stream is created once, from the scan that the source reads, outside 
of the fallback: a
+   * stream can start to use the checkpoint of the source, or other resources, 
before it fails, so
+   * a failure of `createStream` fails the query, as it did without 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
+   * @param source the name of the source in the errors of its scan, see 
`sourceName`
+   */
+  def buildScan(
+      table: SupportsRead,
+      options: CaseInsensitiveStringMap,
+      output: Seq[AttributeReference],
+      conf: SQLConf,
+      reads: => Option[Reads],
+      source: Seq[String])(
+      createStream: Scan => SparkDataStream): StreamingScan = {
+    val capabilities = table.capabilities()
+    val returnsReadSchema = 
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
+    val builder = table.newScanBuilder(options)
+    val prunesColumns = returnsReadSchema && 
conf.streamingV2ColumnPruningEnabled &&
+      builder.isInstanceOf[SupportsPushDownRequiredColumns]
+    val 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 columns that the scan node of `scan`, a scan of all the columns, 
outputs.
+    def outputOfAllColumns(scan: Scan): Seq[AttributeReference] = {
+      if (returnsReadSchema) {
+        // The readers of the stream return the columns of the read schema, so 
a read schema that
+        // does not follow the relation fails the query when it starts: the 
scan node cannot
+        // output the columns of the relation in its place. Without the column 
pruning, the scan
+        // node outputs them instead, as it did before the capability.
+        def invalid(reason: String, cause: Throwable): Seq[AttributeReference] 
= {
+          if (conf.streamingV2ColumnPruningEnabled) {
+            throw 
QueryExecutionErrors.streamingScanInvalidReadSchemaError(source, reason, cause)
+          }
+          logWarning(log"The read schema of the scan of all the columns of the 
streaming table " +
+            log"${MDC(LogKeys.STREAMING_TABLE, table)} ${MDC(LogKeys.REASON, 
reason)}. Its scan " +
+            log"node outputs the columns of the relation, as the column 
pruning is disabled.")
+          output
+        }
+        Try(readOutput(scan.readSchema(), output, output)) match {
+          case Success(Right(columns)) => columns
+          case Success(Left(reason)) => invalid(reason, null)
+          case Failure(e) => invalid(s"could not be read: $e", e)
+        }
+      } else {
+        output
+      }
+    }
+    // The scan of all the columns with no filter, as without these pushdowns, 
and the columns that
+    // its scan node outputs.
+    def scanOfAllColumns(builder: ScanBuilder): (Scan, 
Seq[AttributeReference]) = {
+      val scan = build(builder, output, Nil)
+      scan -> outputOfAllColumns(scan)
+    }
+    // The scan of `columns` with `filters` and the columns that its scan node 
outputs, or why its
+    // read schema does not follow `SupportsPushDownRequiredColumns`. A scan 
of all the columns
+    // with filters is checked as one with no filter.
+    def scanWith(
+        builder: ScanBuilder,
+        columns: Seq[AttributeReference],
+        filters: Seq[Expression]): Either[String, (Scan, 
Seq[AttributeReference])] = {
+      val scan = build(builder, columns, filters)
+      if (!returnsReadSchema) {
+        Right(scan -> output)
+      } else if (columns.length == output.length) {
+        Right(scan -> outputOfAllColumns(scan))
+      } else {
+        readOutput(scan.readSchema(), output, columns).map(scan -> _)
+      }
+    }
+    // Tries the scans of `attempts`, the columns and the filters of each, in 
order, each from a
+    // new scan builder after the first, and then the scan of all the columns 
with no filter.
+    def firstScan(
+        attempts: Seq[(Seq[AttributeReference], Seq[Expression])],
+        builder: ScanBuilder): ((Scan, Seq[AttributeReference]), 
Seq[Expression]) = {
+      attempts match {
+        case Seq() => scanOfAllColumns(builder) -> Nil
+        case (columns, filters) +: rest =>
+          val (reason, cause) = Try(scanWith(builder, columns, filters)) match 
{
+            case Success(Right(built)) => return built -> filters
+            case Success(Left(reason)) => s"its read schema $reason" -> None
+            case Failure(e) => s"it failed with $e" -> Some(e)
+          }
+          // What the next scan reads: its columns, and its filters if it has 
some, or no filter
+          // after a scan with filters.
+          val (nextColumns, nextFilters) = rest.headOption.getOrElse(output -> 
Nil)
+          val nextRead = if (nextColumns.length < output.length) {
+            val names = nextColumns.map(_.name).mkString(", ")
+            log"only the columns ${MDC(LogKeys.COLUMN_NAMES, names)}"
+          } else {
+            log"all the columns"
+          }
+          val next = if (nextFilters.nonEmpty) {
+            nextRead + log" with the filters " +
+              log"${MDC(LogKeys.FILTER, nextFilters.map(_.sql).mkString(", 
"))}"
+          } else if (filters.nonEmpty) {
+            nextRead + log" with no filter"
+          } else {
+            nextRead
+          }
+          val message = if (filters.isEmpty) {
+            log"The scan of the streaming table ${MDC(LogKeys.STREAMING_TABLE, 
table)} could " +
+              log"not be built to read only the columns " +
+              log"${MDC(LogKeys.COLUMN_NAMES, columns.map(_.name).mkString(", 
"))}: " +
+              log"${MDC(LogKeys.REASON, reason)}. It reads " + next + log" 
instead."
+          } else {
+            val names = if (columns.length < output.length) {
+              columns.map(_.name).mkString(", ")
+            } else {
+              "all"
+            }
+            log"The scan of the streaming table ${MDC(LogKeys.STREAMING_TABLE, 
table)} could " +
+              log"not be built with the pushdowns (columns: 
${MDC(LogKeys.COLUMN_NAMES, names)}, " +
+              log"filters: ${MDC(LogKeys.FILTER, 
filters.map(_.sql).mkString(", "))}): " +
+              log"${MDC(LogKeys.REASON, reason)}. It reads " + next + log" 
instead."
+          }
+          cause match {
+            case Some(e) => logWarning(message, e)
+            case None => logWarning(message)
+          }
+          firstScan(rest, table.newScanBuilder(options))
+      }
+    }
+
+    val ((scan, scanOutput), pushedFilters) =
+      if (requiredOutput.length == output.length && filters.isEmpty) {
+        scanOfAllColumns(builder) -> Nil
+      } else {
+        // When the filters fail, the column pruning alone may still work, and 
when the column
+        // pruning fails, the filters alone.
+        val fewerPushdowns = if (filters.nonEmpty && requiredOutput.length < 
output.length) {
+          Seq(requiredOutput -> Nil, output -> filters)
+        } else {
+          Nil
+        }
+        firstScan((requiredOutput -> filters) +: fewerPushdowns, builder)
+      }
+    StreamingScan(scan, createStream(scan),
+      Some(scanOutput).filterNot(_.map(_.exprId) == output.map(_.exprId)), 
pushedFilters)
+  }
+
+  /**
+   * Returns the columns of `output` that a scan built to read 
`requiredOutput` reads, in the
+   * order of its read schema, or why the read schema does not follow
+   * `SupportsPushDownRequiredColumns`: each of its fields must be a column of 
`output`, once, with
+   * the type of the column, and it must have the columns of `requiredOutput`. 
The readers return
+   * strings for char and varchar columns, so these compare as strings, 
whether the relation or
+   * the read schema has them as strings or with their types. The columns keep 
their nullability,
+   * as the plans of the micro-batches are optimized with them.
+   */
+  private def readOutput(
+      readSchema: StructType,
+      output: Seq[AttributeReference],
+      requiredOutput: Seq[AttributeReference]): Either[String, 
Seq[AttributeReference]] = {
+    val columns = output.map(column => column.name -> column).toMap
+    val fields = readSchema.fields.toSeq
+    val names = fields.map(_.name)
+    val unknown = names.filterNot(columns.contains)
+    val repeated = names.diff(names.distinct).distinct
+    lazy val retyped = fields.filterNot { field =>
+      DataType.equalsIgnoreNullability(
+        CharVarcharUtils.replaceCharVarcharWithStringAlways(field.dataType),
+        
CharVarcharUtils.replaceCharVarcharWithStringAlways(columns(field.name).dataType))
+    }
+    lazy val readColumns = names.map(columns)
+    lazy val missing = 
requiredOutput.filterNot(AttributeSet(readColumns).contains)
+    if (unknown.nonEmpty) {
+      Left(s"${readSchema.simpleString} has the columns ${unknown.mkString(", 
")}, which the " +
+        "relation does not output")
+    } else if (repeated.nonEmpty) {
+      Left(s"${readSchema.simpleString} has the columns ${repeated.mkString(", 
")} more than once")
+    } else if (retyped.nonEmpty) {
+      Left(s"${readSchema.simpleString} has the columns 
${retyped.map(_.name).mkString(", ")} " +
+        "with other types than the relation outputs them with")
+    } else if (missing.nonEmpty) {
+      Left(s"${readSchema.simpleString} does not have the columns " +
+        s"${missing.map(_.name).mkString(", ")}")
+    } else {
+      Right(readColumns)
+    }
+  }
+
+  /**
+   * Returns `relation`, the relation of a streaming source in the plan of the 
query, with the
+   * filters that its scan builder got applied to its rows. The query applies 
them anyway, as they
+   * are the filters that it applies to all the rows that it reads from the 
source, so the plan of
+   * each micro-batch has the same result with them. With them, it also 
applies all the filters
+   * that the scan may apply, in any form, however the plan of the micro-batch 
is optimized, so the
+   * scan cannot drop a row that the plan keeps.
+   */
+  def withPushedFilters(relation: StreamingDataSourceV2ScanRelation): 
LogicalPlan = {

Review Comment:
   Agreed that it belongs in this PR, thank you. Each micro-batch now checks, 
before it reads its data, that the query still applies the pushed filters 
(`StreamingV2ScanPushDown.checkPushedFilters`, called before the 
`IncrementalExecution` of every micro-batch, and before each planning of a 
continuous query).
   
   The check optimizes the plan again exactly as at the start: same 
placeholders, opaque static subtrees, excluded inference rules, and the 
configuration of the micro-batch. Each pushed filter must be one of the filters 
that every read of its relation applies. If it is not, the query fails with the 
new error `STREAMING_SCAN_FILTERS_CHANGED` before the micro-batch reads 
anything, so no row is lost. The error names the source, the filters, and the 
conf to turn off.
   
   Why this design rather than comparing with the optimized plan of the 
micro-batch, which an earlier version of #59943 did and dropped: a micro-batch 
legitimately rewrites or drops its own copy when other filters imply it, e.g. 
an equality inferred through a static join folds `id > 0` away. The 
re-derivation compares the start with itself, so only a change of a value or of 
the configuration makes them differ. Checking only the first micro-batch would 
also miss the case you describe, since such a value is usually still the same 
right after the start.
   
   It costs one more such optimization per micro-batch, only when some scan got 
filters, which needs the opt-in conf. The conf doc says so.
   
   The new test "fail a micro-batch whose query no longer applies the filters 
that its scan got" uses a foldable expression whose value changes at each 
evaluation, as an unmodeled function of the time would. It checks that the 
first micro-batch fails with the new error. All the other filter tests pass 
through the check, so it reports no false positive on them.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,740 @@
+/*
+ * 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, NamedExpression, 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
+import org.apache.spark.util.Utils
+
+/**
+ * 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. 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] = {
+    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) {
+        try {
+          // 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.
+          def visit(node: LogicalPlan): Unit = node match {
+            case ScanOfStream(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.
+            val message = 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."
+            if (Utils.isTesting) {
+              throw SparkException.internalError(message.message)
+            }
+            logWarning(message)
+            Map.empty
+          } 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))
+            }
+          }
+        } catch {
+          // The tests fail instead, so that they catch a regression of the 
optimization.
+          case NonFatal(e) if !Utils.isTesting =>

Review Comment:
   Done. `Utils.isTesting` is replaced by the internal conf 
`spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` (false by 
default). The pushdown suites set it, so a regression of the optimization fails 
them, while the default, and so a connector suite, gets the user path. It 
covers both the failure of the optimization and the unknown relations, which 
now go through the same warning.
   
   The test is now "handle a failure of the optimization when the query 
starts", parameterized over the conf. With it, the query fails. Without it, the 
scan reads all the columns with no filter, the warning is logged, and the 
answer is right.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -0,0 +1,2168 @@
+/*
+ * 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.streaming
+
+import java.util
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.{AtomicInteger, AtomicLong}
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.logging.log4j.Level
+import org.scalatest.BeforeAndAfter
+
+import org.apache.spark.{SparkConf, SparkException}
+import org.apache.spark.sql.{DataFrame, Encoder, Encoders, Row}
+import org.apache.spark.sql.catalyst.{InternalRow, ProjectingInternalRow}
+import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeSet, Cast, 
EvalMode, Expression, GreaterThan, IsNotNull, Literal, RLike, ScalarSubquery}
+import org.apache.spark.sql.catalyst.optimizer.{ColumnPruning, PruneFilters}
+import org.apache.spark.sql.catalyst.plans.logical.{Filter, LogicalPlan, 
Project, WithCTE}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.{Dataset, SparkSession}
+import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable, 
InMemoryTableCatalog, SupportsRead, Table, TableCapability}
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.read.{InputPartition, PartitionReader, 
PartitionReaderFactory, Scan, ScanBuilder, SupportsPushDownFilters, 
SupportsPushDownRequiredColumns, SupportsPushDownV2Filters}
+import 
org.apache.spark.sql.connector.read.streaming.{ContinuousPartitionReader, 
ContinuousPartitionReaderFactory, ContinuousStream, MicroBatchStream, Offset, 
PartitionOffset}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
DataSourceV2Strategy, MicroBatchScanExec, StreamingDataSourceV2ScanRelation}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
MemoryStreamBaseClass, StreamExecution, StreamingQueryWrapper, 
StreamingV2ScanPushDown}
+import org.apache.spark.sql.execution.streaming.sources.ContinuousMemoryStream
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources.{Filter => SourceFilter}
+import org.apache.spark.sql.types.{CharType, IntegerType, StringType, 
StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
+
+class StreamingV2ScanPushDownSuite extends StreamTest with BeforeAndAfter {
+  import testImplicits._
+
+  private val tbl = "testcat.t"
+
+  // The pushdowns to the scans of streaming queries are disabled by default.
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED, true)
+    .set(SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED, true)
+
+  before {
+    spark.conf.set("spark.sql.catalog.testcat", 
classOf[InMemoryTableCatalog].getName)
+  }
+
+  after {
+    spark.sessionState.catalogManager.reset()
+    spark.conf.unset("spark.sql.catalog.testcat")
+  }
+
+  // Streams that drop the rows that fail the pushed filters.
+  private val filtering = InMemoryBaseTable.SIMULATE_STREAMING_FILTERS -> 
"true"
+
+  /**
+   * Creates the in-memory `table` with `columns`, `properties`, and the 
capability
+   * STREAMING_COLUMN_PRUNING and STREAMING_FILTER_PUSHDOWN, which in-memory 
tables
+   * do not have by default.
+   */
+  private def createTable(table: String, columns: String, properties: (String, 
String)*): Unit = {
+    val allProperties = (Seq(InMemoryBaseTable.STREAMING_COLUMN_PRUNING -> 
"true",
+      InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN -> "true") ++ 
properties).toMap
+    sql(s"CREATE TABLE $table ($columns) TBLPROPERTIES (" +
+      allProperties.map { case (key, value) => s"'$key' = '$value'" 
}.mkString(", ") + ")")
+  }
+
+  private def withSourceTable(properties: (String, String)*)(f: => Unit): Unit 
= {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, data string, extra int", properties: _*)
+      sql(s"INSERT INTO $tbl VALUES (1, 'a', 10), (2, 'b', 20)")
+      f
+    }
+  }
+
+  /** The columns that a streaming query needs from each of its sources, when 
it starts. */
+  private def reads(df: DataFrame): Map[StreamingRelationV2, 
StreamingV2ScanPushDown.Reads] =
+    StreamingV2ScanPushDown.columnsAndFiltersOfSources(spark, 
df.queryExecution.analyzed, None)
+
+  private def requiredColumns(df: DataFrame): Map[StreamingRelationV2, 
AttributeSet] =
+    reads(df).map { case (relation, read) => relation -> read.requiredColumns }
+
+  // The columns of each filter that all the reads of the sources of `df` 
apply first.
+  private def pushed(df: DataFrame): Seq[Set[String]] =
+    
reads(df).values.toSeq.flatMap(_.filters).map(_.references.map(_.name).toSet)
+
+  private def insert(values: String, table: String = tbl): StreamAction = 
Execute { _ =>
+    sql(s"INSERT INTO $table VALUES $values")
+  }
+
+  private def pruningEnabled(enabled: Boolean): Map[String, String] =
+    Map(SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> enabled.toString)
+
+  /**
+   * Runs `f`, which restarts streams with other values of the confs of these 
pushdowns, and then
+   * restores their values: `testStream` restores the value that a conf had 
before the last
+   * `StartStream` that set it, rather than before the first.
+   */
+  private def withPushDownConfsRestored(f: => Unit): Unit = withSQLConf(
+    SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "true",
+    SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key -> "true")(f)
+
+  private def filterPushdownEnabled(enabled: Boolean): Map[String, String] =
+    Map(SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key -> enabled.toString)
+
+  /** Returns the filters pushed down to the scan of each streaming source of 
the query. */
+  private def pushedFilters(query: StreamExecution): Seq[Seq[String]] = {
+    query.logicalPlan.collect {
+      case relation: StreamingDataSourceV2ScanRelation =>
+        relation.scan match {
+          case scan: InMemoryBaseTable#InMemoryBatchScan =>
+            scan.pushedFilters.map(_.toString).toSeq.sorted
+          case scan =>
+            fail(s"The scan $scan of ${relation.name} is not a scan of an 
in-memory table.")
+        }
+    }
+  }
+
+  /**
+   * Checks that the last micro-batch evaluates the filters on `column` once, 
apart from the
+   * IsNotNull that the optimizer infers.
+   */
+  private def assertEvaluatedOnce(columns: String*): StreamAction = 
AssertOnQuery { query =>
+    val conditions = query.lastExecution.optimizedPlan.collect {
+      case filter: Filter => filter.condition
+    }.flatMap(splitConjunctivePredicates).filter { condition =>
+      val names = condition.references.map(_.name).toSet
+      names.nonEmpty && names.subsetOf(columns.toSet)
+    }.filterNot(_.isInstanceOf[IsNotNull])
+    assert(conditions.length === 1, conditions)
+    true
+  }
+
+  /** Checks that the filters pushed down to the scan of each streaming source 
are `filters`. */
+  private def assertPushedFilters(filters: String*): StreamAction = 
AssertOnQuery { query =>
+    val pushed = pushedFilters(query)
+    assert(pushed.nonEmpty)
+    pushed.foreach(p => assert(p === filters.sorted))
+    true
+  }
+
+  /** Checks the read schemas of the scans of the streaming sources of the 
query. */
+  private def assertReadSchemas(columns: Seq[String]*): StreamAction = 
AssertOnQuery { query =>
+    val readSchemas = query.logicalPlan.collect {
+      case relation: StreamingDataSourceV2ScanRelation =>
+        relation.scan.readSchema().fieldNames.toSeq
+    }
+    assert(readSchemas.sortBy(_.mkString(",")) === 
columns.sortBy(_.mkString(",")))
+    true
+  }
+
+  /** Checks that the scan of each streaming source of the query reads 
`columns`. */
+  private def assertReadSchema(columns: String*): StreamAction = AssertOnQuery 
{ query =>
+    val readSchemas = query.logicalPlan.collect {
+      case relation: StreamingDataSourceV2ScanRelation =>
+        relation.scan.readSchema().fieldNames.toSeq
+    }
+    assert(readSchemas.nonEmpty)
+    readSchemas.foreach(readSchema => assert(readSchema === columns))
+    true
+  }
+
+  /** Checks the output of the scan nodes of the last micro-batch. */
+  private def assertScanOutputs(columns: Seq[String]*): StreamAction = 
AssertOnQuery { query =>
+    val outputs = query.lastExecution.executedPlan.collect {
+      case scan: MicroBatchScanExec => scan.output.map(_.name)
+    }
+    assert(outputs.sortBy(_.mkString(",")) === columns.sortBy(_.mkString(",")))
+    true
+  }
+
+  test("read only the columns that a streaming query needs, also after a 
restart") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl).where("extra > 10").select("data")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("data", "extra"),
+        assertScanOutputs(Seq("data", "extra")),
+        CheckAnswer(Row("b")),
+        StopStream,
+        insert("(3, 'c', 30), (4, 'd', 5)"),
+        StartStream(),
+        ProcessAllAvailable(),
+        assertReadSchema("data", "extra"),
+        CheckAnswer(Row("b"), Row("c")))
+    }
+  }
+
+  // Each case is a query over the source, and the columns that the optimizer 
reads for it, which
+  // fewer than those that the operators of its analyzed plan reference.
+  Seq[(String, DataFrame => DataFrame, Seq[String])](
+    ("a column that a later projection drops",
+      _.withColumn("x", lit(1)).select("data"), Seq("data")),
+    ("chained projections", _.select("id", "data").select("data"), 
Seq("data")),
+    ("expressions and functions that a later projection drops",
+      _.select(upper($"data").as("u"), ($"id" * 2).as("i")).select("u"), 
Seq("data")),
+    ("several aliases of a column",
+      _.select($"id".as("x"), $"data".as("y")).select($"x".as("z")).where("z > 
1"), Seq("id")),
+    ("a field of a struct of columns",
+      _.select(struct($"id", $"data").as("s")).select("s.data"), Seq("data")),
+    ("the fields of a struct of columns",
+      _.select(struct($"id", $"extra").as("s")).select("s.*"), Seq("id", 
"extra")),
+    ("a filter between projections",
+      _.select("id", "data").where("id > 1").select("data"), Seq("id", 
"data")),
+    ("a projection of all the columns", _.select("*").select("data"), 
Seq("data"))
+  ).foreach { case (name, query, columns) =>
+    test(s"read only the columns that the optimized query reads: $name") {
+      withSourceTable() {
+        val expected = query(spark.read.table(tbl)).collect().toSeq
+        testStream(query(spark.readStream.table(tbl)))(
+          ProcessAllAvailable(),
+          assertReadSchema(columns: _*),
+          assertScanOutputs(columns),
+          CheckAnswer(expected: _*))
+      }
+    }
+  }
+
+  Seq[(String, DataFrame => DataFrame)](
+    ("from_json", _.select(from_json($"json", new StructType().add("a", 
"int")).as("p"))
+      .select("p.a")),
+    ("get_json_object", _.select(get_json_object($"json", "$.a").as("a"))),
+    ("parse_json", _.select(parse_json($"json").as("v"))
+      .select(variant_get($"v", "$.a", "int").as("a")))
+  ).foreach { case (name, query) =>
+    test(s"read only the parsed column of $name") {
+      withTable(tbl) {
+        createTable(tbl, "id bigint, json string, extra int")
+        sql(s"""INSERT INTO $tbl VALUES (1, '{"a": 1}', 10), (2, '{"a": 2}', 
20)""")
+        val expected = query(spark.read.table(tbl)).collect().toSeq
+        testStream(query(spark.readStream.table(tbl)))(
+          ProcessAllAvailable(),
+          assertReadSchema("json"),
+          CheckAnswer(expected: _*))
+      }
+    }
+  }
+
+  test("read only the columns of a streaming aggregation, also after a 
restart") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl).groupBy("data").count()
+      testStream(df, OutputMode.Complete())(
+        ProcessAllAvailable(),
+        assertReadSchema("data"),
+        CheckAnswer(Row("a", 1L), Row("b", 1L)),
+        StopStream,
+        insert("(3, 'a', 30)"),
+        StartStream(),
+        ProcessAllAvailable(),
+        assertReadSchema("data"),
+        CheckAnswer(Row("a", 2L), Row("b", 1L)))
+    }
+  }
+
+  test("read only the event-time column of a time window") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, data string, ts timestamp")
+      sql(s"INSERT INTO $tbl VALUES " +
+        "(1, 'a', timestamp_seconds(0)), (2, 'b', timestamp_seconds(15))")
+      val df = spark.readStream.table(tbl).groupBy(window($"ts", "10 
seconds")).count()
+        .select($"window.start".cast("long"), $"count")
+      testStream(df, OutputMode.Complete())(
+        ProcessAllAvailable(),
+        assertReadSchema("ts"),
+        CheckAnswer(Row(0L, 1L), Row(10L, 1L)))
+    }
+  }
+
+  test("read no column of the source when the query needs none, also after a 
restart") {
+    withSourceTable() {
+      testStream(spark.readStream.table(tbl).groupBy().count(), 
OutputMode.Complete())(
+        ProcessAllAvailable(),
+        assertReadSchema(),
+        assertScanOutputs(Nil),
+        CheckAnswer(Row(2L)),
+        StopStream,
+        insert("(3, 'c', 30)"),
+        StartStream(),
+        ProcessAllAvailable(),
+        assertReadSchema(),
+        CheckAnswer(Row(3L)))
+      testStream(spark.readStream.table(tbl).select(lit(1).as("one")))(
+        ProcessAllAvailable(),
+        assertReadSchema(),
+        CheckAnswer(Row(1), Row(1), Row(1)))
+    }
+  }
+
+  test("read only the columns of a streaming deduplication, also after a 
restart") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl).dropDuplicates("data").select("id")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data"),
+        CheckAnswer(Row(1L), Row(2L)),
+        StopStream,
+        insert("(3, 'a', 30), (4, 'c', 40)"),
+        StartStream(),
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data"),
+        CheckAnswer(Row(1L), Row(2L), Row(4L)))
+    }
+  }
+
+  test("read the metadata columns that a streaming query needs") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl).select("data", "index")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("data", "index"),
+        CheckAnswerRowsByFunc(rows => {
+          assert(rows.map(_.getString(0)).sorted === Seq("a", "b"))
+          assert(rows.forall(!_.isNullAt(1)))
+        }, lastOnly = false))
+    }
+  }
+
+  test("read only the columns of each child of a union") {
+    withSourceTable() {
+      // Each read of the table has its own relation and scan, and the 
optimizer prunes the
+      // columns of each child of the union by position.
+      val twoReads = 
spark.readStream.table(tbl).union(spark.readStream.table(tbl)).select("data")
+      testStream(twoReads)(
+        ProcessAllAvailable(),
+        assertReadSchemas(Seq("data"), Seq("data")),
+        CheckAnswer(Row("a"), Row("b"), Row("a"), Row("b")))
+
+      val differentColumns = spark.readStream.table(tbl).select("id")
+        .union(spark.readStream.table(tbl).select($"extra".cast("long")))
+      testStream(differentColumns)(
+        ProcessAllAvailable(),
+        assertReadSchemas(Seq("id"), Seq("extra")),
+        CheckAnswer(Row(1L), Row(2L), Row(10L), Row(20L)))
+
+      // The children of a self-union read the same relation, whose scan reads 
the columns that
+      // both of them read.
+      val source = spark.readStream.table(tbl)
+      testStream(source.select("id", "data").union(source.select("id", 
"data")).select("data"))(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          val relations = query.logicalPlan.collect {
+            case relation: StreamingDataSourceV2ScanRelation => relation
+          }
+          assert(relations.length == 2 && 
relations.map(_.stream).distinct.length == 1)
+          assert(relations.head.scan.readSchema().fieldNames.toSeq === 
Seq("data"))
+          true
+        },
+        CheckAnswer(Row("a"), Row("b"), Row("a"), Row("b")))
+    }
+  }
+
+  test("read the columns that a scan returns when it reads more than the 
required ones") {
+    withSourceTable(InMemoryBaseTable.SIMULATE_PARTIAL_COLUMN_PRUNING -> 
"true") {
+      val df = spark.readStream.table(tbl).select("data", "index")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data", "extra", "index"),
+        CheckAnswerRowsByFunc(rows => {
+          assert(rows.map(_.getString(0)).sorted === Seq("a", "b"))
+          assert(rows.forall(!_.isNullAt(1)))
+        }, lastOnly = false))
+    }
+  }
+
+  Seq(
+    InMemoryBaseTable.SIMULATE_INCOMPLETE_COLUMN_PRUNING -> "does not have the 
columns data",
+    InMemoryBaseTable.SIMULATE_RETYPED_COLUMN_PRUNING ->
+      "has the columns data with other types than the relation outputs them 
with"
+  ).foreach { case (property, reason) =>
+    test(s"read all the columns when a scan does not read the required ones: 
$property") {
+      withSourceTable(property -> "true") {
+        val table = spark.sessionState.catalogManager.catalog("testcat")
+          
.asInstanceOf[InMemoryTableCatalog].liveTable(Identifier.of(Array.empty, "t"))
+          .asInstanceOf[InMemoryBaseTable]
+        val logAppender = new LogAppender("the fallback of streaming column 
pruning")
+        withLogAppender(logAppender,
+            loggerNames = 
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+            level = Some(Level.WARN)) {
+          testStream(spark.readStream.table(tbl).select("data"))(
+            ProcessAllAvailable(),
+            // The scan that does not read "data" is replaced by one of all 
the columns before its
+            // stream is created, so the source only has the stream of the 
scan of all the columns.
+            assertReadSchema("id", "data", "extra"),
+            assertScanOutputs(Seq("id", "data", "extra")),
+            AssertOnQuery(_ => table.createdMicroBatchStreams.get() == 1),
+            CheckAnswer(Row("a"), Row("b")))
+        }
+        val warnings = 
logAppender.loggingEvents.map(_.getMessage.getFormattedMessage)
+        assert(warnings.exists { message =>
+          message.contains("could not be built to read only the columns data") 
&&
+            message.contains(reason) &&
+            message.contains("It reads all the columns instead")
+        }, warnings)
+      }
+    }
+  }
+
+  test("keep the nullability of the columns of the relation when a scan 
reports another") {
+    withSourceTable(InMemoryBaseTable.SIMULATE_NON_NULLABLE_COLUMN_PRUNING -> 
"true") {
+      sql(s"INSERT INTO $tbl VALUES (3, NULL, 30)")
+      testStream(spark.readStream.table(tbl).select("data"))(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          val readSchemas = query.logicalPlan.collect {
+            case relation: StreamingDataSourceV2ScanRelation => 
relation.scan.readSchema()
+          }
+          assert(readSchemas.map(_.fields.map(f => f.name -> 
f.nullable).toSeq) ===
+            Seq(Seq("data" -> false)))
+          // The plan of each micro-batch is optimized with the columns of the 
relation, whose
+          // nullability the scan node keeps.
+          val outputs = query.lastExecution.executedPlan.collect {
+            case scan: MicroBatchScanExec => scan.output.map(a => a.name -> 
a.nullable)
+          }
+          assert(outputs === Seq(Seq("data" -> true)))
+          true
+        },
+        CheckAnswer(Row("a"), Row("b"), Row(null)))
+    }
+  }
+
+  test("read the columns of a scan of all the columns in the order of its read 
schema") {
+    withPushDownConfsRestored {
+      withSourceTable(InMemoryBaseTable.SIMULATE_REORDERED_COLUMN_PRUNING -> 
"true") {
+        // The streams of the table return the columns of the read schemas, 
which are in the
+        // reverse order, also when the pruning is disabled.
+        Seq(true, false).foreach { enabled =>
+          testStream(spark.readStream.table(tbl))(
+            StartStream(additionalConfs = pruningEnabled(enabled)),
+            ProcessAllAvailable(),
+            assertReadSchema("extra", "data", "id"),
+            assertScanOutputs(Seq("extra", "data", "id")),
+            CheckAnswer(Row(1L, "a", 10), Row(2L, "b", 20)))
+        }
+      }
+    }
+  }
+
+  test("read the event-time column of a watermark that the query does not 
output") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, data string, ts timestamp")
+      sql(s"INSERT INTO $tbl VALUES " +
+        "(1, 'a', timestamp_seconds(0)), (2, 'b', timestamp_seconds(10))")
+      val df = spark.readStream.table(tbl).withWatermark("ts", "5 
seconds").select("data")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("data", "ts"),
+        CheckAnswer(Row("a"), Row("b")),
+        // The watermark gets the event times of the rows.
+        AssertOnQuery { query =>
+          query.recentProgress.filter(_.numInputRows > 
0).map(_.eventTime.get("max")).toSeq ==
+            Seq("1970-01-01T00:00:10.000Z")
+        })
+    }
+  }
+
+  test("read only the columns of a stream-static join") {
+    withSourceTable() {
+      val static = spark.range(2, 4).toDF("sid")
+      val source = spark.readStream.table(tbl)
+      val df = source.join(static, source("id") === 
static("sid")).select("data")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data"),
+        CheckAnswer(Row("b")),
+        insert("(3, 'c', 30), (4, 'd', 40)"),
+        ProcessAllAvailable(),
+        CheckAnswer(Row("b"), Row("c")))
+    }
+  }
+
+  test("read only the columns of each side of a stream-stream join, also after 
a restart") {
+    withSourceTable() {
+      val left = spark.readStream.table(tbl).select("id", "data")
+      val right = spark.readStream.table(tbl).selectExpr("id AS rid", "extra")
+      val df = left.join(right, left("id") === right("rid")).select("data", 
"extra")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchemas(Seq("id", "data"), Seq("id", "extra")),
+        CheckAnswer(Row("a", 10), Row("b", 20)),
+        StopStream,
+        insert("(3, 'c', 30)"),
+        StartStream(),
+        ProcessAllAvailable(),
+        assertReadSchemas(Seq("id", "data"), Seq("id", "extra")),
+        CheckAnswer(Row("a", 10), Row("b", 20), Row("c", 30)))
+    }
+  }
+
+  test("keep the layout of the state of a stream-stream join across the values 
of the conf " +
+      "when a scan returns the columns in another order") {
+    withPushDownConfsRestored {
+      val (leftTable, rightTable) = ("testcat.l", "testcat.r")
+      withTable(leftTable, rightTable) {
+        createTable(leftTable, "k bigint, v bigint, unused int",
+          InMemoryBaseTable.SIMULATE_REORDERED_COLUMN_PRUNING -> "true")
+        createTable(rightTable, "rk bigint, w int")
+        // The left row is kept in the state of the join, which is written 
without pruning first.
+        sql(s"INSERT INTO $leftTable VALUES (1, 100, 0)")
+        val left = spark.readStream.table(leftTable)
+        val right = spark.readStream.table(rightTable)
+        val df = left.join(right, $"k" === $"rk").select("v", "w")
+        testStream(df)(
+          StartStream(additionalConfs = pruningEnabled(false)),
+          ProcessAllAvailable(),
+          // The scan of all the columns returns them in the reverse order too.
+          assertReadSchemas(Seq("unused", "v", "k"), Seq("rk", "w")),
+          CheckAnswer(),
+          StopStream,
+          // The pruned scan returns (v, k), and the join still gets (k, v).
+          insert("(1, 7)", rightTable),
+          StartStream(additionalConfs = pruningEnabled(true)),
+          ProcessAllAvailable(),
+          assertReadSchemas(Seq("v", "k"), Seq("rk", "w")),
+          CheckAnswer(Row(100L, 7)),
+          // And the other way around.
+          insert("(2, 200, 0)", leftTable),
+          ProcessAllAvailable(),
+          StopStream,
+          insert("(2, 8)", rightTable),
+          StartStream(additionalConfs = pruningEnabled(false)),
+          ProcessAllAvailable(),
+          CheckAnswer(Row(100L, 7), Row(200L, 8)))
+      }
+    }
+  }
+
+  test("keep the state of a streaming aggregation across the values of the 
conf when a scan " +
+      "returns the columns in another order") {
+    withPushDownConfsRestored {
+      withTable(tbl) {
+        createTable(tbl, "k bigint, v bigint, unused int",
+          InMemoryBaseTable.SIMULATE_REORDERED_COLUMN_PRUNING -> "true")
+        sql(s"INSERT INTO $tbl VALUES (1, 10, 0), (2, 20, 0)")
+        val df = spark.readStream.table(tbl).groupBy("k").agg(sum("v"))
+        testStream(df, OutputMode.Complete())(
+          StartStream(additionalConfs = pruningEnabled(false)),
+          ProcessAllAvailable(),
+          assertReadSchema("unused", "v", "k"),
+          CheckAnswer(Row(1L, 10L), Row(2L, 20L)),
+          StopStream,
+          insert("(1, 1, 0)"),
+          StartStream(additionalConfs = pruningEnabled(true)),
+          ProcessAllAvailable(),
+          assertReadSchema("v", "k"),
+          CheckAnswer(Row(1L, 11L), Row(2L, 20L)),
+          StopStream,
+          insert("(2, 2, 0)"),
+          StartStream(additionalConfs = pruningEnabled(false)),
+          ProcessAllAvailable(),
+          CheckAnswer(Row(1L, 11L), Row(2L, 22L)))
+      }
+    }
+  }
+
+  test("fail to plan a micro-batch that reads a column that its scan does not 
read") {
+    withSourceTable() {
+      testStream(spark.readStream.table(tbl).select("data"))(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          val relation = query.logicalPlan.collectFirst {
+            case relation: StreamingDataSourceV2ScanRelation => relation
+          }.get
+          assert(relation.output.map(_.name) === Seq("id", "data", "extra"))
+          assert(relation.scanOutput.map(_.map(_.name)) === Some(Seq("data")))
+          assert(relation.simpleString(10).contains("ScanOutput: [data#"))
+          val offset = relation.stream.initialOffset()
+          val batch = relation.copy(startOffset = Some(offset), endOffset = 
Some(offset))
+          // Unlike the query, this plan reads all the columns of the relation.
+          checkError(
+            exception = intercept[SparkException] {
+              spark.sessionState.planner.plan(Project(relation.output, 
batch)).next()
+            },
+            condition = "STREAMING_SCAN_MISSING_COLUMNS",
+            parameters = Map(
+              "columns" -> "`id`, `extra`",
+              "source" -> "`testcat`.`t`",
+              "config" -> 
s"\"${SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key}\""))
+          true
+        })
+    }
+  }
+
+  test("read only the columns that a continuous query needs") {
+    val input = ContinuousMemoryStream.singlePartition[(Long, String, Int)]
+    val table = new PruningContinuousTable(input, takesFilters = false)
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"pruning_continuous", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra").where("extra > 10").select("data")
+    withTempView("continuous_pruning") {
+      val query = 
df.writeStream.format("memory").queryName("continuous_pruning")
+        .trigger(Trigger.Continuous(100)).start()
+      try {
+        input.addData((1L, "a", 10), (2L, "b", 20), (3L, "c", 30))
+        eventually(timeout(streamingTimeout)) {
+          checkAnswer(spark.table("continuous_pruning"), Seq(Row("b"), 
Row("c")))
+        }
+        val readSchemas = 
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.logicalPlan
+          .collect { case r: StreamingDataSourceV2ScanRelation => 
r.scan.readSchema().fieldNames }
+        assert(readSchemas.map(_.toSeq) === Seq(Seq("_2", "_3")))
+      } finally {
+        query.stop()
+      }
+    }
+  }
+
+  test("push the filters of a streaming query down to the scan of its source") 
{
+    // The suite enables the filter pushdown, which is disabled by default.
+    assert(!SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.defaultValue.get)
+    withPushDownConfsRestored {
+      withSourceTable() {
+        val df = spark.readStream.table(tbl).where("extra > 10").select("data")
+        testStream(df)(
+          StartStream(additionalConfs = filterPushdownEnabled(true)),
+          ProcessAllAvailable(),
+          assertPushedFilters("GreaterThan(extra,10)"),
+          // The scan of the in-memory table does not apply the filters, which 
Spark evaluates.
+          CheckAnswer(Row("b")),
+          StopStream,
+          insert("(3, 'c', 30), (4, 'd', 5)"),
+          StartStream(additionalConfs = filterPushdownEnabled(false)),
+          ProcessAllAvailable(),
+          assertPushedFilters(),
+          CheckAnswer(Row("b"), Row("c")),
+          StopStream,
+          insert("(5, 'e', 50), (6, 'f', 6)"),
+          StartStream(additionalConfs = filterPushdownEnabled(true)),
+          ProcessAllAvailable(),
+          assertPushedFilters("GreaterThan(extra,10)"),
+          CheckAnswer(Row("b"), Row("c"), Row("e")))
+      }
+    }
+  }
+
+  test("push down only the filters that every read of a relation applies") {
+    withSourceTable() {
+      val source = spark.readStream.table(tbl)
+      val df = source.where("extra > 10").union(source.where("extra > 10 AND 
id > 1"))
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertPushedFilters("GreaterThan(extra,10)"),
+        CheckAnswer(Row(2L, "b", 20), Row(2L, "b", 20)))
+    }
+  }
+
+  // Each case is a condition on a value that the optimizer of each 
micro-batch folds into its own
+  // value, such as its current time, and the column that it reads.
+  Seq(
+    "ts < current_timestamp()" -> "ts",
+    "ts < now()" -> "ts",
+    "CAST(ts AS DATE) < current_date()" -> "ts",
+    "CAST(ts AS TIMESTAMP_NTZ) < localtimestamp()" -> "ts",
+    "tod < current_time()" -> "tod",
+    "CAST(tod AS TIMESTAMP_NTZ) < TIMESTAMP_NTZ'2100-01-01 00:00:00'" -> "tod",
+    "CAST(tod AS TIMESTAMP) < TIMESTAMP'2100-01-01 00:00:00'" -> "tod",
+    "data = current_database()" -> "data",
+    "data = current_timezone()" -> "data",
+    // The casts of the special strings, which SpecialDatetimeValues folds.
+    "d = 'today'" -> "d",
+    "ts < 'now'" -> "ts",
+    "d = to_date('today')" -> "d",
+    "d < CAST('tomorrow' AS DATE)" -> "d",
+    "CAST(ts AS TIMESTAMP_NTZ) > CAST('yesterday' AS TIMESTAMP_NTZ)" -> "ts",
+    // The casts of strings with only a time to timestamps, which take the 
current date.
+    "ts < '12:00:00'" -> "ts",
+    "ts > CAST('T09:30:00' AS TIMESTAMP)" -> "ts",
+    // Every cast of a string to a timestamp with local time zone is a 
placeholder when the query
+    // starts, also of a string with a date, or of a string column. A 
follow-up could push these
+    // down again when their values do not depend on the date.
+    "CAST(data AS TIMESTAMP) < TIMESTAMP'2100-01-01 00:00:00'" -> "data",
+    "ts < '2100-01-01 12:00:00'" -> "ts"
+  ).foreach { case (condition, column) =>
+    test(s"do not push down a filter on a value that depends on when it is 
evaluated: $condition") {
+      withTable(tbl) {
+        createTable(tbl, "id bigint, data string, ts timestamp, tod time, d 
date")
+        val df = spark.readStream.table(tbl).where(s"id > 1 AND 
$condition").select("id")
+        val read = reads(df).values.toSeq match { case Seq(read) => read }
+        // The column of the condition is still read, but only the filter on 
the id is pushed down.
+        assert(read.requiredColumns.map(_.name).toSet === Set("id", column))
+        assert(read.filters.nonEmpty)
+        assert(read.filters.forall(_.references.map(_.name).toSet == 
Set("id")), read.filters)
+      }
+    }
+  }
+
+  test("do not push down a filter on the current time of a micro-batch") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, data string, ts timestamp")
+      sql(s"INSERT INTO $tbl VALUES " +
+        "(1, 'a', timestamp_seconds(0)), (2, 'b', timestamp_seconds(10))")
+      // Each micro-batch has its own current time, so the time when the query 
started cannot be
+      // pushed down in its place.
+      Seq("current_timestamp()", "now()").foreach { time =>
+        val df = spark.readStream.table(tbl).where(s"id > 0 AND ts < 
$time").select("data")
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertPushedFilters("GreaterThan(id,0)"),
+          CheckAnswer(Row("a"), Row("b")))
+      }
+    }
+  }
+
+  test("read the columns and apply the filters of every reference to a common 
table expression") {
+    withSourceTable() {
+      withTempView("s") {
+        spark.readStream.table(tbl).createOrReplaceTempView("s")
+        // Both references to the common table expression have the relation of 
the source, so its
+        // scan reads the columns of both, and applies no filter, as only one 
of them filters.
+        val df = sql("WITH c AS (SELECT * FROM s) " +
+          "SELECT a.id, b.extra FROM c a JOIN c b ON a.id = b.id WHERE a.data 
= 'a'")
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("id", "data", "extra"),
+          assertPushedFilters(),
+          CheckAnswer(Row(1L, 10)),
+          insert("(3, 'a', 30)"),
+          ProcessAllAvailable(),
+          CheckAnswer(Row(1L, 10), Row(3L, 30)))
+
+        // Each reference applies its own filter.
+        val pruned = sql("WITH c AS (SELECT * FROM s) " +
+          "SELECT data FROM c WHERE extra > 15 UNION ALL SELECT data FROM c 
WHERE extra < 15")
+        testStream(pruned)(
+          ProcessAllAvailable(),
+          assertReadSchema("data", "extra"),
+          assertPushedFilters(),
+          CheckAnswer(Row("a"), Row("a"), Row("b")))
+      }
+    }
+  }
+
+  test("push down no filter that the optimizer infers from the filters of 
another source") {
+    val otherTable = "testcat.other"
+    withSourceTable() {
+      withTable(otherTable) {
+        createTable(otherTable, "oid bigint, value string")
+        val source = spark.readStream.table(tbl)
+        val other = spark.readStream.table(otherTable).where("oid < 3")
+        val df = source.join(other, source("id") === 
other("oid")).select("data", "value")
+        testStream(df)(
+          ProcessAllAvailable(),
+          // The optimizer infers a filter on the id of the source from the 
one on the other
+          // source, which is not pushed down: a scan only gets the filters 
that the query applies
+          // to its own source.
+          AssertOnQuery { query =>
+            assert(pushedFilters(query).sortBy(_.mkString) === Seq(Nil, 
Seq("LessThan(oid,3)")))
+            true
+          },
+          CheckAnswer(),
+          insert("(1, 'x'), (2, 'y'), (3, 'z')", otherTable),
+          ProcessAllAvailable(),
+          CheckAnswer(Row("a", "x"), Row("b", "y")),
+          insert("(3, 'c', 30)"),
+          ProcessAllAvailable(),
+          CheckAnswer(Row("a", "x"), Row("b", "y")))
+      }
+    }
+  }
+
+  test("plan the micro-batches whose filters imply the pushed filters in 
another form") {
+    val otherTable = "testcat.other"
+    withSourceTable() {
+      withTable(otherTable) {
+        createTable(otherTable, "oid bigint, value string")
+        sql(s"INSERT INTO $otherTable VALUES (1, 'x'), (2, 'y')")
+        // A micro-batch infers id = 2 from the equality of the static side, 
and puts its value in
+        // place of the column in the pushed filter id > 0, which it then 
drops: id = 2 implies it.
+        val source = spark.readStream.table(tbl)
+        val static = spark.range(1, 3).toDF("sid").where("sid = 2")
+        val joined = source.where("id > 0").join(static, source("id") === 
static("sid"))
+        testStream(joined.select("data"))(
+          ProcessAllAvailable(),
+          assertPushedFilters("GreaterThan(id,0)"),
+          CheckAnswer(Row("b")))
+        // So does a stream-stream join, in the micro-batches where both 
sources have data.
+        val other = spark.readStream.table(otherTable).where("oid = 2")
+        val streams = source.where("id > 0").join(other, source("id") === 
other("oid"))
+        testStream(streams.select("data", "value"))(
+          ProcessAllAvailable(),
+          CheckAnswer(Row("b", "y")),
+          insert("(2, 'bb', 22)"),
+          insert("(2, 'yy')", otherTable),
+          ProcessAllAvailable(),
+          CheckAnswer(Row("b", "y"), Row("b", "yy"), Row("bb", "y"), Row("bb", 
"yy")))
+      }
+    }
+  }
+
+  test("plan the micro-batches that fold a value of their own into a pushed 
filter") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, owner string, d date")
+      sql(s"INSERT INTO $tbl VALUES (1, current_user(), current_date()), (2, 
'other', NULL)")
+      // A micro-batch folds current_user() and now() into literals, which it 
then puts in place
+      // of the columns in the pushed filters owner <> '' and d >= 
DATE'2020-01-01'.
+      testStream(spark.readStream.table(tbl).where("owner <> '' AND owner = 
current_user()")
+          .select("id"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("Not(EqualTo(owner,))"),
+        CheckAnswer(Row(1L)))
+      testStream(spark.readStream.table(tbl)
+          .where("d >= DATE'2020-01-01' AND d = to_date(now())").select("id"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("GreaterThanOrEqual(d,2020-01-01)"))
+    }
+  }
+
+  test("read only the columns of a join with a static common table 
expression") {
+    withSourceTable() {
+      withTempView("s") {
+        spark.readStream.table(tbl).createOrReplaceTempView("s")
+        val df = sql("WITH dims AS (SELECT id AS sid FROM range(2, 4)) " +
+          "SELECT s.data FROM s JOIN dims ON s.id = dims.sid")
+        // The definition of the common table expression stays in the plan 
optimized when the
+        // query starts, with a placeholder of its plan.
+        assert(df.queryExecution.analyzed.exists(_.isInstanceOf[WithCTE]))
+        assert(requiredColumns(df).values.map(_.map(_.name).toSet).toSeq ===
+          Seq(Set("id", "data")))
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("id", "data"),
+          CheckAnswer(Row("b")))
+      }
+    }
+  }
+
+  test("read the columns of a condition on a subquery, whatever its plan is") {
+    withSourceTable() {
+      withTempView("s") {
+        spark.readStream.table(tbl).createOrReplaceTempView("s")
+        // The plan of the subquery does not fold into the plan optimized when 
the query starts,
+        // as a micro-batch may replace it with the cache, so the scan reads 
both columns.
+        val df = sql("SELECT CASE WHEN (SELECT true) THEN data ELSE CAST(extra 
AS STRING) END " +
+          "AS v FROM s")
+        assert(requiredColumns(df).values.map(_.map(_.name).toSet).toSeq ===
+          Seq(Set("data", "extra")))
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("data", "extra"),
+          CheckAnswer(Row("a"), Row("b")))
+        // The nodes of a subquery that reference the columns of the query 
stay, so the scan reads
+        // these columns.
+        val correlated = sql("SELECT data FROM s " +
+          "WHERE EXISTS (SELECT 1 FROM range(0, 2) r WHERE r.id + 1 = s.id)")
+        
assert(requiredColumns(correlated).values.map(_.map(_.name).toSet).toSeq ===
+          Seq(Set("id", "data")))
+        testStream(correlated)(
+          ProcessAllAvailable(),
+          assertReadSchema("id", "data"),
+          CheckAnswer(Row("a"), Row("b")))
+      }
+    }
+  }
+
+  // The values that the optimizer computes from the clock or from the 
session, which have the
+  // pattern CURRENT_LIKE, by which ComputeCurrentTime and ReplaceCurrentLike 
find them.
+  Seq(
+    "current_timezone() = 'UTC'",
+    "current_date() > DATE'2000-01-01'",
+    "curdate() > DATE'2000-01-01'",
+    "current_timestamp() > TIMESTAMP'2000-01-01 00:00:00'",
+    "now() > TIMESTAMP'2000-01-01 00:00:00'",
+    "localtimestamp() > TIMESTAMP_NTZ'2000-01-01 00:00:00'",
+    "current_time() >= TIME'00:00:00'",
+    "localtime() >= TIME'00:00:00'",
+    "current_database() = 'default'",
+    "current_schema() = 'default'",
+    "current_catalog() = 'spark_catalog'",
+    "length(current_path()) >= 0",
+    "length(current_user()) >= 0",
+    "length(user()) >= 0",
+    "length(session_user()) >= 0"
+  ).foreach { condition =>
+    test(s"read the columns of a condition on a value of the clock or the 
session: $condition") {
+      withSourceTable() {
+        // Each micro-batch gets its own value, which may differ from the 
value when the query
+        // starts, so the condition is not folded then, and the scan reads 
both columns.
+        val df = spark.readStream.table(tbl).select(expr(s"CASE WHEN 
$condition THEN data " +
+          "ELSE CAST(extra AS STRING) END AS v"))
+        assert(requiredColumns(df).values.map(_.map(_.name).toSet).toSeq ===
+          Seq(Set("data", "extra")))
+        val holds = sql(s"SELECT $condition").head().getBoolean(0)
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("data", "extra"),
+          CheckAnswer((if (holds) Seq("a", "b") else Seq("10", 
"20")).map(Row(_)): _*))
+      }
+    }
+  }
+
+  Seq(
+    "CAST('today' AS DATE) < DATE'2100-01-01'",
+    "CAST('12:00:00' AS TIMESTAMP) < TIMESTAMP'2100-01-01 00:00:00'",
+    // The casts of strings to arrays, structs and maps of timestamps cast 
each string.
+    "element_at(CAST(array('12:00:00') AS ARRAY<TIMESTAMP>), 1) < 
TIMESTAMP'2100-01-01 00:00:00'",
+    "CAST(named_struct('t', '12:00:00') AS STRUCT<t: TIMESTAMP>).t < " +
+      "TIMESTAMP'2100-01-01 00:00:00'",
+    "element_at(CAST(map('k', '12:00:00') AS MAP<STRING, TIMESTAMP>), 'k') < " 
+
+      "TIMESTAMP'2100-01-01 00:00:00'",
+    // The casts of times to timestamps take the current date, at any depth 
too.
+    "CAST(TIME'12:00:00' AS TIMESTAMP_NTZ) < TIMESTAMP_NTZ'2100-01-01 
00:00:00'",
+    "element_at(CAST(array(TIME'12:00:00') AS ARRAY<TIMESTAMP>), 1) < " +
+      "TIMESTAMP'2100-01-01 00:00:00'",
+    // So do the other conversions of strings, and of variants that have them, 
to timestamps.
+    """from_json('{"t": "12:00:00"}', 't TIMESTAMP').t < TIMESTAMP'2100-01-01 
00:00:00'""",
+    """variant_get(parse_json('"12:00:00"'), '$', 'timestamp') < """ +
+      "TIMESTAMP'2100-01-01 00:00:00'",
+    """CAST(parse_json('"12:00:00"') AS TIMESTAMP) < TIMESTAMP'2100-01-01 
00:00:00'"""
+  ).foreach { condition =>
+    test(s"read the columns of a condition on a value that depends on when it 
is converted: " +
+        condition) {
+      withSourceTable() {
+        // The condition takes the date of each micro-batch, so the scan reads 
both columns.
+        val df = spark.readStream.table(tbl).select(expr(s"CASE WHEN 
$condition THEN data " +
+          "ELSE CAST(extra AS STRING) END AS v"))
+        val reads = requiredColumns(df)
+        assert(reads.values.map(_.map(_.name).toSet).toSeq ===
+          Seq(Set("data", "extra")))
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("data", "extra"),
+          CheckAnswer(Row("a"), Row("b")))
+      }
+    }
+  }
+
+  test("read the columns of a condition on a cast whose string is a literal 
only once optimized") {
+    withSourceTable() {
+      // The cast of `cutoff` is only foldable once the optimizer replaces the 
alias with the
+      // string, and then takes the date of the start of the query, so the 
condition would be
+      // folded with it if the cast stayed a cast.
+      val df = spark.readStream.table(tbl).withColumn("cutoff", 
lit("12:00:00"))
+        .select(expr("CASE WHEN CAST(cutoff AS TIMESTAMP) < 
TIMESTAMP'2100-01-01 00:00:00' " +
+          "THEN data ELSE CAST(extra AS STRING) END AS v"))
+      val reads = requiredColumns(df)
+      assert(reads.values.map(_.map(_.name).toSet).toSeq ===
+        Seq(Set("data", "extra")))
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("data", "extra"),
+        CheckAnswer(Row("a"), Row("b")))
+    }
+  }
+
+  test("push down no filter after a filter that is not pushed down") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, owner string, qty int, payload string")
+      sql(s"INSERT INTO $tbl VALUES (1, current_user(), 1, '1'), (2, 'other', 
0, 'abc')")
+      val raise = "CASE WHEN qty <= 0 THEN raise_error('bad qty') ELSE true 
END"
+      val source = spark.readStream.table(tbl)
+      // The filter on the owner has a value of each micro-batch, so it is not 
pushed down, and
+      // neither is any filter written after it: each micro-batch evaluates 
the pushed filters
+      // first, so a filter that fails on the row of the other owner, as the 
cast of its payload
+      // does with ANSI, or the error raised for its quantity 0, would fail 
the query.
+      Seq(raise -> Nil, "CAST(payload AS INT) > 0" -> Nil, "id > 0" -> 
Seq("GreaterThan(id,0)"))
+        .foreach { case (filter, taken) =>
+          val df = source.where(s"owner = current_user() AND $filter")
+          assert(pushed(df) === Nil, filter)
+          // The filters of the V1 builder of the in-memory tables compare 
columns with values,
+          // which cannot fail, so it gets id > 0 wherever it is. It cannot 
take the others.
+          testStream(df.select("id"))(
+            ProcessAllAvailable(),
+            assertPushedFilters(taken: _*),
+            CheckAnswer(Row(1L)))
+        }
+      // The filters written before it are pushed down, as the query evaluates 
them first anyway.
+      assert(pushed(source.where(s"$raise AND id > 0 AND owner = 
current_user() AND qty > 0")) ===
+        Seq(Set("qty"), Set("id")))
+      // With several reads of the relation, the pushed filters are those that 
all of them
+      // evaluate first, in the same order.
+      val read = source.where(s"$raise AND id > 0")
+      assert(pushed(read.union(read)) === Seq(Set("qty"), Set("id")))
+      assert(pushed(read.union(source.where(s"$raise AND qty > 0"))) === 
Seq(Set("qty")))
+      assert(pushed(read.union(source.where(s"id > 0 AND $raise"))) === Nil)
+    }
+  }
+
+  test("drop the rows that fail the pushed filters in the stream of a source") 
{
+    withSourceTable(filtering) {
+      // The stream only returns the rows that pass the pushed filter, so the 
progress of the query
+      // only counts them.
+      def inputRows(query: StreamExecution): Long = 
query.recentProgress.map(_.numInputRows).sum
+      testStream(spark.readStream.table(tbl).where("extra > 
10").select("data"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("GreaterThan(extra,10)"),
+        CheckAnswer(Row("b")),
+        AssertOnQuery(inputRows(_) == 1),
+        insert("(3, 'c', 30), (4, 'd', 5), (5, 'e', 50)"),
+        ProcessAllAvailable(),
+        CheckAnswer(Row("b"), Row("c"), Row("e")),
+        AssertOnQuery(inputRows(_) == 3))
+    }
+  }
+
+  test("filter the rows of a continuous stream with the filters that its scan 
builder took") {
+    val input = ContinuousMemoryStream.singlePartition[(Long, String, Int)]
+    val table = new PruningContinuousTable(input, takesFilters = true)
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"pruning_continuous", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra").where("extra > 10").select("data")
+    PruningContinuousTable.returnedRows.set(0)
+    withTempView("continuous_filtering") {
+      val query = 
df.writeStream.format("memory").queryName("continuous_filtering")
+        .trigger(Trigger.Continuous(100)).start()
+      try {
+        input.addData((1L, "a", 10), (2L, "b", 20), (3L, "c", 30))
+        eventually(timeout(streamingTimeout)) {
+          checkAnswer(spark.table("continuous_filtering"), Seq(Row("b"), 
Row("c")))
+        }
+        // The readers dropped the row that fails the filter, which the plan 
of the query applies
+        // to the rows of the source too.
+        assert(PruningContinuousTable.returnedRows.get() === 2)
+        val filtered = 
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.logicalPlan
+          .collect {
+            case Filter(_, relation: StreamingDataSourceV2ScanRelation) =>
+              relation.pushedFilters.map(_.references.map(_.name).toSet)
+          }
+        assert(filtered === Seq(Seq(Set("_3"))))
+      } finally {
+        query.stop()
+      }
+    }
+  }
+
+  test("plan the micro-batches whose filters fold the pushed filters in part") 
{
+    // The streams drop the rows that fail the pushed filters, so the answers 
depend on them.
+    withTable(tbl) {
+      createTable(tbl, "id bigint, owner string, d date", filtering)
+      sql(s"INSERT INTO $tbl VALUES (1, current_user(), current_date()), " +
+        "(6, current_user(), current_date()), (7, 'other', current_date())")
+      // A micro-batch folds current_user() into a literal, which it puts in 
place of the column
+      // in the pushed filter owner = '' OR id > 5, which it then folds into 
id > 5.
+      testStream(spark.readStream.table(tbl)
+          .where("(owner = '' OR id > 5) AND owner = 
current_user()").select("id"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("Or(EqualTo(owner,),GreaterThan(id,5))"),
+        CheckAnswer(Row(6L)))
+      // So does a date that is not the date of the micro-batch, as on the day 
after the start.
+      // The micro-batch is planned whether the rows have its date or not.
+      testStream(spark.readStream.table(tbl)
+          .where("(d < DATE'2000-01-01' OR id > 5) AND d = 
to_date(now())").select("id"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("Or(LessThan(d,2000-01-01),GreaterThan(id,5))"))
+    }
+    // And an equality that a micro-batch infers through a stream-static join.
+    withTable(tbl) {
+      createTable(tbl, "a bigint, b bigint", filtering)
+      sql(s"INSERT INTO $tbl VALUES (2, 0), (0, 0), (5, 3)")
+      val source = spark.readStream.table(tbl).where("a > 1 OR b > 2")
+      val static = spark.range(0, 2).toDF("x").where("x = 0")
+      testStream(source.join(static, source("b") === static("x")).select("a"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("Or(GreaterThan(a,1),GreaterThan(b,2))"),
+        CheckAnswer(Row(2L)))
+    }
+  }
+
+  test("read all the columns with no filter from a table without the 
capabilities") {
+    withSourceTable(InMemoryBaseTable.STREAMING_COLUMN_PRUNING -> "false",
+        InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN -> "false") {
+      val df = spark.readStream.table(tbl).where("extra > 10").select("data")
+      testStream(df)(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data", "extra"),
+        assertScanOutputs(Seq("id", "data", "extra")),
+        assertPushedFilters(),
+        AssertOnQuery { query =>
+          // The plan of the query only applies the filter of the query.
+          val relations = query.logicalPlan.collect {
+            case relation: StreamingDataSourceV2ScanRelation => relation
+          }
+          relations.nonEmpty && relations.forall(_.pushedFilters.isEmpty)
+        },
+        CheckAnswer(Row("b")))
+    }
+  }
+
+  test("push down only what the capabilities of the table allow") {
+    val df = () => spark.readStream.table(tbl).where("extra > 
10").select("data")
+    withSourceTable(InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN -> "false") {
+      testStream(df())(
+        ProcessAllAvailable(),
+        assertReadSchema("data", "extra"),
+        assertPushedFilters(),
+        CheckAnswer(Row("b")))
+    }
+    withSourceTable(InMemoryBaseTable.STREAMING_COLUMN_PRUNING -> "false") {
+      testStream(df())(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data", "extra"),
+        assertPushedFilters("GreaterThan(extra,10)"),
+        CheckAnswer(Row("b")))
+    }
+  }
+
+  Seq(
+    // The column pruning alone works when the filters fail.
+    "pushFilters" -> (Seq("_2", "_3") -> Nil),
+    // The filters alone work when the column pruning fails.
+    "pruneColumns" -> (Seq("_1", "_2", "_3") -> Seq("GreaterThan(_3,10)")),
+    // Neither works when any pushdown fails the build, so the scan reads all 
the columns with no
+    // filter, as without the pushdowns.
+    "build" -> (Seq("_1", "_2", "_3") -> Nil)
+  ).foreach { case (failingStep, (columns, filters)) =>
+    test(s"read with fewer pushdowns when the scan fails with the pushdowns: 
$failingStep") {
+      val input = new ProjectingMemoryStream(spark)
+      val table = new FailingPushDownTable(input, failingStep)
+      val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"failing_push_down", table,
+        CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+        None)).toDF("id", "data", "extra").where("extra > 10").select("data")
+      val logs = new LogAppender("the fallback of a streaming scan")
+      withLogAppender(logs,
+          loggerNames = 
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+          level = Some(Level.WARN)) {
+        testStream(df)(
+          StartStream(),
+          AddData(input, (1L, "a", 10), (2L, "b", 20)),
+          ProcessAllAvailable(),
+          // Each new scan builder builds the scan with fewer pushdowns: the 
column pruning
+          // alone, then the filters alone, and then all the columns with no 
filter.
+          assertReadSchema(columns: _*),
+          AssertOnQuery(_ => table.streams.asScala.toSeq == Seq(columns -> 
filters)),
+          CheckAnswer(Row("b")))
+      }
+      val warnings = logs.loggingEvents.map(_.getMessage.getFormattedMessage)
+      assert(warnings.exists { message =>
+        message.contains("could not be built with the pushdowns (columns: _2, 
_3, filters: ") &&
+          message.contains(s"$failingStep failed with the pushdowns") &&
+          message.contains("It reads only the columns _2, _3 with no filter 
instead.")
+      }, warnings)
+      assert(warnings.exists { message =>
+        message.contains("could not be built to read only the columns _2, _3: 
") &&
+          message.contains(s"$failingStep failed with the pushdowns") &&
+          message.contains("It reads all the columns with the filters ")
+      } === (failingStep != "pushFilters"), warnings)
+      assert(warnings.exists { message =>
+        message.contains("could not be built with the pushdowns (columns: all, 
filters: ") &&
+          message.contains(s"$failingStep failed with the pushdowns") &&
+          message.contains("It reads all the columns with no filter instead.")
+      } === (failingStep == "build"), warnings)
+    }
+  }
+
+  test("fail the query when the stream of its scan with the pushdowns cannot 
be created") {
+    val input = new ProjectingMemoryStream(spark)
+    val table = new FailingPushDownTable(input, "toMicroBatchStream")
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"failing_push_down", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra").where("extra > 10").select("data")
+    testStream(df)(
+      StartStream(),
+      ExpectFailure[IllegalStateException](e =>
+        assert(e.getMessage.contains("toMicroBatchStream failed with the 
pushdowns"))))
+    // The stream may have started to use the checkpoint of the source when it 
failed, so no
+    // other stream is created for a scan of all the columns.
+    assert(table.streamAttempts.get() === 1)
+    assert(table.streams.isEmpty)
+  }
+
+  test("keep the placeholders of the values that depend on when they are 
evaluated apart") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl)
+        .select(current_user(), current_database(), current_catalog(), 
col("data"))
+      val placeholders = 
StreamingV2ScanPushDown.forStartup(df.queryExecution.analyzed)
+        .collectFirst { case project: Project => project.projectList.take(3) 
}.get
+        .map(_.asInstanceOf[Alias].child)
+      // The placeholders of different expressions differ, although they have 
the same type.
+      assert(placeholders.map(_.dataType).distinct.length === 1)
+      assert(placeholders.map(_.canonicalized).distinct.length === 3)
+    }
+  }
+
+  test("keep the placeholders of different static plans apart") {
+    withSourceTable() {
+      val df = spark.readStream.table(tbl).select(
+        expr("(SELECT max(id) FROM range(3))").as("a"),
+        expr("(SELECT max(id) FROM range(4))").as("b"),
+        expr("(SELECT max(id) FROM range(3))").as("c"),
+        col("data"))
+      val placeholders = 
StreamingV2ScanPushDown.forStartup(df.queryExecution.analyzed)
+        .collectFirst { case project: Project => project.projectList.take(3) 
}.get
+        .map(_.collectFirst { case subquery: ScalarSubquery => 
subquery.plan.canonicalized }.get)
+      // The placeholders of different plans differ, although they have the 
same output, while
+      // those of the same plan do not, as the plans in the micro-batches.
+      assert(placeholders(0) !== placeholders(1))
+      assert(placeholders(0) === placeholders(2))
+    }
+  }
+
+  test("plan the placeholders in the expressions of other placeholders too") {
+    withSourceTable() {
+      // The cast of the string is a placeholder whose expression has the 
placeholder of the
+      // current date.
+      val df = spark.readStream.table(tbl).select(
+        expr("CAST(concat(CAST(current_date() AS STRING), ' 12:00') AS 
TIMESTAMP)").as("t"),
+        col("data"))
+      val startup = 
StreamingV2ScanPushDown.forStartup(df.queryExecution.analyzed)
+      assert(!startup.flatMap(_.expressions).forall(_.deterministic))
+      // The planner of a micro-batch gets the values of both, which are 
deterministic.
+      val planned = StreamingV2ScanPushDown.forPlanning(startup)
+      assert(planned.flatMap(_.expressions).forall(_.deterministic))
+    }
+  }
+
+  test("fail the start of a query whose optimization for the pruning fails, in 
tests") {
+    // A rule that fails in the optimization when the query starts, whose plan 
has the relations of
+    // the sources, unlike the plans of the micro-batches.
+    val failing = new Rule[LogicalPlan] {
+      override def apply(plan: LogicalPlan): LogicalPlan = {
+        if (plan.exists(_.isInstanceOf[StreamingRelationV2])) {
+          throw new IllegalStateException("The optimization at the start 
failed.")
+        }
+        plan
+      }
+    }
+    withSourceTable() {
+      spark.experimental.extraOptimizations = Seq(failing)
+      try {
+        // Outside of tests, the scans read all their columns instead, with a 
warning.
+        testStream(spark.readStream.table(tbl).select("data"))(
+          StartStream(),
+          ExpectFailure[IllegalStateException](e =>
+            assert(e.getMessage.contains("The optimization at the start 
failed."))))
+      } finally {
+        spark.experimental.extraOptimizations = Nil
+      }
+    }
+  }
+
+  test("read a source whose scans report strings for its char columns") {
+    withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+      val input = MemoryStream[(Long, String)]
+      val table = new StringReadSchemaTable(input)
+      val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"string_read_schema", table,
+        CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+        None))
+      // The relation outputs a char column, which the read schema of the scan 
has as a string:
+      // the readers return strings for both.
+      testStream(df)(
+        StartStream(),
+        AddData(input, (1L, "a"), (2L, "b")),
+        ProcessAllAvailable(),
+        assertReadSchema("_1", "_2"),
+        CheckAnswerRowsByFunc(rows => assert(rows.map(row => row.getLong(0) ->
+          row.getString(1).trim).toSet === Set(1L -> "a", 2L -> "b")), 
lastOnly = false))
+    }
+  }
+
+  // The confs with which the plans have char and varchar types, which the 
analysis rejects
+  // otherwise.
+  Seq(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS, 
SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO)
+    .foreach { conf =>
+      test(s"read only the columns of a query from a table with char and 
varchar columns: " +
+          conf.key) {
+        withSQLConf(conf.key -> "true") {
+          withTable(tbl) {
+            createTable(tbl, "id bigint, c char(3), v varchar(5), extra int")
+            sql(s"INSERT INTO $tbl VALUES (1, 'a', 'x', 10), (2, 'b', 'y', 
20)")
+            // The relation of the source outputs the columns with the types 
char and varchar,
+            // while the read schemas of its scans may have strings.
+            testStream(spark.readStream.table(tbl).select("c", "v"))(
+              ProcessAllAvailable(),
+              assertReadSchema("c", "v"),
+              CheckAnswer(spark.read.table(tbl).select("c", 
"v").collect().toSeq: _*))
+            val logs = new LogAppender("the read schemas of the scans of char 
and varchar columns")
+            withLogAppender(logs,
+                loggerNames = 
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+                level = Some(Level.WARN)) {
+              Seq(true, false).foreach { enabled =>
+                withSQLConf(SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> 
enabled.toString) {
+                  testStream(spark.readStream.table(tbl))(
+                    ProcessAllAvailable(),
+                    assertReadSchema("id", "c", "v", "extra"),
+                    CheckAnswer(spark.read.table(tbl).collect().toSeq: _*))
+                }
+              }
+            }
+            // The scan of all the columns follows the relation, with the 
pruning or without it.
+            assert(logs.loggingEvents.isEmpty,
+              logs.loggingEvents.map(_.getMessage.getFormattedMessage))
+          }
+        }
+      }
+    }
+
+  test("replace the expressions that make dates or timestamps of strings, 
times or variants") {
+    withSourceTable() {
+      // Each expression, and whether it is replaced: one whose type has a 
date or a timestamp, of
+      // any precision and time zone, at any depth, made of a string, a time 
or a variant, which
+      // may take the current date, whatever its child is, as a cast or 
another conversion.
+      val expressions = Seq(
+        "CAST('12:00:00' AS TIMESTAMP)" -> true,
+        "CAST('12:00:00' AS TIMESTAMP_LTZ(9))" -> true,
+        "CAST('2100-01-01 12:00:00' AS TIMESTAMP)" -> true,
+        "CAST(data AS TIMESTAMP)" -> true,
+        "CAST('now' AS TIMESTAMP_NTZ)" -> true,
+        "CAST('today' AS DATE)" -> true,
+        "CAST(array('12:00:00') AS ARRAY<TIMESTAMP>)" -> true,
+        "CAST(named_struct('t', '12:00:00') AS STRUCT<t: TIMESTAMP>)" -> true,
+        "CAST(map('k', '12:00:00') AS MAP<STRING, TIMESTAMP>)" -> true,
+        "CAST(TIME'12:00:00' AS TIMESTAMP_NTZ)" -> true,
+        "CAST(array(TIME'12:00:00') AS ARRAY<TIMESTAMP>)" -> true,
+        """CAST(parse_json('"12:00:00"') AS TIMESTAMP)""" -> true,
+        """variant_get(parse_json('"12:00:00"'), '$', 'timestamp')""" -> true,
+        """from_json('{"t": "12:00:00"}', 't TIMESTAMP')""" -> true,
+        "to_timestamp(data, 'HH:mm:ss')" -> true,
+        // Neither the conversions of other values, nor the expressions that 
take the dates and
+        // the timestamps of their children.
+        "CAST(DATE'2100-01-01' AS TIMESTAMP)" -> false,
+        "CAST(1 AS TIMESTAMP)" -> false,
+        "CAST(array(1) AS ARRAY<STRING>)" -> false,
+        "CAST(TIMESTAMP'2100-01-01 00:00:00' AS STRING)" -> false,
+        "named_struct('s', data, 't', TIMESTAMP'2100-01-01 00:00:00')" -> 
false,
+        "date_trunc('DAY', TIMESTAMP'2100-01-01 00:00:00')" -> false)
+      val df = spark.readStream.table(tbl)
+        .select(expressions.map(e => expr(e._1)) :+ col("data"): _*)
+      val replaced = 
StreamingV2ScanPushDown.forStartup(df.queryExecution.analyzed)
+        .collectFirst { case project: Project => 
project.projectList.take(expressions.length) }.get
+        .map(_.asInstanceOf[Alias].child)
+      assert(replaced.map(_.nodeName == "StartupValue") === 
expressions.map(_._2))
+    }
+  }
+
+  test("apply the filters that the scan builder got in the plan of each 
micro-batch") {
+    withSourceTable() {
+      // id + extra > 10 cannot be translated to a filter of the source, so 
the scan builder only
+      // gets extra > 15. Each micro-batch applies it to the rows of the 
source, which the query
+      // applies anyway, so the scan cannot drop a row that the plan keeps, 
whatever it does with
+      // the filter. The filter that the scan builder does not get is 
evaluated after it, as for
+      // a batch scan, rather than on every row of the source.
+      testStream(spark.readStream.table(tbl).where("id + extra > 10 AND extra 
> 15")
+          .select("data"))(
+        ProcessAllAvailable(),
+        assertPushedFilters("GreaterThan(extra,15)"),
+        AssertOnQuery { query =>
+          val filtered = query.logicalPlan.collect {
+            case Filter(condition, relation: 
StreamingDataSourceV2ScanRelation) =>
+              condition -> relation
+          }
+          assert(filtered.length === 1)
+          val (condition, relation) = filtered.head
+          assert(relation.pushedFilters.map(_.references.map(_.name).toSet) 
=== Seq(Set("extra")))
+          assert(condition === relation.pushedFilters.head)
+          true
+        },
+        CheckAnswer(Row("b")),
+        insert("(3, 'c', 5), (4, 'd', 30)"),
+        ProcessAllAvailable(),
+        CheckAnswer(Row("b"), Row("d")))
+    }
+  }
+
+  test("push down the filters of a query that joins a source with an inline 
table") {
+    withSourceTable() {
+      val source = spark.readStream.table(tbl)
+      val inline = sql("SELECT * FROM VALUES (2, current_date()) AS s(k, d)")
+      val df = source.where("extra > 10").join(inline, source("id") === 
inline("k"))
+        .select("data", "d")
+      val sourceReads = reads(df).values.toSeq
+      assert(sourceReads.map(_.requiredColumns.map(_.name).toSet) ===
+        Seq(Set("id", "data", "extra")))
+      
assert(sourceReads.flatMap(_.filters).map(_.references.map(_.name).toSet) ===
+        Seq(Set("extra")))
+    }
+  }
+
+  test("filter the rows of each read of a source with the filters that its 
scan builder got") {
+    withSourceTable() {
+      val source = spark.readStream.table(tbl)
+      val df = source.where("extra > 10").select("data")
+        .union(source.where("extra > 10 AND id > 1").select("data"))
+      testStream(df)(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          // Both reads of the relation are filtered with the filter that they 
both apply.
+          val filtered = query.logicalPlan.collect {
+            case Filter(condition, relation: 
StreamingDataSourceV2ScanRelation) =>
+              condition -> relation
+          }
+          assert(filtered.length === 2)
+          filtered.foreach { case (condition, relation) =>
+            assert(relation.pushedFilters.map(_.toString) ===
+              Seq(s"(${relation.output(2)} > 10)"))
+            assert(condition === relation.pushedFilters.head)
+          }
+          // So is each read of the relation in the optimized plan of a 
micro-batch.
+          val microBatchFilters = query.lastExecution.optimizedPlan.collect {
+            case Filter(condition, relation: 
StreamingDataSourceV2ScanRelation) =>
+              condition.exists(c => 
relation.pushedFilters.exists(c.semanticEquals))
+          }
+          assert(microBatchFilters === Seq(true, true))
+          true
+        },
+        CheckAnswer(Row("b"), Row("b")))
+    }
+  }
+
+  test("do not build the scans of the batch relations of a streaming query 
when it starts") {
+    withSourceTable() {
+      val table = new CountingBatchTable
+      val static = Dataset.ofRows(spark, DataSourceV2Relation.create(
+        table, None, None, CaseInsensitiveStringMap.empty()))
+      val source = spark.readStream.table(tbl)
+      val df = source.join(static, source("id") === 
static("sid")).select("data")
+      val reads = requiredColumns(df)
+      assert(reads.values.map(_.map(_.name).toSet).toSeq === Seq(Set("id", 
"data")))
+      assert(table.scanBuilders.get() === 0)
+    }
+  }
+
+  test("read the columns of a condition on a static side, whatever the cache 
holds") {
+    withSourceTable() {
+      val static = spark.range(1, 4).toDF("sid").withColumn("on", lit(false))
+      val source = spark.readStream.table(tbl)
+      val df = source.join(static, source("id") === static("sid"))
+        .select(when(col("on"), 
col("data")).otherwise(col("extra").cast("string")).as("v"))
+      // The static side is opaque when the query starts, so the scan reads 
both columns of the
+      // condition, also when a micro-batch cannot fold it, as with the static 
side cached after
+      // the query started.
+      assert(requiredColumns(df).values.map(_.map(_.name).toSet).toSeq ===
+        Seq(Set("id", "data", "extra")))
+      static.cache()
+      try {
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchemas(Seq("id", "data", "extra")),
+          CheckAnswer(Row("10"), Row("20")),
+          insert("(3, 'c', 30)"),
+          ProcessAllAvailable(),
+          CheckAnswer(Row("10"), Row("20"), Row("30")))
+      } finally {
+        static.unpersist()
+      }
+    }
+  }
+
+  test("fail a query whose scan of all the columns has a read schema that does 
not follow the " +
+      "relation") {
+    val input = MemoryStream[(Long, String, Int)]
+    val table = new UnknownColumnReadSchemaTable(input)
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"unknown_column_read_schema", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra")
+    // The readers of the stream would return the column that the relation 
does not output, so
+    // the scan node could not output the columns of the relation in their 
order.
+    testStream(df)(
+      StartStream(),
+      ExpectFailure[SparkException] { e =>
+        checkError(e.asInstanceOf[SparkException],
+          condition = "STREAMING_SCAN_INVALID_READ_SCHEMA",
+          parameters = Map(
+            "source" -> "`unknown_column_read_schema`",
+            "reason" -> ("struct<_1:bigint,_2:string,_3:int,unknown:int> has 
the columns " +
+              "unknown, which the relation does not output"),
+            "config" -> 
s"\"${SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key}\""))
+      })
+    // Without the column pruning, the scan node outputs the columns of the 
relation instead, as
+    // it did before the capability.
+    withPushDownConfsRestored {
+      testStream(df)(
+        StartStream(additionalConfs = pruningEnabled(false)),
+        AddData(input, (1L, "a", 10)),
+        ProcessAllAvailable(),
+        assertScanOutputs(Seq("_1", "_2", "_3")),
+        CheckAnswer(Row(1L, "a", 10)))
+    }
+  }
+
+  test("read all the columns of a source whose pruned scan has no read 
schema") {
+    val input = MemoryStream[(Long, String, Int)]
+    val table = new NoPrunedReadSchemaTable(input)
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"no_pruned_read_schema", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra").select("data")
+    testStream(df)(
+      StartStream(),
+      AddData(input, (1L, "a", 10), (2L, "b", 20)),
+      ProcessAllAvailable(),
+      // The pruned scan is replaced by a scan of all the columns before its 
stream is created.
+      assertReadSchema("_1", "_2", "_3"),
+      AssertOnQuery(_ => table.streams.get() == 1),
+      CheckAnswer(Row("a"), Row("b")))
+  }
+
+  test("fail a micro-batch that reads other columns once the configuration of 
the optimizer " +
+      "changes in the session of the query") {
+    withSourceTable() {
+      val static = spark.range(1, 4).toDF("sid")
+      val source = spark.readStream.table(tbl)
+      val df = source.join(static, source("id") === 
static("sid")).select("data")
+      val batches = new ConcurrentLinkedQueue[Seq[Row]]()
+      val query = df.writeStream.foreachBatch { (batch: DataFrame, _: Long) =>
+        batches.add(batch.collect().toSeq)
+        // The next micro-batches are optimized without ColumnPruning, so 
their join reads all
+        // the columns of the source, while its scan only reads those of the 
plan optimized
+        // when the query started.
+        batch.sparkSession.conf.set(
+          SQLConf.OPTIMIZER_EXCLUDED_RULES.key, ColumnPruning.ruleName)
+      }.start()
+      try {
+        query.processAllAvailable()
+        assert(batches.asScala.toSeq.map(_.map(_.getString(0)).sorted) === 
Seq(Seq("a", "b")))
+        sql(s"INSERT INTO $tbl VALUES (3, 'c', 30)")
+        val e = intercept[StreamingQueryException](query.processAllAvailable())
+        checkError(
+          exception = e.getCause.asInstanceOf[SparkException],
+          condition = "STREAMING_SCAN_MISSING_COLUMNS",
+          parameters = Map(
+            "columns" -> "`extra`",
+            "source" -> "`testcat`.`t`",
+            "config" -> 
s"\"${SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key}\""))
+      } finally {
+        query.stop()
+      }
+    }
+  }
+
+  test("read all the columns when the pruning of streaming scans is disabled, 
as by default") {
+    assert(!SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.defaultValue.get)
+    withSQLConf(SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "false") {
+      withSourceTable() {
+        val df = spark.readStream.table(tbl).select("data")
+        testStream(df)(
+          ProcessAllAvailable(),
+          assertReadSchema("id", "data", "extra"),
+          assertScanOutputs(Seq("id", "data", "extra")),
+          CheckAnswer(Row("a"), Row("b")))
+      }
+    }
+  }
+
+  test("canonicalize and show the pushed filters of a streaming scan 
relation") {
+    withSourceTable() {
+      testStream(spark.readStream.table(tbl).where("extra > 
10").select("data"))(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          val relation = query.logicalPlan.collectFirst {
+            case relation: StreamingDataSourceV2ScanRelation => relation
+          }.get
+          assert(relation.pushedFilters.nonEmpty)
+          // A copy of the relation has new attributes, also in its pushed 
filters, and the same
+          // result.
+          val copy = 
relation.newInstance().asInstanceOf[StreamingDataSourceV2ScanRelation]
+          assert(copy.pushedFilters.flatMap(_.references).map(_.exprId).toSet
+            .intersect(relation.output.map(_.exprId).toSet).isEmpty)
+          assert(copy.sameResult(relation))
+          // The plan applies the pushed filters with those of the query, so 
the relation shows
+          // the filters that its scan builder was given.
+          val string = relation.simpleString(100)
+          assert(string.contains("FiltersOfScanBuilder: [") && 
string.contains(" > 10)]"), string)
+          true
+        },
+        CheckAnswer(Row("b")))
+    }
+  }
+
+  // The confs with which the optimizer may not prune the copies of the pushed 
filters that each
+  // micro-batch keeps above other operators.
+  private val withoutPruneFilters = Seq(
+    Map.empty[String, String],
+    Map(SQLConf.CONSTRAINT_PROPAGATION_ENABLED.key -> "false"),
+    Map(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> PruneFilters.ruleName))
+
+  test("evaluate a pushed filter once above a projection of a value of each 
micro-batch") {
+    withSourceTable() {
+      // The query outputs the value, so that the optimizer keeps its 
projection.
+      val df = spark.readStream.table(tbl).withColumn("pt", 
current_timestamp())
+        .where("extra > 10").select("data", "pt")
+      // Each micro-batch keeps a copy of the filter above the projection, 
which it drops, as the
+      // pushed filter is applied to the rows of the source below it, whether 
the optimizer
+      // could prune the copy or not.
+      withoutPruneFilters.foreach { confs =>
+        withSQLConf(confs.toSeq: _*) {
+          assert(pushed(df) === Seq(Set("extra")), confs)
+          testStream(df)(
+            ProcessAllAvailable(),
+            assertPushedFilters("GreaterThan(extra,10)"),
+            assertEvaluatedOnce("extra"))
+        }
+      }
+    }
+  }
+
+  test("evaluate a pushed filter once after a separate filter that is not 
pushed down") {
+    withTable(tbl) {
+      createTable(tbl, "id bigint, data string, ts timestamp, extra int")
+      sql(s"INSERT INTO $tbl VALUES " +
+        "(1, 'a', timestamp_seconds(0), 10), (2, 'b', timestamp_seconds(0), 
20)")
+      // The filters cannot be combined when the query starts, as the first 
one has a value of
+      // each micro-batch. The V1 builder of the in-memory tables gets the 
second one, and each
+      // micro-batch drops its copy above the first one.
+      val df = spark.readStream.table(tbl).where("ts < 
current_timestamp()").where("extra > 10")
+        .select("data")
+      withoutPruneFilters.foreach { confs =>
+        withSQLConf(confs.toSeq: _*) {
+          testStream(df)(
+            ProcessAllAvailable(),
+            assertPushedFilters("GreaterThan(extra,10)"),
+            assertEvaluatedOnce("extra"),
+            CheckAnswer(Row("b")))
+        }
+      }
+    }
+  }
+
+  Seq(
+    // Two filters above the projection, which the micro-batch combines.
+    "two filters" -> ((df: DataFrame) =>
+      df.withColumn("pt", current_timestamp()).where("extra > 10").where("data 
= 'b'")
+        .select("data", "pt"), Seq(Seq("extra"), Seq("data"))),
+    // A filter that the optimizer rewrites, as id > CAST(1 AS BIGINT), whose 
pushed filter is
+    // optimized too.
+    "a rewritten filter" -> ((df: DataFrame) =>
+      df.withColumn("pt", current_timestamp()).where("id > 1").select("data", 
"pt"),
+      Seq(Seq("id"))),
+    // A filter on an alias of the column of the pushed filter.
+    "a filter on an alias" -> ((df: DataFrame) =>
+      df.select(col("data"), col("extra").as("e"), 
current_timestamp().as("pt"))
+        .where("e > 10").select("data", "pt"), Seq(Seq("e", "extra"))),
+    // A filter above a watermark, which keeps the rows and the columns of its 
child.
+    "a filter above a watermark" -> ((df: DataFrame) =>
+      df.withColumn("pt", current_timestamp()).withWatermark("pt", "10 
seconds")
+        .where("extra > 10").select("data"), Seq(Seq("extra")))
+  ).foreach { case (name, (query, columns)) =>
+    test(s"evaluate the pushed filters once with $name above a projection of a 
value of each " +
+        "micro-batch") {
+      withSourceTable() {
+        val df = query(spark.readStream.table(tbl))
+        withoutPruneFilters.foreach { confs =>
+          withSQLConf(confs.toSeq: _*) {
+            testStream(df)(
+              ProcessAllAvailable() +:
+                columns.map(names => assertEvaluatedOnce(names: _*)): _*)
+          }
+        }
+      }
+    }
+  }
+
+  test("read all the columns with the filters when only the column pruning 
fails") {
+    // The pruned scans of the table do not have the column data, so the scan 
reads all the
+    // columns, still with the filter.
+    withSourceTable(InMemoryBaseTable.SIMULATE_INCOMPLETE_COLUMN_PRUNING -> 
"true") {
+      testStream(spark.readStream.table(tbl).where("extra > 
10").select("data"))(
+        ProcessAllAvailable(),
+        assertReadSchema("id", "data", "extra"),
+        assertPushedFilters("GreaterThan(extra,10)"),
+        CheckAnswer(Row("b")))
+    }
+  }
+
+  test("push down the filters to a scan of all the columns whose read schema 
does not follow " +
+      "the relation, without the column pruning") {
+    val input = MemoryStream[(Long, String, Int)]
+    val table = new UnknownColumnFilterTable(input)
+    val df = Dataset.ofRows(spark, StreamingRelationV2(None, 
"unknown_column_filter", table,
+      CaseInsensitiveStringMap.empty(), 
DataTypeUtils.toAttributes(table.schema()), None, None,
+      None)).toDF("id", "data", "extra").where("extra > 10").select("data")
+    val logs = new LogAppender("the read schema of a scan of all the columns 
with filters")
+    withLogAppender(logs,
+        loggerNames = 
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+        level = Some(Level.WARN)) {
+      withSQLConf(SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "false") {
+        testStream(df)(
+          StartStream(),
+          AddData(input, (1L, "a", 10), (2L, "b", 20)),
+          ProcessAllAvailable(),
+          AssertOnQuery(_ => table.pushed == Seq("GreaterThan(_3,10)")),
+          CheckAnswer(Row("b")))
+      }
+    }
+    // The scan with the filter goes through the check of a scan of all the 
columns, which only
+    // logs the read schema without the column pruning, rather than building 
it again.
+    val warnings = logs.loggingEvents.map(_.getMessage.getFormattedMessage)
+    assert(warnings.exists(_.contains("as the column pruning is disabled")), 
warnings)
+    assert(!warnings.exists(_.contains("could not be built")), warnings)
+  }
+
+  test("do not optimize a query without conditions when no source prunes its 
columns") {
+    withSourceTable(InMemoryBaseTable.STREAMING_COLUMN_PRUNING -> "false") {
+      val source = spark.readStream.table(tbl)
+      // Nothing can be pushed down without a condition, so the query is not 
optimized, and its
+      // scan gets no filter.
+      assert(reads(source.select("data")).isEmpty)
+      assert(reads(source.union(source)).isEmpty)
+      assert(reads(source.where("extra > 10")).nonEmpty)
+      assert(reads(source.join(spark.range(3).toDF("id"), "id")).nonEmpty)
+      // The optimizer turns the conditions of an as-of or a lateral join into 
filters too.
+      val static = spark.range(3).toDF("sid")
+      assert(reads(source.joinAsOf(static, source("id"), static("sid"), 
source("extra") > 10,
+        "inner", null, allowExactMatches = true, "backward")).nonEmpty)
+      withTempView("s") {
+        source.createOrReplaceTempView("s")
+        assert(reads(sql("SELECT * FROM s JOIN LATERAL (SELECT s.id AS x) ON 
s.extra > 10"))
+          .nonEmpty)
+      }
+    }
+    // A source that prunes its columns needs the optimized query either way.
+    withSourceTable() {
+      assert(reads(spark.readStream.table(tbl).select("data")).nonEmpty)
+    }
+  }
+
+  test("push down no filter that the optimizer infers from a generator") {
+    // The optimizer infers isnotnull(arr) and size(arr) > 0 from the explode 
of arr, which the
+    // query does not write: the scan only gets the filters that the query 
applies, whether the
+    // query has another filter or not, and whether the table prunes its 
columns or not.
+    Seq(Nil, Seq(InMemoryBaseTable.STREAMING_COLUMN_PRUNING -> "false"))
+      .foreach { properties =>
+        withTable(tbl) {
+          createTable(tbl, "id bigint, arr array<int>", properties: _*)
+          val source = spark.readStream.table(tbl)
+          assert(pushed(source.select(explode(col("arr")))) === Nil, 
properties)
+          assert(pushed(source.where("id > 0").select(explode(col("arr")))) 
=== Seq(Set("id")),
+            properties)
+        }
+      }
+  }
+
+  test("push down only the leading predicates that a V2 filter builder gets") {

Review Comment:
   Done. New end-to-end tests, "evaluate the filters of the micro-batches in 
their order with a V2 filter builder" and the same with a Catalyst filter 
builder, run a streaming query over `FilterStreamTable`, a memory stream whose 
builder is a `SupportsPushDownV2Filters` or a 
`SupportsPushDownCatalystFilters`. Under ANSI, the query filters `id > 0 AND 
payload RLIKE '^[0-9]+$' AND CAST(payload AS INT) > 1` over rows that include 
`"abc"`. Each test checks:
   - the answer, so the cast never sees `"abc"`;
   - the filters that the builder got: `id > 0` for the V2 builder, which 
cannot take the RLIKE, and all three, in order, for the Catalyst builder;
   - the order of the conjuncts of the filter over the relation in the 
optimized plan of the micro-batch: the RLIKE before the cast.
   



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