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


##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java:
##########
@@ -190,5 +190,37 @@ public enum TableCapability {
    *
    * @since 4.4.0
    */
-  STREAMING_COLUMN_PRUNING
+  STREAMING_COLUMN_PRUNING,
+
+  /**
+   * Signals that the scans of the streaming reads of the table may get the 
filters that the
+   * streaming query applies to all the rows that it reads from the table, 
which Spark pushes to a
+   * scan builder that implements
+   * {@link org.apache.spark.sql.connector.read.SupportsPushDownFilters} or
+   * {@link org.apache.spark.sql.connector.read.SupportsPushDownV2Filters}, as 
it does for the
+   * scans of batch reads: the filters that Spark plans with the scan, over 
the relation of the
+   * read, up to the first nondeterministic one, so the filters after a 
nondeterministic filter or
+   * projection, or above another operator, such as a filter on the event-time 
column above its
+   * watermark, are not pushed. The filters of a {@code 
SupportsPushDownFilters} builder compare
+   * columns with values, which cannot fail, so it gets such filters whatever 
their order among
+   * the filters over the relation. A builder whose filters may fail on some 
rows, as a cast does
+   * with ANSI, only gets the filters that the query applies before any other 
filter, in their
+   * order, and the streams of its scans must not evaluate a filter on a row 
that a filter before
+   * it drops, as Spark does not, so that each filter only sees the rows that 
the query evaluates it
+   * on.
+   * <p>
+   * Spark builds the scan of a streaming read once, when the query starts, 
from the plan of the
+   * query optimized then, and creates the micro-batch or continuous stream of 
the read from that
+   * scan. By returning this capability, a table declares that its scan 
builders can take filters
+   * for such a scan, as for the scan of a batch read. The stream may then 
drop the rows that fail

Review Comment:
   **This lets the stream drop the rows that fail the filters, but does not say 
that its offsets must not depend on them.** The filters are decided again each 
time the query starts, while the query goes on from the offsets of its 
checkpoint: `spark.sql.streaming.v2FilterPushdown.enabled` is not one of the 
confs of the offset log (OffsetSeq.scala:199-214), and another session conf, an 
edit of the query or another version of Spark can push other filters. So a 
connector that numbers only the files or the rows that pass the filters in its 
offsets would skip or repeat data with no error after such a restart. The 
column pruning cannot do this, since it never changes which rows a stream 
returns. Could this paragraph say that the offsets of the stream, including 
those of `latestOffset`, must be positions in all the rows of the table, as 
without filters, since a restart may push other filters with the same offsets?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,172 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
     }
   }
 
+  /**
+   * Checks that `plan`, the optimized plan of a micro-batch in `session`, 
applies the filters that
+   * the scans of its sources got when the query started to all the rows that 
it reads from them:
+   * a scan may drop the rows that fail its filters, so the plan must drop 
them too. The conditions
+   * that the plan applies to all the rows of each occurrence of a relation 
whose scan got filters
+   * must imply these filters (see `impliedBy`). Otherwise, the value of an 
expression in a pushed
+   * filter changed after the query started, as a function of the time that 
`forStartup` does not
+   * replace would, or the configuration of the optimizer changed in the 
session of the query, or
+   * the optimizer of the micro-batch rewrote a pushed filter in a way that 
`impliedBy` does not
+   * follow, and the micro-batch fails before it reads its data, with the 
failure of the optimizer
+   * as its cause if there is one.
+   */
+  def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = {
+    val hasPushedFilters = plan.exists {
+      case relation: StreamingDataSourceV2ScanRelation => 
relation.pushedFilters.nonEmpty
+      case _ => false
+    }
+    if (hasPushedFilters) {
+      // The configuration of the micro-batch, without the rules that infer 
filters, which would
+      // add conditions to those that `impliedBy` gets from the optimizer.
+      lazy val optimizerConf = 
withoutInferredFilters(session.sessionState.conf.clone())
+      // The conjuncts of `condition` once the optimizer of the micro-batch 
optimizes a filter of
+      // `relation` with it, none if it folds into true, which the next 
micro-batches reuse.
+      def optimized(relation: StreamingDataSourceV2ScanRelation)(
+          condition: Expression): Option[Seq[Expression]] = {
+        val key = condition.canonicalized
+        Option(optimizedConditions.getIfPresent(key)).getOrElse {
+          val rewritten = SQLConf.withExistingConf(optimizerConf) {
+            session.sessionState.optimizer.execute(
+              Filter(condition, relation.copy(pushedFilters = Nil)))
+          } match {
+            case Filter(optimizedCondition, _: 
StreamingDataSourceV2ScanRelation) =>
+              Some(splitConjunctivePredicates(optimizedCondition))
+            case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+            case _ => None
+          }
+          optimizedConditions.put(key, rewritten)
+          rewritten
+        }
+      }
+      conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) 
=>
+        val implied = impliedBy(conditions, optimized(relation))
+        val results = relation.pushedFilters.map(filter => filter -> 
Try(implied(filter)))
+        val unapplied = results.collect {
+          case (filter, result) if !result.getOrElse(false) => filter
+        }
+        if (unapplied.nonEmpty) {
+          throw QueryExecutionErrors.streamingScanFiltersChangedError(
+            sourceName(relation.relation.table, relation.catalog, 
relation.identifier),
+            unapplied.map(_.sql),
+            results.collectFirst { case (_, Failure(e)) => e }.orNull)
+        }
+      }
+    }
+  }
+
+  // The conditions that the optimizer of a micro-batch rewrote for 
`checkPushedFilters`, by the
+  // condition canonicalized: the micro-batches of a query check the same 
filters with the same
+  // values, which the optimizer rewrites in the same way.
+  private val optimizedConditions: Cache[Expression, Option[Seq[Expression]]] =

