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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +696,239 @@ 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,
+      rewrites: PushedFilterRewrites = new PushedFilterRewrites): Unit = {
+    val hasPushedFilters = plan.exists {
+      case relation: StreamingDataSourceV2ScanRelation => 
relation.pushedFilters.nonEmpty
+      case _ => false
+    }
+    if (hasPushedFilters) {
+      // 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. It
+      // runs with a tracker of its own, so that its rules do not count as 
those of the
+      // optimization of the micro-batch.
+      def optimized(relation: StreamingDataSourceV2ScanRelation)(
+          condition: Expression): Option[Seq[Expression]] = 
rewrites(condition) {
+        QueryPlanningTracker.withTracker(new QueryPlanningTracker) {
+          SQLConf.withExistingConf(rewrites.optimizerConf(session)) {
+            session.sessionState.optimizer.execute(
+              Filter(condition, relation.copy(pushedFilters = Nil)))
+          }
+        } match {
+          case Filter(optimizedCondition, _: 
StreamingDataSourceV2ScanRelation) =>
+            Some(splitConjunctivePredicates(optimizedCondition))
+          case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+          case _ => None
+        }
+      }
+      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,
+            results.collectFirst { case (_, Failure(e)) => e }.orNull)
+        }
+      }
+    }
+  }
+
+  /**
+   * The conditions that the optimizer of a micro-batch rewrote for 
`checkPushedFilters`, by the
+   * condition canonicalized (see `exact`), which a streaming query keeps for 
its micro-batches:
+   * they check the same filters with the same values, which its optimizer 
rewrites in the same
+   * way, with the configuration that the first check takes from the session 
of the query. A query
+   * that restarts gets a new one, with the configuration that it restarts 
with.
+   */
+  class PushedFilterRewrites {
+    private val rewrites: Cache[Expression, Option[Seq[Expression]]] =
+      CacheBuilder.newBuilder().maximumSize(100).build[Expression, 
Option[Seq[Expression]]]()
+    @volatile private var conf: SQLConf = _
+
+    // The configuration of the micro-batches without the rules that infer 
filters, which would
+    // add conditions to those that `impliedBy` gets from the optimizer.
+    private[runtime] def optimizerConf(session: SparkSession): SQLConf = {
+      if (conf == null) {
+        conf = withoutInferredFilters(session.sessionState.conf.clone())
+      }
+      conf
+    }
+
+    def apply(condition: Expression)(
+        rewrite: => Option[Seq[Expression]]): Option[Seq[Expression]] = {
+      val key = exact(condition).canonicalized
+      Option(rewrites.getIfPresent(key)).getOrElse {
+        val rewritten = rewrite
+        rewrites.put(key, rewritten)
+        rewritten
+      }
+    }
+  }
+
+  // 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,
+  // nor do the conjuncts of such a filter after its first nondeterministic 
one, which sees the rows
+  // that these drop: only the leading deterministic ones, as when the query 
starts. A conjunct
+  // goes through a projection only if `CollapseProject` would inline its 
aliases, as
+  // `PhysicalOperation` does, so that an expensive alias used more than once 
is not copied.
+  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)
+        val applied = if (condition.deterministic) {
+          conditions ++ above
+        } else {
+          conditions.takeWhile(_.deterministic)
+        }
+        conditionsOverRelations(child, applied)
+      case Project(projectList, child) if projectList.forall(_.deterministic) 
=>
+        val aliases = getAliasMap(projectList)
+        val alwaysInline = 
SQLConf.get.getConf(SQLConf.COLLAPSE_PROJECT_ALWAYS_INLINE)
+        val inlined = above.filter { condition =>
+          CollapseProject.canCollapseExpressions(Seq(condition), aliases, 
alwaysInline)
+        }
+        conditionsOverRelations(child, inlined.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 given the values that the facts give to its 
columns, equal to
+   * literals: the filter holds if it evaluates to true with these values when 
all its columns
+   * have one, and otherwise if `optimize`, the optimizer of the micro-batch, 
rewrites the filter
+   * with the equalities of these values into conditions that hold, or 
evaluate to true with the
+   * values. The optimizer of a micro-batch puts these values in place of the 
columns in its
+   * filters (see `ConstantPropagation`), wherever no expression that may fail 
keeps them, 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 `(a + 
b > 3 AND b > 0) OR
+   * a > 9` becomes `a + b > 3 OR a > 9` with `b = 1`. Only the columns of the 
types whose equal
+   * values are the same get values (see `hasExactEquality`), not those of 
floating types, as a
+   * column equal to 0.0 may be -0.0, or strings of a collation that is not 
binary, nor the
+   * structs and arrays that have such values, whose filters are not pushed 
down (see
+   * `isPushable`). The facts and the filters are compared with `exact`. 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 = exactSet(facts)
+    def holds(condition: Expression): Boolean = {

Review Comment:
   Done in 0bc41c2: `holds` now applies `exact` to the condition once and 
recurses over the result. The subtrees keep their canonicalized forms and hash 
codes, which are cached, so a long OR is linear.
   
   `checkPushedFilters` also skips the occurrences of the relations whose 
`pushedFilters` is empty. So `impliedBy` only builds its facts and values for 
relations with pushed filters.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -21,67 +21,155 @@ import scala.collection.mutable
 import scala.util.{Failure, Success, Try}
 import scala.util.control.NonFatal
 
+import com.google.common.cache.{Cache, CacheBuilder}
+
 import org.apache.spark.SparkException
 import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.{InternalRow, QueryPlanningTracker}
 import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
-import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, AttributeSet, Cast, Expression, Generator, NamedExpression, 
OuterReference, SubqueryExpression, Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, 
AttributeMap, AttributeReference, AttributeSet, Cast, EqualNullSafe, EqualTo, 
Expression, ExpressionSet, ExprUtils, Generator, LeafExpression, Literal, 
NamedExpression, Or, OuterReference, PredicateHelper, SubqueryExpression, 
Unevaluable}
+import org.apache.spark.sql.catalyst.expressions.Literal.TrueLiteral
 import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
-import org.apache.spark.sql.catalyst.optimizer.ReplaceExpressions
+import org.apache.spark.sql.catalyst.optimizer.{CollapseProject, 
InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions}
 import org.apache.spark.sql.catalyst.planning.PhysicalOperation
-import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, LeafNode, 
LogicalPlan, Statistics}
+import org.apache.spark.sql.catalyst.plans.logical.{AsOfJoin, CTERelationDef, 
Filter, Join, LateralJoin, LeafNode, LogicalPlan, Project, SetOperation, 
Statistics}
 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.catalyst.util.{truncatedString, ArrayData, 
CharVarcharUtils, MapData}
 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, 
