HyukjinKwon commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4500207632
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,172 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
}
}
+ /**
+ * Checks that `plan`, the optimized plan of a micro-batch in `session`,
applies the filters that
+ * the scans of its sources got when the query started to all the rows that
it reads from them:
+ * a scan may drop the rows that fail its filters, so the plan must drop
them too. The conditions
+ * that the plan applies to all the rows of each occurrence of a relation
whose scan got filters
+ * must imply these filters (see `impliedBy`). Otherwise, the value of an
expression in a pushed
+ * filter changed after the query started, as a function of the time that
`forStartup` does not
+ * replace would, or the configuration of the optimizer changed in the
session of the query, or
+ * the optimizer of the micro-batch rewrote a pushed filter in a way that
`impliedBy` does not
+ * follow, and the micro-batch fails before it reads its data, with the
failure of the optimizer
+ * as its cause if there is one.
+ */
+ def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = {
+ val hasPushedFilters = plan.exists {
+ case relation: StreamingDataSourceV2ScanRelation =>
relation.pushedFilters.nonEmpty
+ case _ => false
+ }
+ if (hasPushedFilters) {
+ // The configuration of the micro-batch, without the rules that infer
filters, which would
+ // add conditions to those that `impliedBy` gets from the optimizer.
+ lazy val optimizerConf =
withoutInferredFilters(session.sessionState.conf.clone())
+ // The conjuncts of `condition` once the optimizer of the micro-batch
optimizes a filter of
+ // `relation` with it, none if it folds into true, which the next
micro-batches reuse.
+ def optimized(relation: StreamingDataSourceV2ScanRelation)(
+ condition: Expression): Option[Seq[Expression]] = {
+ val key = condition.canonicalized
+ Option(optimizedConditions.getIfPresent(key)).getOrElse {
+ val rewritten = SQLConf.withExistingConf(optimizerConf) {
+ session.sessionState.optimizer.execute(
+ Filter(condition, relation.copy(pushedFilters = Nil)))
+ } match {
+ case Filter(optimizedCondition, _:
StreamingDataSourceV2ScanRelation) =>
+ Some(splitConjunctivePredicates(optimizedCondition))
+ case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+ case _ => None
+ }
+ optimizedConditions.put(key, rewritten)
+ rewritten
+ }
+ }
+ conditionsOverRelations(plan, Nil).foreach { case (relation, conditions)
=>
+ val implied = impliedBy(conditions, optimized(relation))
+ val results = relation.pushedFilters.map(filter => filter ->
Try(implied(filter)))
+ val unapplied = results.collect {
+ case (filter, result) if !result.getOrElse(false) => filter
+ }
+ if (unapplied.nonEmpty) {
+ throw QueryExecutionErrors.streamingScanFiltersChangedError(
+ sourceName(relation.relation.table, relation.catalog,
relation.identifier),
+ unapplied.map(_.sql),
+ results.collectFirst { case (_, Failure(e)) => e }.orNull)
+ }
+ }
+ }
+ }
+
+ // The conditions that the optimizer of a micro-batch rewrote for
`checkPushedFilters`, by the
+ // condition canonicalized: the micro-batches of a query check the same
filters with the same
+ // values, which the optimizer rewrites in the same way.
+ private val optimizedConditions: Cache[Expression, Option[Seq[Expression]]] =
+ CacheBuilder.newBuilder().maximumSize(100).build[Expression,
Option[Seq[Expression]]]()
+
+ // Each occurrence of a streaming relation in `plan`, with the deterministic
conditions that the
+ // plan applies to all its rows, given `above`, those that it applies to all
the rows of `plan`:
+ // the conditions of the filters over it, through the projections, with the
aliases of these in
+ // place of their names, as `PhysicalOperation` finds the filters of a
relation. The conditions
+ // over a filter or a projection that is not deterministic do not hold for
the rows that it gets.
+ private def conditionsOverRelations(
+ plan: LogicalPlan,
+ above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation,
Seq[Expression])] = {
+ plan match {
+ case relation: StreamingDataSourceV2ScanRelation => Seq(relation ->
above)
+ case Filter(condition, child) =>
+ val conditions =
splitConjunctivePredicates(condition).filter(_.deterministic)
+ conditionsOverRelations(child,
+ if (condition.deterministic) conditions ++ above else conditions)
+ case Project(projectList, child) if projectList.forall(_.deterministic)
=>
+ val aliases = getAliasMap(projectList)
+ conditionsOverRelations(child, above.map(replaceAlias(_, aliases)))
+ case other => other.children.flatMap(conditionsOverRelations(_, Nil))
+ }
+ }
+
+ /**
+ * Returns whether a filter is implied by `facts`, the deterministic
conditions that hold for all
+ * the rows that a plan keeps from a relation. No row passes a fact that is
false or null, which
+ * implies any filter. Otherwise, the facts imply a filter if they have it,
or its conjuncts, or
+ * one of its disjuncts, also once the columns that the facts make equal to
literals have these
+ * values in it, and `optimize`, the optimizer of the micro-batch, rewrote
it. The optimizer of a
+ * micro-batch puts these values in place of the columns in its filters (see
+ * `ConstantPropagation`), e.g. with an equality that it infers through a
join, and rewrites the
+ * filters with the other rules of the same batch, so that `id > 1` becomes
true with `id = 5`,
+ * and `CAST(extra AS BIGINT) < id` becomes `extra < 5`. The values replace
their columns for the
+ * types whose equal values are the same (see `hasExactEquality`), and for
the floating types,
+ * whose equal values only differ for 0.0 and -0.0, and for NaN values,
which Spark evaluates
+ * alike: a column equal to zero is 0.0 or -0.0, so the filter must hold
with each, as
+ * `floor(d) >= 0` does, unlike `CAST(d AS STRING) = '0.0'`. This may miss
that the facts imply a
+ * filter, which fails the micro-batch, but never finds that they imply a
filter that they do not
+ * imply, as long as the rules of the optimizer keep what the filters mean.
+ */
+ private def impliedBy(
+ facts: Seq[Expression],
+ optimize: Expression => Option[Seq[Expression]]): Expression => Boolean
= {
+ val noRow = facts.exists {
+ case Literal(false, BooleanType) | Literal(null, _) => true
+ case _ => false
+ }
+ val known = ExpressionSet(facts)
+ def holds(condition: Expression): Boolean = known.contains(condition) ||
(condition match {
+ case TrueLiteral => true
+ case And(left, right) => holds(left) && holds(right)
+ case Or(left, right) => holds(left) || holds(right)
+ case _ => false
+ })
+ val values = AttributeMap(facts.collect {
+ case EqualTo(column: Attribute, value: Literal) => column -> value
+ case EqualTo(value: Literal, column: Attribute) => column -> value
+ case EqualNullSafe(column: Attribute, value: Literal) => column -> value
+ case EqualNullSafe(value: Literal, column: Attribute) => column -> value
+ }.filter { case (column, value) =>
+ column.dataType == value.dataType &&
Review Comment:
Done in 92694a4: `hasExactEquality` now takes the nanosecond timestamps
(`AnyTimestampNanoType`) and the structs and arrays whose fields and elements
have exact equality. `values` compares the types with
`DataType.equalsIgnoreNullability`, so the literal `named_struct('a', 1)`,
whose field isn't nullable, gives its value to `k`.
The test of the folded filters now joins on a struct key, with `k.a > 0`
against `sk = named_struct('a', 1)`. The test of the check covers a struct
literal and an array literal whose nullability differs from the column.
The comparison of two columns of a non-binary collation stays out, and the
Scaladoc of `impliedBy` now says so: a string of such a collation gets no
value, even where `ConstantPropagation` puts it in a comparison of two columns
of that collation.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,172 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
}
}
+ /**
+ * Checks that `plan`, the optimized plan of a micro-batch in `session`,
applies the filters that
+ * the scans of its sources got when the query started to all the rows that
it reads from them:
+ * a scan may drop the rows that fail its filters, so the plan must drop
them too. The conditions
+ * that the plan applies to all the rows of each occurrence of a relation
whose scan got filters
+ * must imply these filters (see `impliedBy`). Otherwise, the value of an
expression in a pushed
+ * filter changed after the query started, as a function of the time that
`forStartup` does not
+ * replace would, or the configuration of the optimizer changed in the
session of the query, or
+ * the optimizer of the micro-batch rewrote a pushed filter in a way that
`impliedBy` does not
+ * follow, and the micro-batch fails before it reads its data, with the
failure of the optimizer
+ * as its cause if there is one.
+ */
+ def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = {
+ val hasPushedFilters = plan.exists {
+ case relation: StreamingDataSourceV2ScanRelation =>
relation.pushedFilters.nonEmpty
+ case _ => false
+ }
+ if (hasPushedFilters) {
+ // The configuration of the micro-batch, without the rules that infer
filters, which would
+ // add conditions to those that `impliedBy` gets from the optimizer.
+ lazy val optimizerConf =
withoutInferredFilters(session.sessionState.conf.clone())
+ // The conjuncts of `condition` once the optimizer of the micro-batch
optimizes a filter of
+ // `relation` with it, none if it folds into true, which the next
micro-batches reuse.
+ def optimized(relation: StreamingDataSourceV2ScanRelation)(
+ condition: Expression): Option[Seq[Expression]] = {
+ val key = condition.canonicalized
+ Option(optimizedConditions.getIfPresent(key)).getOrElse {
+ val rewritten = SQLConf.withExistingConf(optimizerConf) {
+ session.sessionState.optimizer.execute(
+ Filter(condition, relation.copy(pushedFilters = Nil)))
+ } match {
+ case Filter(optimizedCondition, _:
StreamingDataSourceV2ScanRelation) =>
+ Some(splitConjunctivePredicates(optimizedCondition))
+ case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+ case _ => None
+ }
+ optimizedConditions.put(key, rewritten)
+ rewritten
+ }
+ }
+ conditionsOverRelations(plan, Nil).foreach { case (relation, conditions)
=>
+ val implied = impliedBy(conditions, optimized(relation))
+ val results = relation.pushedFilters.map(filter => filter ->
Try(implied(filter)))
+ val unapplied = results.collect {
+ case (filter, result) if !result.getOrElse(false) => filter
+ }
+ if (unapplied.nonEmpty) {
+ throw QueryExecutionErrors.streamingScanFiltersChangedError(
+ sourceName(relation.relation.table, relation.catalog,
relation.identifier),
+ unapplied.map(_.sql),
+ results.collectFirst { case (_, Failure(e)) => e }.orNull)
+ }
+ }
+ }
+ }
+
+ // The conditions that the optimizer of a micro-batch rewrote for
`checkPushedFilters`, by the
+ // condition canonicalized: the micro-batches of a query check the same
filters with the same
+ // values, which the optimizer rewrites in the same way.
+ private val optimizedConditions: Cache[Expression, Option[Seq[Expression]]] =
+ CacheBuilder.newBuilder().maximumSize(100).build[Expression,
Option[Seq[Expression]]]()
+
+ // Each occurrence of a streaming relation in `plan`, with the deterministic
conditions that the
+ // plan applies to all its rows, given `above`, those that it applies to all
the rows of `plan`:
+ // the conditions of the filters over it, through the projections, with the
aliases of these in
+ // place of their names, as `PhysicalOperation` finds the filters of a
relation. The conditions
+ // over a filter or a projection that is not deterministic do not hold for
the rows that it gets.
+ private def conditionsOverRelations(
+ plan: LogicalPlan,
+ above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation,
Seq[Expression])] = {
+ plan match {
+ case relation: StreamingDataSourceV2ScanRelation => Seq(relation ->
above)
+ case Filter(condition, child) =>
+ val conditions =
splitConjunctivePredicates(condition).filter(_.deterministic)
Review Comment:
Done in 92694a4: for a nondeterministic condition, the walk now keeps
`splitConjunctivePredicates(condition).takeWhile(_.deterministic)`, as
`readsOfSources` does when the query starts, and its comment says why. The test
of the check now rejects `Filter(rand(0) > 0.5 AND id > 1, relation)` and
accepts `Filter(id > 1 AND rand(0) > 0.5, relation)`, whose `rand(0)` only sees
the rows that `id > 1` keeps.
##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java:
##########
@@ -190,5 +190,37 @@ public enum TableCapability {
*
* @since 4.4.0
*/
- STREAMING_COLUMN_PRUNING
+ STREAMING_COLUMN_PRUNING,
+
+ /**
+ * Signals that the scans of the streaming reads of the table may get the
filters that the
+ * streaming query applies to all the rows that it reads from the table,
which Spark pushes to a
+ * scan builder that implements
+ * {@link org.apache.spark.sql.connector.read.SupportsPushDownFilters} or
+ * {@link org.apache.spark.sql.connector.read.SupportsPushDownV2Filters}, as
it does for the
+ * scans of batch reads: the filters that Spark plans with the scan, over
the relation of the
+ * read, up to the first nondeterministic one, so the filters after a
nondeterministic filter or
+ * projection, or above another operator, such as a filter on the event-time
column above its
+ * watermark, are not pushed. The filters of a {@code
SupportsPushDownFilters} builder compare
+ * columns with values, which cannot fail, so it gets such filters whatever
their order among
+ * the filters over the relation. A builder whose filters may fail on some
rows, as a cast does
+ * with ANSI, only gets the filters that the query applies before any other
filter, in their
+ * order, and the streams of its scans must not evaluate a filter on a row
that a filter before
+ * it drops, as Spark does not, so that each filter only sees the rows that
the query evaluates it
+ * on.
+ * <p>
+ * Spark builds the scan of a streaming read once, when the query starts,
from the plan of the
+ * query optimized then, and creates the micro-batch or continuous stream of
the read from that
+ * scan. By returning this capability, a table declares that its scan
builders can take filters
+ * for such a scan, as for the scan of a batch read. The stream may then
drop the rows that fail
Review Comment:
Done in 92694a4: the paragraph now says that the offsets of the stream,
including those of `latestOffset`, must still be positions in all the rows of
the table, as without filters. The filters are decided again each time the
query starts, so a query that restarts from the offsets of its checkpoint may
push other filters, or none.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +618,172 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
}
}
+ /**
+ * Checks that `plan`, the optimized plan of a micro-batch in `session`,
applies the filters that
+ * the scans of its sources got when the query started to all the rows that
it reads from them:
+ * a scan may drop the rows that fail its filters, so the plan must drop
them too. The conditions
+ * that the plan applies to all the rows of each occurrence of a relation
whose scan got filters
+ * must imply these filters (see `impliedBy`). Otherwise, the value of an
expression in a pushed
+ * filter changed after the query started, as a function of the time that
`forStartup` does not
+ * replace would, or the configuration of the optimizer changed in the
session of the query, or
+ * the optimizer of the micro-batch rewrote a pushed filter in a way that
`impliedBy` does not
+ * follow, and the micro-batch fails before it reads its data, with the
failure of the optimizer
+ * as its cause if there is one.
+ */
+ def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = {
+ val hasPushedFilters = plan.exists {
+ case relation: StreamingDataSourceV2ScanRelation =>
relation.pushedFilters.nonEmpty
+ case _ => false
+ }
+ if (hasPushedFilters) {
+ // The configuration of the micro-batch, without the rules that infer
filters, which would
+ // add conditions to those that `impliedBy` gets from the optimizer.
+ lazy val optimizerConf =
withoutInferredFilters(session.sessionState.conf.clone())
+ // The conjuncts of `condition` once the optimizer of the micro-batch
optimizes a filter of
+ // `relation` with it, none if it folds into true, which the next
micro-batches reuse.
+ def optimized(relation: StreamingDataSourceV2ScanRelation)(
+ condition: Expression): Option[Seq[Expression]] = {
+ val key = condition.canonicalized
+ Option(optimizedConditions.getIfPresent(key)).getOrElse {
+ val rewritten = SQLConf.withExistingConf(optimizerConf) {
+ session.sessionState.optimizer.execute(
+ Filter(condition, relation.copy(pushedFilters = Nil)))
+ } match {
+ case Filter(optimizedCondition, _:
StreamingDataSourceV2ScanRelation) =>
+ Some(splitConjunctivePredicates(optimizedCondition))
+ case _: StreamingDataSourceV2ScanRelation => Some(Nil)
+ case _ => None
+ }
+ optimizedConditions.put(key, rewritten)
+ rewritten
+ }
+ }
+ conditionsOverRelations(plan, Nil).foreach { case (relation, conditions)
=>
+ val implied = impliedBy(conditions, optimized(relation))
+ val results = relation.pushedFilters.map(filter => filter ->
Try(implied(filter)))
+ val unapplied = results.collect {
+ case (filter, result) if !result.getOrElse(false) => filter
+ }
+ if (unapplied.nonEmpty) {
+ throw QueryExecutionErrors.streamingScanFiltersChangedError(
+ sourceName(relation.relation.table, relation.catalog,
relation.identifier),
+ unapplied.map(_.sql),
+ results.collectFirst { case (_, Failure(e)) => e }.orNull)
+ }
+ }
+ }
+ }
+
+ // The conditions that the optimizer of a micro-batch rewrote for
`checkPushedFilters`, by the
+ // condition canonicalized: the micro-batches of a query check the same
filters with the same
+ // values, which the optimizer rewrites in the same way.
+ private val optimizedConditions: Cache[Expression, Option[Seq[Expression]]] =
Review Comment:
Done in 92694a4, the first way: the cache is now a
`StreamingV2ScanPushDown.PushedFilterRewrites` with at most 100 entries.
`MicroBatchExecution` and `ContinuousExecution` create one for each run of a
query and pass it to each `IncrementalExecution`.
So the entries go away with the query, queries don't share them, and a query
that restarts gets a new cache with the configuration it restarts with. A
rewrite, or a `None`, from an earlier configuration can't fail it again.
The test of the unwrapped cast now also restarts the query and checks that
the restarted one rewrites the filter again.
--
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]