HyukjinKwon commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4518402678
##########
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:
Done in 0bc41c2, as you suggest. A column now gets the value of an equality
whose literal has the type of the column apart from the names and the
nullability of its fields. This is `DataType.equalsStructurally(...,
ignoreNullability = true)`, as in `BinaryComparison.sameType`. The value is
`Literal(value.value, column.dataType)`, with the type of the column.
The names matter for the expressions that read the type of their child when
they are evaluated. `to_json` turns out not to be one of them:
`ReplaceExpressions` builds its evaluator from the type of the column before
`ConstantPropagation` runs. `typeof` is one: with the literal of
`named_struct('x', 1)` in place of `s`, `typeof(s)` would be `struct<x:int>`
rather than `struct<a:int>`.
With names that differ only in case, the analyzer casts the static side to
the type of the column, `k = cast(sk as struct<a:int>)`. So no equality with a
literal is inferred for the stream side, and the micro-batches keep `k.a > 0`
as it is, which the check finds.
Tests:
- The unit test of the check now covers struct literals whose fields have
other names, names that differ only in case, and an array of such structs. It
also has a filter on `typeof(k)` that holds with the type of the column but not
with the type of the literal.
- The end-to-end test of the folds also joins on a static `struct<x: int>`.
It checks that `k.a > 0` is pushed down, that the micro-batches fold it away,
and that the answer is right.
##########
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:
Done in 0bc41c2: `isTrue` now evaluates a filter or a conjunct with the
values only when the result is foldable, as `ConstantPropagation.fold` and
`ConstantFolding` require. So it never runs a UDF.
Your example still passes, through the optimizer. With `id = 5`, the
optimizer keeps `my_udf(id)` and folds `id > 3` into true, and so the whole
filter. The unit test of the check now has this case, with a Scala UDF that
counts its calls. The check accepts the plan, and the UDF is called zero times.
##########
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:
Done in 0bc41c2, the first way. `hasExactEquality` now also accepts:
- the types that are not orderable (`OrderUtils.isOrderable`): maps,
variants, the geo types and calendar intervals. No equality compares them, so
no column of these types gets a value, in the micro-batches or in the check;
- `NullType`, whose only value is null;
- a user-defined type, when its SQL type is accepted.
It still recurses into structs and arrays, so `payload struct<id: int,
attrs: map<string, string>>` is accepted, and `payload.id = 5` is pushed down.
The only exclusions left are those that the docs name: the floating types, the
strings of non-binary collations, and the structs, arrays and user-defined
types with such values. The Javadoc of `STREAMING_FILTER_PUSHDOWN`, the config
doc and the Scaladoc now name user-defined types too.
The new test `push down the filters on columns of types that no equality
compares` checks that the filters on a map, a variant and a struct with a map
are pushed down. It also runs `p.id = 5` through a stream that drops the rows
that fail it.
##########
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:
Done in 0bc41c2: the real-time fixture now drops rows, as the micro-batch
ones do. `PruningRealTimeTable` binds the filters that its builder takes to the
columns of the stream. The readers of `PruningLowLatencyStream` drop the rows
that fail them, in `next` and in `nextWithTimeout`, and count them. The test of
the pushdown now checks that the stream dropped the two rows that fail `extra >
10`.
The new test `fail a real-time batch whose query no longer applies the
filters that its scan got` uses `ChangingValue`. The scan gets `extra < 1`, the
plan of the batch has a larger value, and the batch fails with
`STREAMING_SCAN_FILTERS_CHANGED`. The test fails when `checkPushedFilters` does
not run.
--
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]