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


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

Review Comment:
   Done in 9a090d6: after the leading filters, V2 and Catalyst builders now 
also get the filters of `filtersInAnyOrder` that they take and that pass 
`ExprUtils.canEvaluateUnconditionally`. These can't fail, so they may run 
anywhere. The Javadoc of `STREAMING_FILTER_PUSHDOWN` says so, and the order is 
required only for the filters before them. The test of the leading V2 
predicates now also pushes `id > 1` after an RLIKE that isn't pushed and an 
ANSI cast that may fail.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -830,31 +1381,233 @@ class StreamingV2ScanPushDownSuite extends StreamTest 
with BeforeAndAfter {
     }
   }
 
-  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.")
+  Seq(true, false).foreach { failOnError =>
+    test(s"handle a failure of the optimization when the query starts: 
$failOnError") {
+      // 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)
+        val logs = new LogAppender("the failure of the optimization at the 
start")
+        try {
+          val failOnErrorConf = 
SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR.key
+          withSQLConf(failOnErrorConf -> failOnError.toString) {
+            val df = spark.readStream.table(tbl).where("extra > 
10").select("data")
+            if (failOnError) {
+              testStream(df)(
+                StartStream(),
+                ExpectFailure[IllegalStateException](e =>
+                  assert(e.getMessage.contains("The optimization at the start 
failed."))))
+            } else {
+              // As outside of the tests, the scan reads all the columns with 
no filter instead.
+              withLogAppender(logs,
+                  loggerNames = 
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+                  level = Some(Level.WARN)) {
+                testStream(df)(
+                  ProcessAllAvailable(),
+                  assertReadSchema("id", "data", "extra"),
+                  assertPushedFilters(),
+                  CheckAnswer(Row("b")))
+              }
+              
assert(logs.loggingEvents.exists(_.getMessage.getFormattedMessage.contains(
+                "Could not optimize the streaming query to push down what it 
reads")))
+            }
+          }
+        } finally {
+          spark.experimental.extraOptimizations = Nil
         }
-        plan
       }
     }
+  }
+
+  test("fail a micro-batch whose query no longer applies the filters that its 
scan got") {
     withSourceTable() {
-      spark.experimental.extraOptimizations = Seq(failing)
+      // The filter has a value that changes each time that it is evaluated, 
which the optimization
+      // at the start folds, as it would fold a function of the time that it 
does not replace.
+      ChangingValue.values.set(0)
+      val df = spark.readStream.table(tbl)
+        .where(col("extra") < 
ExpressionUtils.column(ChangingValue())).select("data")
+      // The scan drops the rows that fail extra < 1, while the plan of the 
micro-batch has a
+      // larger value, so it would keep some of them: the micro-batch fails 
before it reads them.
+      testStream(df)(
+        StartStream(),
+        ExpectFailure[SparkException] { e =>
+          checkError(e.asInstanceOf[SparkException],
+            condition = "STREAMING_SCAN_FILTERS_CHANGED",
+            parameters = Map(
+              "filters" -> "(testcat.t.extra < 1)",
+              "source" -> "`testcat`.`t`",
+              "config" -> 
s"\"${SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key}\""))
+        })
+    }
+  }
+
+  test("check that the plan of each micro-batch implies the filters that its 
scans got") {
+    withTable(tbl) {
+      createTable(tbl,
+        "id bigint, data string, d double, e int, t time, k struct<a: int>, xs 
array<int>, " +
+          "f struct<a: double>")
+      // A relation of the source, whose pushed filters each case sets.
+      var relation: StreamingDataSourceV2ScanRelation = null
+      testStream(spark.readStream.table(tbl))(
+        ProcessAllAvailable(),
+        AssertOnQuery { query =>
+          relation = query.logicalPlan.collectFirst {
+            case relation: StreamingDataSourceV2ScanRelation => relation
+          }.get
+          true
+        })
+      val Seq(id, data, d, e, t, k, xs, f) = relation.output
+      // Checks the plan of a micro-batch that `plan` makes of the relation, 
once the scan of the
+      // relation got `pushed`.
+      def check(pushed: Expression)(plan: LogicalPlan => LogicalPlan): Unit = {
+        StreamingV2ScanPushDown.checkPushedFilters(
+          spark, plan(relation.copy(pushedFilters = Seq(pushed))))
+      }
+      // Whether the check accepts that plan.
+      def accepts(pushed: Expression)(plan: LogicalPlan => LogicalPlan): 
Boolean = {
+        try {
+          check(pushed)(plan)
+          true
+        } catch {
+          case e: SparkException if e.getCondition == 
"STREAMING_SCAN_FILTERS_CHANGED" => false
+        }
+      }
+      val idAbove1 = GreaterThan(id, Literal(1L))
+      val random = GreaterThan(Rand(Literal(0L)), Literal(0.5))
+      // The plan applies the filter, with others or not, or a weaker one, or 
none.
+      assert(accepts(idAbove1)(Filter(And(EqualTo(data, Literal("a")), 
idAbove1), _)))
+      assert(!accepts(idAbove1)(Filter(GreaterThan(id, Literal(0L)), _)))
+      assert(!accepts(idAbove1)(identity))
+      // Or it keeps no row.
+      assert(accepts(idAbove1)(Filter(Literal(false), _)))
+      assert(accepts(idAbove1)(
+        Filter(And(EqualTo(data, Literal("a")), Literal.create(null, 
BooleanType)), _)))
+      // Through a projection, under an alias, but not through a projection or 
above a filter that
+      // is not deterministic, as these get the rows that the filter would 
drop.
+      assert(accepts(idAbove1) { relation =>
+        val alias = Alias(id, "i")()
+        Filter(GreaterThan(alias.toAttribute, Literal(1L)), Project(Seq(alias, 
data), relation))
+      })
+      assert(!accepts(idAbove1) { relation =>
+        Filter(idAbove1, Project(Seq(id, Alias(Rand(Literal(0L)), "r")()), 
relation))
+      })
+      assert(!accepts(idAbove1)(relation => Filter(idAbove1, Filter(random, 
relation))))
+      // A filter that is not deterministic gets its rows before its conjuncts 
after the first
+      // nondeterministic one, but not before those that it evaluates first.
+      assert(!accepts(idAbove1)(Filter(And(random, idAbove1), _)))
+      assert(accepts(idAbove1)(Filter(And(idAbove1, random), _)))
+      // With the values of the columns that the plan makes equal to literals.
+      assert(accepts(idAbove1)(Filter(EqualTo(id, Literal(5L)), _)))
+      assert(!accepts(idAbove1)(Filter(EqualTo(id, Literal(0L)), _)))
+      val either = Or(EqualTo(data, Literal("")), GreaterThan(id, Literal(5L)))
+      assert(accepts(either)(
+        Filter(And(EqualTo(data, Literal("a")), GreaterThan(id, Literal(5L))), 
_)))
+      assert(!accepts(either)(Filter(EqualTo(data, Literal("a")), _)))
+      assert(accepts(EqualTo(Cast(id, StringType), Literal("5")))(
+        Filter(EqualTo(id, Literal(5L)), _)))
+      assert(accepts(GreaterThan(t, Literal(LocalTime.of(0, 0, 1))))(
+        Filter(EqualTo(t, Literal(LocalTime.of(12, 0))), _)))
+      // Also for a struct or an array of such values, whose literal may have 
another nullability.
+      val struct = Literal.create(InternalRow(1),
+        StructType(Seq(StructField("a", IntegerType, nullable = false))))
+      assert(accepts(GreaterThan(GetStructField(k, 0, Some("a")), Literal(0)))(
+        Filter(EqualTo(k, struct), _)))
+      val array = Literal.create(ArrayData.toArrayData(Array(1, 2)),
+        ArrayType(IntegerType, containsNull = false))
+      assert(accepts(ArrayContains(xs, Literal(2)))(Filter(EqualTo(xs, array), 
_)))
+      // A struct of a double gets its value if it is not 0.0 or -0.0.
+      def structOf(value: Double): Literal = Literal.create(InternalRow(value),
+        StructType(Seq(StructField("a", DoubleType, nullable = false))))
+      val kd = GetStructField(f, 0, Some("a"))
+      assert(accepts(GreaterThan(kd, Literal(0.0)))(Filter(EqualTo(f, 
structOf(1.0)), _)))
+      assert(!accepts(EqualTo(Cast(kd, StringType), Literal("0.0")))(
+        Filter(EqualTo(f, structOf(0.0)), _)))
+      // And once the optimizer of the micro-batch rewrote it, as it rewrites 
the plan.
+      assert(accepts(LessThan(Cast(e, LongType), id))(
+        Filter(And(EqualTo(id, Literal(5L)), LessThan(e, Literal(5))), _)))
+      assert(accepts(If(EqualTo(data, Literal("")), GreaterThan(id, 
Literal(5L)),

Review Comment:
   Done in 9a090d6: the cast case of the test of the check now builds its 
micro-batch plan with the optimizer, with the rules that infer filters 
excluded, as the check sees it. Two new cases do the same:
   
   - `(id + e > 3 AND e > 0) OR id > 9` with `e = 1`, which the optimizer 
rewrites only in part.
   - `10 / id > 1 OR id < 1` with `id = 0` under ANSI.
   
   The `IF` case went away, and `array_contains(xs, 2)` with `xs = [1, 2]` 
stays, now accepted through its direct evaluation. The Scaladoc of `impliedBy` 
now describes the optimizer after SPARK-60983 and uses the partial rewrite as 
its example.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -1094,45 +1906,326 @@ class StreamingV2ScanPushDownSuite extends StreamTest 
with BeforeAndAfter {
       }
     }
   }
+
+  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 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 of a micro-batch prunes the filters 
that the constraints of
+  // their children imply, or does not.
+  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 has the value of the projection once it is 
optimized, so it applies the
+      // filter above the projection, once, and its check finds the filter 
there, whether the
+      // optimizer prunes filters 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, which each
+      // micro-batch applies 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: _*)): _*)

Review Comment:
   Done in 9a090d6: each of the four cases now asserts its pushed filters with 
`assertPushedFilters` before `assertEvaluatedOnce`, over the same confs. The 
Scaladoc of `assertEvaluatedOnce` now says `columns`.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -830,31 +1381,233 @@ class StreamingV2ScanPushDownSuite extends StreamTest 
with BeforeAndAfter {
     }
   }
 
-  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.")
+  Seq(true, false).foreach { failOnError =>
+    test(s"handle a failure of the optimization when the query starts: 
$failOnError") {
+      // 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)
+        val logs = new LogAppender("the failure of the optimization at the 
start")
+        try {
+          val failOnErrorConf = 
SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR.key
+          withSQLConf(failOnErrorConf -> failOnError.toString) {

Review Comment:
   Done in 9a090d6: the test now asserts that the default of 
`SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR` is true in the tests, before 
it sets the conf in both branches.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -311,7 +314,8 @@ class MicroBatchExecution(
                 sourceIdentifyingName
               )
             StreamingDataSourceV2ScanRelation(relation, streamingScan.scan, 
output,
-              streamingScan.stream, scanOutput = streamingScan.scanOutput)
+              streamingScan.stream, scanOutput = streamingScan.scanOutput,
+              pushedFilters = streamingScan.pushedFilters)

Review Comment:
   Done in 9a090d6: `StreamingV2ScanPushDownRealTimeSuite` now has "push down 
the filters of a real-time query". There, `PruningRealTimeTable` with 
`takesFilters` declares `STREAMING_FILTER_PUSHDOWN` and records the filters of 
a V1 builder, with the filter pushdown enabled. Its stream returns all the 
rows, so the answers and the per-batch check run as in the other modes, and the 
test asserts the filters that the builder and the relation got.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +383,201 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
 
   /**
    * Builds the scan of a streaming source, and creates its stream with 
`createStream`. If the
-   * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its 
scan builder supports
-   * the pushdown, and `conf` enables it, the scan only reads the columns of 
`output` that the query
-   * reads (see `requiredColumnsOfSources`). `requiredColumns` is only 
evaluated for such a scan.
-   * Otherwise, the scan reads all the columns of `output`, as the scans of 
streaming queries did
-   * before this pushdown.
+   * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+   * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and 
`conf` enables it,
+   * the scan only reads the columns of `output` that the query reads, or gets 
the filters that the
+   * query applies to all the rows that it reads from the source (see 
`columnsAndFiltersOfSources`).
+   * `reads` is only evaluated for such a scan. Otherwise, the scan reads all 
the columns of
+   * `output` with no filter, as the scans of streaming queries did before 
these pushdowns.
    *
-   * The streams of the scans of a table with the capability return the 
columns of the read
-   * schemas of the scans, in their order, so Spark asks each scan of such a 
table for its read
+   * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING` 
return the columns of the
+   * read schemas of the scans, in their order, so Spark asks each scan of 
such a table for its read
    * schema before it creates the stream, whether the scan reads all the 
columns or not. A pruned
    * scan must read the required columns and only columns of `output`, each 
once and with its
    * type, as `SupportsPushDownRequiredColumns` requires. If the scan builder 
or the scan fails
-   * with the pruning, or the read schema of a pruned scan cannot be read or 
does not follow
-   * `SupportsPushDownRequiredColumns`, a scan of all the columns is built 
instead, from a new scan
-   * builder, as without this pushdown. If the read schema of a scan of all 
the columns of such a
-   * table does not follow the relation, the query fails with 
STREAMING_SCAN_INVALID_READ_SCHEMA,
-   * unless `conf` disables the column pruning, with which the scan node 
outputs the columns of
-   * the relation, as it did before the capability.
+   * with the pushdowns, or the read schema of a pruned scan cannot be read or 
does not follow
+   * `SupportsPushDownRequiredColumns`, the scan is built again from a new 
scan builder: with the

Review Comment:
   Done in 9a090d6: the Scaladoc now says "with the column pruning alone, 
unless the read schema of the pruned scan did not follow it, and then with the 
filters alone if it had both". The bullet of the PR description says the same.
   



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