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


##########
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 = {
+      known.contains(exact(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) =>
+      DataType.equalsIgnoreNullability(column.dataType, value.dataType) &&
+        hasExactEquality(column.dataType)
+    })
+    // Whether `condition` evaluates to true with the values, which all its 
columns have.
+    def isTrue(condition: Expression): Boolean =
+      condition.references.forall(values.contains) && Try {
+        condition.transform { case column: Attribute => values(column) }.eval()
+      }.toOption.contains(true)
+    filter => noRow || holds(filter) || {
+      val columns = filter.references.toSeq.filter(values.contains)
+      columns.nonEmpty && (isTrue(filter) || {
+        val equalities = columns.map { column =>
+          val value = values(column)
+          if (value.value == null) EqualNullSafe(column, value) else 
EqualTo(column, value)
+        }
+        optimize((equalities :+ filter).reduce(And))
+          .exists(_.forall(condition => holds(condition) || isTrue(condition)))
+      })
+    }
+  }
+
+  // Whether the values of `dataType` that are equal are the same, so that a 
column that is equal
+  // to a value has this value in any expression: not those of the floating 
types, as 0.0 is
+  // equal to -0.0, nor the strings that a collation finds equal, nor the 
structs and arrays that
+  // have such values.
+  private def hasExactEquality(dataType: DataType): Boolean = dataType match {

Review Comment:
   Minor: this is about a bug outside this PR's diff, but it is the reason for 
this exclusion. Giving no values to the floating columns, and not pushing their 
filters down (`isPushable`), works around `ConstantPropagation` putting 0.0 in 
place of a column equal to 0.0, which is wrong in batch queries too: 
`canReplace` (expressions.scala:252-253) relies on 
`UnsafeRowUtils.isBinaryStable`, which only rejects the strings of collations 
that are not binary, while 0.0 and -0.0 are equal with different bits. For 
example, `SELECT * FROM t WHERE d = 0.0 AND atan2(d, -1.0) > 0` keeps a row 
where `d` is -0.0, since `atan2(0.0, -1.0)` is pi, while without the optimizer 
`atan2(-0.0, -1.0)` is -pi and the row is dropped. Could 
`ConstantPropagation.canReplace` exclude the floating types, as it does for the 
strings of non-binary collations, in a separate PR? Then the micro-batches 
would keep the filters on floating columns as they are, and these filters could 
be pushed down.



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