SupportsPushDownRequiredColumns}
+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, 
StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
 import 
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, 
OffsetSeqMetadataBase}
 import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{AnyTimeType, DataType, DatetimeType, 
StringType, StructType, VariantType}
+import org.apache.spark.sql.types.{AnyTimestampNanoType, AnyTimeType, 
ArrayType, BinaryType, BooleanType, DataType, DatetimeType, DateType, 
DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, MapType, 
StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, 
YearMonthIntervalType}
 import org.apache.spark.sql.util.CaseInsensitiveStringMap
-import org.apache.spark.util.Utils
 
 /**
- * Pushes the top-level columns 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`.
+ * 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
- * reads the columns that the planner takes from the optimized plan for the 
relation of the source
- * (see `DataSourceV2Strategy`): those of the projections and the filters over 
each occurrence of
- * the relation.
+ * gets what the planner takes from the optimized plan for the relation of the 
source (see
+ * `DataSourceV2Strategy`): the projections and the filters over each 
occurrence of the relation.
  *
- * The plan of each micro-batch is the one without this pushdown: 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 scan may drop the rows that fail the filters that its builder got, so 
the optimized plan of
+ * each micro-batch must apply them to all the rows that it reads from the 
source, which it checks
+ * before it reads them (see `checkPushedFilters`). 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 {
+private[sql] object StreamingV2ScanPushDown
+  extends Logging with PredicateHelper with AliasHelper {
+
+  /**
+   * 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. The scan may 
evaluate the pushed
+     * filters first, on the rows of the source, 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) => 
exact(l).semanticEquals(exact(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(exactSet)
+          first.filter(filter => sets.forall(_.contains(exact(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`), and if all its columns are of types whose equal 
values are the same
+   * (see `hasExactEquality`), not floating types or strings of a collation 
that is not binary.
+   * The optimizer of a micro-batch may rewrite a filter with the values that 
its plan gives to
+   * the columns of the filter, which the check of the micro-batches then 
gives to them too (see
+   * `impliedBy`), and it only can for such columns: a micro-batch that has a 
pushed filter on
+   * other columns rewritten fails, and so do the next ones, which have the 
same plan.
+   */
+  private def isPushable(filter: Expression): Boolean = {
+    !SubqueryExpression.hasSubquery(filter) && 
!filter.exists(_.isInstanceOf[StartupValue]) &&
+      filter.references.forall(column => hasExactEquality(column.dataType))
+  }
+
+  /**
+   * Returns `expression` for the comparisons of filters, with its literals of 
floating values,
+   * also in structs, arrays and maps, replaced by placeholders of their bits: 
`Literal.equals`
+   * finds 0.0 and -0.0 equal, while filters that only differ in the sign of a 
zero may keep
+   * different rows, as `atan2(0.0, x) > 0` and `atan2(-0.0, x) > 0` do for a 
negative `x`. The
+   * NaN values have the same bits, as Spark evaluates them alike.
+   */
+  private def exact(expression: Expression): Expression = 
expression.transformUp {

Review Comment:
   Done in 0bc41c2: `exact`, `exactSet`, `hasFloating`, `exactValue` and 
`ExactLiteral` now sit together after `isPushable`, with `hasExactEquality`, 
which `isPushable` and `impliedBy` both use. Their code moved as it is.



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