Review Comment:
   Minor: following up on item 54 
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499818888)), 
thank you for the cache. It is a field of this object, so all the streaming 
queries of the driver share its 100 entries, keyed only by the canonicalized 
condition, which keeps the expression IDs and the values but not the query, the 
session or its configuration:
   
   - With enough queries, or filters on several double columns equal to zero 
(up to 8 keys each), the entries are evicted, and the optimizer runs again in 
the micro-batches.
   - The entries outlive their queries and keep their expressions, e.g. large 
`IN` lists, or the closures of the `ScalaUDF`s that a Catalyst builder gets.
   - A query that restarts from the same DataFrame in the same session has the 
same expression IDs, so it reuses the rewrites made with the earlier 
configuration of the optimizer, including a cached `None`, which keeps failing 
it with `STREAMING_SCAN_FILTERS_CHANGED` after the configuration is fixed.
   
   Could the cache belong to the query, e.g. created by `StreamExecution` and 
passed to `IncrementalExecution`, or have the configuration of the optimizer in 
its key?



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

Review Comment:
   **A correction to my list in item 45 
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395300)): 
`ConstantPropagation` also puts the values of struct, array and nanosecond 
timestamp columns into comparisons, so the check still fails micro-batches 
whose plans keep the right rows.** `canReplace` (expressions.scala:252-253) 
takes any column whose type `isBinaryStable` (UnsafeRowUtils.scala:235), which 
only leaves out the strings of non-binary collations, at any depth. Here, 
`hasExactEquality` (L764-L770) has no case for `StructType`, `ArrayType`, 
`TimestampNTZNanosType` or `TimestampLTZNanosType`, and `column.dataType == 
value.dataType` also compares the nullability of the fields.
   
   For example, a V1 builder gets `k.a > 0` (`GreaterThan("k.a", 0)`, through 
the nested predicate pushdown of `PushDownUtils.getsFilter`) from 
`stream.where("k.a > 0").join(static.where("sk = named_struct('a', 1)"), $"k" 
=== $"sk")`. When the query starts, the static side is a `BatchRelation`, so 
nothing is inferred from it. In each micro-batch, `InferFiltersFromConstraints` 
adds `k = [1]` over the stream, and `ConstantPropagation` turns `k.a > 0` into 
`1 > 0`, which folds to true and is dropped. `values` skips `k`, both for its 
type and because the folded `named_struct` has a non-nullable field while the 
field of `k` may be nullable, so every micro-batch with data fails with 
`STREAMING_SCAN_FILTERS_CHANGED`. A smaller case of the same kind: a 
`SupportsPushDownCatalystFilters` builder that gets `c = d` on two `UTF8_LCASE` 
columns, once a micro-batch infers `c = 'x'`, since 
`isSameCollationAttrRefComparison` (expressions.scala:327) lets 
`ConstantPropagation` turn it into `'x' = d`.
   
   Could `hasExactEquality` take the structs and arrays whose fields and 
elements have exact equality, and the nanosecond timestamps, with the types 
compared by `DataType.equalsIgnoreNullability` as `readOutput` does at L599, 
and could a test join on a struct key? The comparisons of two collated columns 
could stay out, as the PR description says for the strings of non-binary 
collations, if the Scaladoc of `impliedBy` names them.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,172 @@ private[sql] object StreamingV2ScanPushDown extends 
Logging {
     }
   }
 
