dongjoon-hyun commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4517955462
##########
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))
Review Comment:
Minor: `hasExactEquality` excludes more types than the docs say. Besides the
floating types and the strings of non-binary collations, it rejects maps,
variants, geometry and geography, calendar intervals, UDTs and `NullType`, and
the structs and arrays with them. The Javadoc of `STREAMING_FILTER_PUSHDOWN`
(TableCapability.java:204-205), the config doc (SQLConf.scala:6333-6335) and
the Scaladoc here only name the floating types, the strings, and the structs
and arrays with such values. For the types that are not orderable
(`OrderUtils.isOrderable`: maps, variants, geo types and calendar intervals),
no `column = literal` equality passes the type check, so neither
`ConstantPropagation` nor `impliedBy` can give such a column a value, and the
exclusion buys nothing. For example, `payload.id = 5` on `payload struct<id:
int, attrs: map<string, string>>` is not pushed down. Could `isPushable` accept
the columns of these types, or could the docs give the whole list?
##########
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) &&
Review Comment:
**`ConstantPropagation` uses an equality with a struct literal whose field
names differ from those of the column, while this gives the column no value
then.** `BinaryComparison.sameType` compares the types with
`DataType.equalsStructurally(left, right, ignoreNullability = true)`, which
ignores the field names (predicates.scala:1047-1048), and
`inferAdditionalConstraints` substitutes the attributes without comparing their
types. So with a stream column `s struct<a: int>` joined on `s = k` with a
static `k struct<x: int>`, where the static side has `k = named_struct('x',
1)`, each micro-batch infers `s = named_struct('x', 1)`, and
`ConstantPropagation` folds a pushed `s.a > 0` into true, as `GetStructField`
reads by ordinal. The facts are then `isnotnull(s)` and that equality,
`equalsIgnoreNullability` drops the equality here because the names differ,
`columns` is empty, and every micro-batch fails with
`STREAMING_SCAN_FILTERS_CHANGED`, although its plan keeps the right rows. The sa
me happens with field names that differ only in case, and with arrays of such
structs.
Following up on item 82
([thread](https://github.com/apache/spark/pull/60129#discussion_r4515255492)):
`s` has a type that gets values, so its filters are still pushed down. Could
this accept `DataType.equalsStructurally(column.dataType, value.dataType,
ignoreNullability = true)` and give the column `Literal(value.value,
column.dataType)`? A literal of the type of the column keeps the check right
for the expressions that read the field names, such as `to_json`.
##########
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()
Review Comment:
Minor: following up on item 66
([thread](https://github.com/apache/spark/pull/60129#discussion_r4503975235)):
the direct evaluation that 9a090d6 added calls `eval()` on any filter or
returned conjunct whose columns all have values, also on deterministic
expressions that are not foldable, such as a `ScalaUDF`, which the optimizer
never evaluates on the driver (`ConstantPropagation.fold` and `ConstantFolding`
require `foldable`). A `SupportsPushDownCatalystFilters` builder gets any
deterministic filter (PushDownUtils.scala:89), so with `my_udf(id) > 0 OR id >
3` pushed and `id = 5` inferred through a join, the micro-batch folds the
filter into true, `holds` fails, and `isTrue` runs `my_udf(5)` on the driver.
Its result is not cached, so this happens in every micro-batch. A UDF with side
effects, or a slow one, then runs in the planning of each micro-batch, and a
fatal error such as a `LinkageError` escapes the `Try` here and the one at
L740, and fails the query. Could `isTrue` requi
re the expression with the values to be `foldable`, as
`ConstantPropagation.fold` does?
##########
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.
##########
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:
Nit: `exact` and `exactSet` sit here with `isPushable` and `Reads`, where
they are first used, about 750 lines from the helpers that only they use,
`hasFloating` (L896), `exactValue` (L903) and `ExactLiteral` (L927), which sit
in the section of the per-batch check after `hasExactEquality`. Could these
five go together?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownRealTimeSuite.scala:
##########
@@ -71,6 +72,32 @@ class StreamingV2ScanPushDownRealTimeSuite extends
StreamRealTimeModeSuiteBase {
AddData(input, (4L, "d", 5), (5L, "e", 50)),
CheckAnswer("b", "c", "e"))
}
+
+ test("push down the filters of a real-time query") {
Review Comment:
Minor: following up on item 74
([thread](https://github.com/apache/spark/pull/60129#discussion_r4503975266)),
thank you for this test. Its stream returns all the rows, and its filters do
not change after the start, so it would also pass if `checkPushedFilters` did
not run for the real-time batches, or if the relation of a real-time batch lost
its `pushedFilters`: Spark still applies `extra > 10` after a stream that drops
nothing. Could it read a stream that drops the rows that fail the pushed
filters, as `FilteringMemoryStream` (StreamingV2ScanPushDownSuite.scala:2677)
does for the micro-batch tests, and add a case where a batch no longer applies
the pushed filter and fails, as those tests do with `ChangingValue`?
##########
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:
Nit: `holds` calls `exact(condition)` again at each level of its And/Or
recursion, and each call is a `transformUp` of the subtree, which
`ExpressionSet.contains` canonicalizes again when it has floating literals. So
a left-deep OR of n disjuncts that are not facts costs O(n^2) for each pushed
filter, in every micro-batch. Also, `impliedBy` builds `exactSet(facts)` and
`values` for each occurrence of a relation (L738-739), also for those whose
`pushedFilters` is empty. Could `holds` take `exact` of the condition once and
recurse over the result, and could L738 skip the relations with no pushed
filters?
--
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]