+  /**
+   * Checks that `plan`, the optimized plan of a micro-batch in `session`, 
applies the filters that
+   * the scans of its sources got when the query started to all the rows that 
it reads from them:
+   * a scan may drop the rows that fail its filters, so the plan must drop 
them too. The conditions
+   * that the plan applies to all the rows of each occurrence of a relation 
whose scan got filters
+   * must imply these filters (see `impliedBy`). Otherwise, the value of an 
expression in a pushed
+   * filter changed after the query started, as a function of the time that 
`forStartup` does not
+   * replace would, or the configuration of the optimizer changed in the 
session of the query, or
+   * the optimizer of the micro-batch rewrote a pushed filter in a way that 
`impliedBy` does not
+   * follow, and the micro-batch fails before it reads its data, with the 
failure of the optimizer
+   * as its cause if there is one.
+   */
+  def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = {
+    val hasPushedFilters = plan.exists {
+      case relation: StreamingDataSourceV2ScanRelation => 
relation.pushedFilters.nonEmpty
+      case _ => false
+    }
+    if (hasPushedFilters) {
+      // The configuration of the micro-batch, without the rules that infer 
filters, which would
+      // add conditions to those that `impliedBy` gets from the optimizer.
+      lazy val optimizerConf = 
withoutInferredFilters(session.sessionState.conf.clone())
+      // The conjuncts of `condition` once the optimizer of the micro-batch 
optimizes a filter of
+      // `relation` with it, none if it folds into true, which the next 
micro-batches reuse.
+      def optimized(relation: StreamingDataSourceV2ScanRelation)(
+          condition: Expression): Option[Seq[Expression]] = {
+        val key = condition.canonicalized
+        Option(optimizedConditions.getIfPresent(key)).getOrElse {
+          val rewritten = SQLConf.withExistingConf(optimizerConf) {
+            session.sessionState.optimizer.execute(
+              Filter(condition, relation.copy(pushedFilters = Nil)))
+          } match {
+            case Filter(optimizedCondition, _: 
StreamingDataSourceV2ScanRelation) =>
+              Some(splitConjunctivePredicates(optimizedCondition))
+            case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+            case _ => None
+          }
+          optimizedConditions.put(key, rewritten)
+          rewritten
+        }
+      }
+      conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) 
=>
+        val implied = impliedBy(conditions, optimized(relation))
+        val results = relation.pushedFilters.map(filter => filter -> 
Try(implied(filter)))
+        val unapplied = results.collect {
+          case (filter, result) if !result.getOrElse(false) => filter
+        }
+        if (unapplied.nonEmpty) {
+          throw QueryExecutionErrors.streamingScanFiltersChangedError(
+            sourceName(relation.relation.table, relation.catalog, 
relation.identifier),
+            unapplied.map(_.sql),
+            results.collectFirst { case (_, Failure(e)) => e }.orNull)
+        }
+      }
+    }
+  }
+
+  // The conditions that the optimizer of a micro-batch rewrote for 
`checkPushedFilters`, by the
+  // condition canonicalized: the micro-batches of a query check the same 
filters with the same
+  // values, which the optimizer rewrites in the same way.
+  private val optimizedConditions: Cache[Expression, Option[Seq[Expression]]] =
+    CacheBuilder.newBuilder().maximumSize(100).build[Expression, 
Option[Seq[Expression]]]()
+
+  // Each occurrence of a streaming relation in `plan`, with the deterministic 
conditions that the
+  // plan applies to all its rows, given `above`, those that it applies to all 
the rows of `plan`:
+  // the conditions of the filters over it, through the projections, with the 
aliases of these in
+  // place of their names, as `PhysicalOperation` finds the filters of a 
relation. The conditions
+  // over a filter or a projection that is not deterministic do not hold for 
the rows that it gets.
+  private def conditionsOverRelations(
+      plan: LogicalPlan,
+      above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation, 
Seq[Expression])] = {
+    plan match {
+      case relation: StreamingDataSourceV2ScanRelation => Seq(relation -> 
above)
+      case Filter(condition, child) =>
+        val conditions = 
splitConjunctivePredicates(condition).filter(_.deterministic)

Review Comment:
   Minor: this keeps the deterministic conjuncts of a nondeterministic 
condition, also those after its first nondeterministic one, so the check 
accepts a plan whose nondeterministic conjunct sees the rows that the scan 
drops. In `Filter(rand(0) > 0.5 AND id > 1, relation)`, `rand(0)` is evaluated 
on every row before `id > 1`, as in `Filter(id > 1, Filter(rand(0) > 0.5, 
relation))`, which the comment at L687 and the test at 
StreamingV2ScanPushDownSuite.scala:1465 reject for that reason. Yet 
StreamingV2ScanPushDownSuite.scala:1466 asserts that the first one is accepted. 
With `id > 1` pushed, `rand(0)` sees fewer rows, so the seeded sample keeps 
other rows than without the pushdown.
   
   When the query starts, `readsOfSources` only takes 
`filters.takeWhile(_.deterministic)` (L216), so such a conjunct is never pushed 
from the start; only a micro-batch whose plan differs from the start, which is 
what this check is for, reaches it. Could the walk keep only 
`splitConjunctivePredicates(condition).takeWhile(_.deterministic)` for a 
nondeterministic condition, and the test at 
StreamingV2ScanPushDownSuite.scala:1466 assert that the plan is rejected?



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