dongjoon-hyun commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4503975235
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +621,219 @@ 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 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]] =
rewrites(condition) {
+ 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
+ }
+ }
+ 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, 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. 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]]]()
+
+ def apply(condition: Expression)(
+ rewrite: => Option[Seq[Expression]]): Option[Seq[Expression]] = {
+ val key = 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.
+ 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)
+ 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'`. A struct or an
array with floating
+ * fields or elements gets its value if it has no 0.0 or -0.0 in them. A
string of a collation
+ * that is not binary gets no value, also where `ConstantPropagation` puts
it in a comparison of
+ * two columns of this collation. 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) =>
+ DataType.equalsIgnoreNullability(column.dataType, value.dataType) &&
+ (hasExactEquality(column.dataType) || isFloating(column.dataType) ||
+ (hasExactEquality(column.dataType, floating = true) &&
+ hasNoFloatingZero(value.value, value.dataType)))
+ })
+ filter => noRow || holds(filter) || {
+ val columns = filter.references.filter(values.contains)
+ // The columns of the filter that are equal to zero, which is 0.0 or
-0.0 in each row.
+ val zeros = columns.toSeq.filter(column =>
isFloatingZero(values(column))).toSet
+ val zeroColumns = AttributeSet(zeros)
+ columns.nonEmpty && zeros.size <= 3 && zeros.subsets().forall { negative
=>
+ val negativeZeros = AttributeSet(negative)
+ val withValues = filter.transform {
Review Comment:
**Following up on items 45 and 53
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499818880)):
since f104507 merged SPARK-60983 into this branch, `ConstantPropagation` keeps
the columns of a sub-expression that can fail, while `withValues` still
replaces them everywhere, so the check can fail micro-batches whose plans apply
the pushed filters.** `replaceConstants` (expressions.scala:241-243) keeps the
columns of such a sub-expression unless all of them get values and it folds
without an error, while `withValues` puts the values in place of every
occurrence of a column, as `ConstantPropagation` did when those items were
written. The check then looks for a form that the micro-batch does not have, or
throws in its own run of the optimizer. For example, with ANSI and a V2 or
Catalyst builder:
- `where("(a + b > 3 AND b > 0) OR a > 9")` joined on `b = x` with
`static.where("x = 1")`: the micro-batch keeps `(a + b > 3) OR (a > 9)`, since
`a` has no value in `a + b`, while the check looks for `(a + 1 > 3) OR (a >
9)`, so every micro-batch with data fails with `STREAMING_SCAN_FILTERS_CHANGED`.
- `where("10 / id > 1 OR id < 1")` joined on `id = k` with `k = 0`: the
micro-batch keeps `10 / id` and folds the `Or` into true, while
`ConstantFolding` evaluates the `10 / 0 > 1 OR 0 < 1` of the check and throws
`DIVIDE_BY_ZERO`, so the first micro-batch fails with it as the cause, even if
no row has `id = 0`.
Both queries succeed without the pushdown, and both still fail after a
rebase on master with SPARK-61033. Could `impliedBy` leave the values to the
optimizer, e.g. optimize `Filter(And(equalities :+ filter), relation)` with the
equalities of the facts, and check that each conjunct that it returns holds?
The explicit 0.0 and -0.0 cases would still be needed for the floating columns,
since `ConstantPropagation` also puts 0.0 into `CAST(d AS STRING) = '0.0'`.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +621,219 @@ 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 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]] =
rewrites(condition) {
+ 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
+ }
+ }
+ 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, 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. 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]]]()
+
+ def apply(condition: Expression)(
+ rewrite: => Option[Seq[Expression]]): Option[Seq[Expression]] = {
+ val key = condition.canonicalized
Review Comment:
Minor: following up on items 45
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395300))
and 54
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499818888)):
this key is new in every micro-batch when a value of the facts comes from
`current_time()`, so the example of item 45, `t > TIME'00:00:01' AND t =
current_time()`, still runs the optimizer in every micro-batch.
MicroBatchExecution.scala:1325-1349 turns `CurrentTimestamp`, `LocalTimestamp`
and `CurrentDate` into `CurrentBatchTimestamp`, but not `CurrentTime`, so
`ComputeCurrentTime` folds it into the time of each micro-batch, and
`TIME'<now>' > TIME'00:00:01'` is a new key each time. Each micro-batch then
clones the configuration, runs the optimizer with its extensions, logs the
three INFO lines of item 54, and adds an entry that is never read again, up to
100, unlike what the Scaladoc at L680-682 says. Could `impliedBy` first try
`holds` on the filter with the values, and evaluate a filte
r whose columns all got values directly, using the optimizer only when that
throws?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -1094,45 +1906,326 @@ class StreamingV2ScanPushDownSuite extends StreamTest
with BeforeAndAfter {
}
}
}
+
+ test("canonicalize and show the pushed filters of a streaming scan
relation") {
+ withSourceTable() {
+ testStream(spark.readStream.table(tbl).where("extra >
10").select("data"))(
+ ProcessAllAvailable(),
+ AssertOnQuery { query =>
+ val relation = query.logicalPlan.collectFirst {
+ case relation: StreamingDataSourceV2ScanRelation => relation
+ }.get
+ assert(relation.pushedFilters.nonEmpty)
+ // A copy of the relation has new attributes, also in its pushed
filters, and the same
+ // result.
+ val copy =
relation.newInstance().asInstanceOf[StreamingDataSourceV2ScanRelation]
+ assert(copy.pushedFilters.flatMap(_.references).map(_.exprId).toSet
+ .intersect(relation.output.map(_.exprId).toSet).isEmpty)
+ assert(copy.sameResult(relation))
+ // The relation shows the filters that its scan builder was given.
+ val string = relation.simpleString(100)
+ assert(string.contains("FiltersOfScanBuilder: [") &&
string.contains(" > 10)]"), string)
+ true
+ },
+ CheckAnswer(Row("b")))
+ }
+ }
+
+ // The confs with which the optimizer of a micro-batch prunes the filters
that the constraints of
+ // their children imply, or does not.
+ private val withoutPruneFilters = Seq(
+ Map.empty[String, String],
+ Map(SQLConf.CONSTRAINT_PROPAGATION_ENABLED.key -> "false"),
+ Map(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> PruneFilters.ruleName))
+
+ test("evaluate a pushed filter once above a projection of a value of each
micro-batch") {
+ withSourceTable() {
+ // The query outputs the value, so that the optimizer keeps its
projection.
+ val df = spark.readStream.table(tbl).withColumn("pt",
current_timestamp())
+ .where("extra > 10").select("data", "pt")
+ // Each micro-batch has the value of the projection once it is
optimized, so it applies the
+ // filter above the projection, once, and its check finds the filter
there, whether the
+ // optimizer prunes filters or not.
+ withoutPruneFilters.foreach { confs =>
+ withSQLConf(confs.toSeq: _*) {
+ assert(pushed(df) === Seq(Set("extra")), confs)
+ testStream(df)(
+ ProcessAllAvailable(),
+ assertPushedFilters("GreaterThan(extra,10)"),
+ assertEvaluatedOnce("extra"))
+ }
+ }
+ }
+ }
+
+ test("evaluate a pushed filter once after a separate filter that is not
pushed down") {
+ withTable(tbl) {
+ createTable(tbl, "id bigint, data string, ts timestamp, extra int")
+ sql(s"INSERT INTO $tbl VALUES " +
+ "(1, 'a', timestamp_seconds(0), 10), (2, 'b', timestamp_seconds(0),
20)")
+ // The filters cannot be combined when the query starts, as the first
one has a value of
+ // each micro-batch. The V1 builder of the in-memory tables gets the
second one, which each
+ // micro-batch applies above the first one.
+ val df = spark.readStream.table(tbl).where("ts <
current_timestamp()").where("extra > 10")
+ .select("data")
+ withoutPruneFilters.foreach { confs =>
+ withSQLConf(confs.toSeq: _*) {
+ testStream(df)(
+ ProcessAllAvailable(),
+ assertPushedFilters("GreaterThan(extra,10)"),
+ assertEvaluatedOnce("extra"),
+ CheckAnswer(Row("b")))
+ }
+ }
+ }
+ }
+
+ Seq(
+ // Two filters above the projection, which the micro-batch combines.
+ "two filters" -> ((df: DataFrame) =>
+ df.withColumn("pt", current_timestamp()).where("extra > 10").where("data
= 'b'")
+ .select("data", "pt"), Seq(Seq("extra"), Seq("data"))),
+ // A filter that the optimizer rewrites, as id > CAST(1 AS BIGINT), whose
pushed filter is
+ // optimized too.
+ "a rewritten filter" -> ((df: DataFrame) =>
+ df.withColumn("pt", current_timestamp()).where("id > 1").select("data",
"pt"),
+ Seq(Seq("id"))),
+ // A filter on an alias of the column of the pushed filter.
+ "a filter on an alias" -> ((df: DataFrame) =>
+ df.select(col("data"), col("extra").as("e"),
current_timestamp().as("pt"))
+ .where("e > 10").select("data", "pt"), Seq(Seq("e", "extra"))),
+ // A filter above a watermark, which keeps the rows and the columns of its
child.
+ "a filter above a watermark" -> ((df: DataFrame) =>
+ df.withColumn("pt", current_timestamp()).withWatermark("pt", "10
seconds")
+ .where("extra > 10").select("data"), Seq(Seq("extra")))
+ ).foreach { case (name, (query, columns)) =>
+ test(s"evaluate the pushed filters once with $name above a projection of a
value of each " +
+ "micro-batch") {
+ withSourceTable() {
+ val df = query(spark.readStream.table(tbl))
+ withoutPruneFilters.foreach { confs =>
+ withSQLConf(confs.toSeq: _*) {
+ testStream(df)(
+ ProcessAllAvailable() +:
+ columns.map(names => assertEvaluatedOnce(names: _*)): _*)
Review Comment:
Minor: following up on items 2, 16 and 20
([thread](https://github.com/apache/spark/pull/60129#discussion_r4483802577)):
these four tests, 12 runs over `withoutPruneFilters`, only check
`assertEvaluatedOnce`, which no code path of the PR can fail since 7b39a35
stopped adding copies of the pushed filters. They check neither the pushdown
nor the answer, so they pass even when nothing is pushed: a regression that
stops the pushdown of the two filters, the rewritten filter, the alias or the
watermark, e.g. in `forStartup`, `isPushable` or `getsFilter`, leaves the
single filter of the query in place, and `checkPushedFilters` returns at
`hasPushedFilters`. Could each case also assert its pushed filters with
`assertPushedFilters`, as the test at L1975 does, keeping the tests and the
confs that items 2, 16 and 20 asked for? Nit: the Scaladoc of
`assertEvaluatedOnce` (L143) says "the filters on `column`", while its
parameter is `columns`.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +383,201 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
/**
* Builds the scan of a streaming source, and creates its stream with
`createStream`. If the
- * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its
scan builder supports
- * the pushdown, and `conf` enables it, the scan only reads the columns of
`output` that the query
- * reads (see `requiredColumnsOfSources`). `requiredColumns` is only
evaluated for such a scan.
- * Otherwise, the scan reads all the columns of `output`, as the scans of
streaming queries did
- * before this pushdown.
+ * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+ * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and
`conf` enables it,
+ * the scan only reads the columns of `output` that the query reads, or gets
the filters that the
+ * query applies to all the rows that it reads from the source (see
`columnsAndFiltersOfSources`).
+ * `reads` is only evaluated for such a scan. Otherwise, the scan reads all
the columns of
+ * `output` with no filter, as the scans of streaming queries did before
these pushdowns.
*
- * The streams of the scans of a table with the capability return the
columns of the read
- * schemas of the scans, in their order, so Spark asks each scan of such a
table for its read
+ * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING`
return the columns of the
+ * read schemas of the scans, in their order, so Spark asks each scan of
such a table for its read
* schema before it creates the stream, whether the scan reads all the
columns or not. A pruned
* scan must read the required columns and only columns of `output`, each
once and with its
* type, as `SupportsPushDownRequiredColumns` requires. If the scan builder
or the scan fails
- * with the pruning, or the read schema of a pruned scan cannot be read or
does not follow
- * `SupportsPushDownRequiredColumns`, a scan of all the columns is built
instead, from a new scan
- * builder, as without this pushdown. If the read schema of a scan of all
the columns of such a
- * table does not follow the relation, the query fails with
STREAMING_SCAN_INVALID_READ_SCHEMA,
- * unless `conf` disables the column pruning, with which the scan node
outputs the columns of
- * the relation, as it did before the capability.
+ * with the pushdowns, or the read schema of a pruned scan cannot be read or
does not follow
+ * `SupportsPushDownRequiredColumns`, the scan is built again from a new
scan builder: with the
+ * column pruning alone and then with the filters alone if it had both, and
then with all the
+ * columns and no filter, as without these pushdowns. If the read schema of
a scan of all the
+ * columns of such a table, with or without filters, does not follow the
relation, the query
+ * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the
column pruning, with
+ * which the scan node outputs the columns of the relation, as it did before
the capability.
*
* The stream is created once, from the scan that the source reads, outside
of the fallback: a
* stream can start to use the checkpoint of the source, or other resources,
before it fails, so
- * a failure of `createStream` fails the query, as it did without this
pushdown.
+ * a failure of `createStream` fails the query, as it did without these
pushdowns.
*
* @param output the output of the relation of the source, with the metadata
columns that the
* query reads, which the analyzer added to it, so that
connectors implementing
* `SupportsMetadataColumns` include them in `readSchema()`
* @param conf the configuration of the query
- * @param requiredColumns the columns that the query reads from the
relation, or None to read
- * all its columns
+ * @param reads what the query reads from the relation, or None to read all
its columns with no
+ * filter
* @param source the name of the source in the errors of its scan, see
`sourceName`
*/
def buildScan(
table: SupportsRead,
options: CaseInsensitiveStringMap,
output: Seq[AttributeReference],
conf: SQLConf,
- requiredColumns: => Option[AttributeSet],
+ reads: => Option[Reads],
source: Seq[String])(
createStream: Scan => SparkDataStream): StreamingScan = {
- val returnsReadSchema =
table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+ val capabilities = table.capabilities()
+ val returnsReadSchema =
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
val builder = table.newScanBuilder(options)
val prunesColumns = returnsReadSchema &&
conf.streamingV2ColumnPruningEnabled &&
builder.isInstanceOf[SupportsPushDownRequiredColumns]
- val requiredOutput = (if (prunesColumns) requiredColumns else None)
- .map(columns => output.filter(columns.contains))
+ val pushesFilters = conf.streamingV2FilterPushdownEnabled &&
+ capabilities.contains(TableCapability.STREAMING_FILTER_PUSHDOWN) &&
+ PushDownUtils.supportsFilters(builder)
+ val known = if (prunesColumns || pushesFilters) reads else None
+ val requiredOutput = known.filter(_ => prunesColumns)
+ .map(r => output.filter(r.requiredColumns.contains))
.getOrElse(output)
+ // The filters that the scan builder gets in some form, which each
micro-batch applies first:
Review Comment:
Minor: this comment, and the one at
StreamingV2ScanPushDownSuite.scala:1003-1006, still describe the removed
`withPushedFilters`, under which each micro-batch applied the pushed filters
first. Since 7b39a35 nothing is added to the plans of the micro-batches, and
the Javadoc of 8ed500a says that Spark may evaluate other conditions first. For
a V1 builder, `where("data <> current_user() AND extra > 10")` pushes `extra >
10`, which the micro-batch evaluates after `data <> current_user()`, so a
reader may take the order of the micro-batch for what keeps the leading filters
safe. The name of the test at StreamingV2ScanPushDownSuite.scala:997, "push
down no filter after a filter that is not pushed down", also disagrees with its
V1 case, which pushes `id > 0` (L1011-1015 there). Could both comments say that
the streams may apply the pushed filters first, to the rows of the source, as
the Scaladoc of `Reads.filters` (L94-97) does?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryExecutionErrors.scala:
##########
@@ -2527,6 +2527,19 @@ private[sql] object QueryExecutionErrors extends
QueryErrorsBase with ExecutionE
cause = null)
}
+ def streamingScanFiltersChangedError(
+ source: Seq[String],
+ filters: Seq[String],
+ cause: Throwable = null): Throwable = {
+ new SparkException(
+ errorClass = "STREAMING_SCAN_FILTERS_CHANGED",
+ messageParameters = Map(
+ "filters" -> filters.mkString(", "),
Review Comment:
Minor: this takes the filters already rendered with `.sql`
(StreamingV2ScanPushDown.scala:671) and joins them unquoted, while rule 7 of
`QueryErrorsBase` asks for SQL expressions in double quotes, through
`toSQLExpr`, and the other parameters here use `toSQLId` and `toSQLConf`. The
message shows `(testcat.t.extra < 1)`
(StreamingV2ScanPushDownSuite.scala:1445): qualified, unquoted, and repeating
the source, and with several function calls among the filters, the list is
ambiguous at its commas. Could it take `filters: Seq[Expression]` and render
`filters.map(toSQLExpr).mkString(", ")`, with the test expecting `"(extra <
1)"`?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +383,201 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
/**
* Builds the scan of a streaming source, and creates its stream with
`createStream`. If the
- * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its
scan builder supports
- * the pushdown, and `conf` enables it, the scan only reads the columns of
`output` that the query
- * reads (see `requiredColumnsOfSources`). `requiredColumns` is only
evaluated for such a scan.
- * Otherwise, the scan reads all the columns of `output`, as the scans of
streaming queries did
- * before this pushdown.
+ * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+ * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and
`conf` enables it,
+ * the scan only reads the columns of `output` that the query reads, or gets
the filters that the
+ * query applies to all the rows that it reads from the source (see
`columnsAndFiltersOfSources`).
+ * `reads` is only evaluated for such a scan. Otherwise, the scan reads all
the columns of
+ * `output` with no filter, as the scans of streaming queries did before
these pushdowns.
*
- * The streams of the scans of a table with the capability return the
columns of the read
- * schemas of the scans, in their order, so Spark asks each scan of such a
table for its read
+ * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING`
return the columns of the
+ * read schemas of the scans, in their order, so Spark asks each scan of
such a table for its read
* schema before it creates the stream, whether the scan reads all the
columns or not. A pruned
* scan must read the required columns and only columns of `output`, each
once and with its
* type, as `SupportsPushDownRequiredColumns` requires. If the scan builder
or the scan fails
- * with the pruning, or the read schema of a pruned scan cannot be read or
does not follow
- * `SupportsPushDownRequiredColumns`, a scan of all the columns is built
instead, from a new scan
- * builder, as without this pushdown. If the read schema of a scan of all
the columns of such a
- * table does not follow the relation, the query fails with
STREAMING_SCAN_INVALID_READ_SCHEMA,
- * unless `conf` disables the column pruning, with which the scan node
outputs the columns of
- * the relation, as it did before the capability.
+ * with the pushdowns, or the read schema of a pruned scan cannot be read or
does not follow
+ * `SupportsPushDownRequiredColumns`, the scan is built again from a new
scan builder: with the
+ * column pruning alone and then with the filters alone if it had both, and
then with all the
+ * columns and no filter, as without these pushdowns. If the read schema of
a scan of all the
+ * columns of such a table, with or without filters, does not follow the
relation, the query
+ * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the
column pruning, with
+ * which the scan node outputs the columns of the relation, as it did before
the capability.
*
* The stream is created once, from the scan that the source reads, outside
of the fallback: a
* stream can start to use the checkpoint of the source, or other resources,
before it fails, so
- * a failure of `createStream` fails the query, as it did without this
pushdown.
+ * a failure of `createStream` fails the query, as it did without these
pushdowns.
*
* @param output the output of the relation of the source, with the metadata
columns that the
* query reads, which the analyzer added to it, so that
connectors implementing
* `SupportsMetadataColumns` include them in `readSchema()`
* @param conf the configuration of the query
- * @param requiredColumns the columns that the query reads from the
relation, or None to read
- * all its columns
+ * @param reads what the query reads from the relation, or None to read all
its columns with no
+ * filter
* @param source the name of the source in the errors of its scan, see
`sourceName`
*/
def buildScan(
table: SupportsRead,
options: CaseInsensitiveStringMap,
output: Seq[AttributeReference],
conf: SQLConf,
- requiredColumns: => Option[AttributeSet],
+ reads: => Option[Reads],
source: Seq[String])(
createStream: Scan => SparkDataStream): StreamingScan = {
- val returnsReadSchema =
table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+ val capabilities = table.capabilities()
+ val returnsReadSchema =
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
val builder = table.newScanBuilder(options)
val prunesColumns = returnsReadSchema &&
conf.streamingV2ColumnPruningEnabled &&
builder.isInstanceOf[SupportsPushDownRequiredColumns]
- val requiredOutput = (if (prunesColumns) requiredColumns else None)
- .map(columns => output.filter(columns.contains))
+ val pushesFilters = conf.streamingV2FilterPushdownEnabled &&
+ capabilities.contains(TableCapability.STREAMING_FILTER_PUSHDOWN) &&
+ PushDownUtils.supportsFilters(builder)
+ val known = if (prunesColumns || pushesFilters) reads else None
+ val requiredOutput = known.filter(_ => prunesColumns)
+ .map(r => output.filter(r.requiredColumns.contains))
.getOrElse(output)
+ // The filters that the scan builder gets in some form, which each
micro-batch applies first:
+ // the others, such as a filter with a UDF that cannot be translated to a
filter of the source,
+ // are evaluated after them, as for the scans of batch queries, rather
than on all the rows of
+ // the source. The filters of a `SupportsPushDownFilters` builder compare
columns with values,
+ // which cannot fail, so it gets those that all the reads apply, wherever
they are. The
+ // predicates of a `SupportsPushDownV2Filters` builder and the filters of
the others may fail
+ // on some rows, as a cast does with ANSI, so they are the leading filters
of the reads, up to
+ // the first that the builder does not get, in their order, which the
streams evaluate them in
+ // (see `TableCapability.STREAMING_FILTER_PUSHDOWN`): none runs before a
filter written before
+ // it. `PushDownUtils.pushFilters` decides which filters the builder gets
in the same way.
+ def gets(filter: Expression): Boolean = PushDownUtils.getsFilter(builder,
filter)
+ val filters = known.filter(_ => pushesFilters)
+ .map { r =>
+ builder match {
+ case _: SupportsPushDownFilters =>
+ DataSourceStrategy.normalizeExprs(r.filtersInAnyOrder,
output).filter(gets)
+ case _ =>
+ DataSourceStrategy.normalizeExprs(r.filters,
output).takeWhile(gets)
+ }
+ }
+ .getOrElse(Nil)
- // Builds the scan of `columns` with `builder`.
- def build(builder: ScanBuilder, columns: Seq[AttributeReference]): Scan = {
+ // Builds the scan of `columns` with `builder`, once it pushed `filters`
down to it.
+ def build(
+ builder: ScanBuilder,
+ columns: Seq[AttributeReference],
+ filters: Seq[Expression]): Scan = {
+ if (filters.nonEmpty) {
+ // Each micro-batch checks that its plan applies these filters to all
the rows that it
+ // reads from the source, see `checkPushedFilters`, so the scan may
apply any of them, in
+ // any form.
+ val (pushed, _) = PushDownUtils.pushFilters(builder, filters,
partitionFields = None)
+ val taken = pushed.fold(_.mkString(", "), _.mkString(", "))
+ logInfo(log"The scan builder of the streaming table " +
+ log"${MDC(LogKeys.STREAMING_TABLE, table)} took the filters " +
+ log"${MDC(LogKeys.PUSHED_FILTERS, taken)}.")
+ }
builder match {
case pruning: SupportsPushDownRequiredColumns =>
pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
case _ =>
}
builder.build()
}
- // The scan of all the columns, as without this pushdown, and the columns
that its scan node
- // outputs.
- def scanOfAllColumns(builder: ScanBuilder): (Scan,
Seq[AttributeReference]) = {
- val scan = build(builder, output)
+ // The columns that the scan node of `scan`, a scan of all the columns,
outputs.
+ def outputOfAllColumns(scan: Scan): Seq[AttributeReference] = {
if (returnsReadSchema) {
// The readers of the stream return the columns of the read schema, so
a read schema that
// does not follow the relation fails the query when it starts: the
scan node cannot
// output the columns of the relation in its place. Without the column
pruning, the scan
// node outputs them instead, as it did before the capability.
- def invalid(reason: String, cause: Throwable): (Scan,
Seq[AttributeReference]) = {
+ def invalid(reason: String, cause: Throwable): Seq[AttributeReference]
= {
if (conf.streamingV2ColumnPruningEnabled) {
throw
QueryExecutionErrors.streamingScanInvalidReadSchemaError(source, reason, cause)
}
logWarning(log"The read schema of the scan of all the columns of the
streaming table " +
log"${MDC(LogKeys.STREAMING_TABLE, table)} ${MDC(LogKeys.REASON,
reason)}. Its scan " +
log"node outputs the columns of the relation, as the column
pruning is disabled.")
- scan -> output
+ output
}
Try(readOutput(scan.readSchema(), output, output)) match {
- case Success(Right(columns)) => scan -> columns
+ case Success(Right(columns)) => columns
case Success(Left(reason)) => invalid(reason, null)
case Failure(e) => invalid(s"could not be read: $e", e)
}
} else {
- scan -> output
+ output
}
}
-
- val (scan, scanOutput) = if (requiredOutput.length == output.length) {
- scanOfAllColumns(builder)
- } else {
- // Logs why the pruned scan could not be built, and builds the scan of
all the columns
- // instead.
- def fallBack(reason: String, cause: Option[Throwable]): (Scan,
Seq[AttributeReference]) = {
- val message = log"The scan of the streaming table " +
- log"${MDC(LogKeys.STREAMING_TABLE, table)} could not be built to
read only the columns " +
- log"${MDC(LogKeys.COLUMN_NAMES,
requiredOutput.map(_.name).mkString(", "))}: " +
- log"${MDC(LogKeys.REASON, reason)}. It reads all the columns
instead."
- cause match {
- case Some(e) => logWarning(message, e)
- case None => logWarning(message)
- }
- scanOfAllColumns(table.newScanBuilder(options))
+ // The scan of all the columns with no filter, as without these pushdowns,
and the columns that
+ // its scan node outputs.
+ def scanOfAllColumns(builder: ScanBuilder): (Scan,
Seq[AttributeReference]) = {
+ val scan = build(builder, output, Nil)
+ scan -> outputOfAllColumns(scan)
+ }
+ // The scan of `columns` with `filters` and the columns that its scan node
outputs, or why its
+ // read schema does not follow `SupportsPushDownRequiredColumns`. A scan
of all the columns
+ // with filters is checked as one with no filter, outside of the fallback
(see `firstScan`), as
+ // its read schema fails the query in the same way: the columns of such a
scan are None.
+ def scanWith(
+ builder: ScanBuilder,
+ columns: Seq[AttributeReference],
+ filters: Seq[Expression]): Either[String, (Scan,
Option[Seq[AttributeReference]])] = {
+ val scan = build(builder, columns, filters)
+ if (!returnsReadSchema) {
Review Comment:
Nit: this branch is covered by the next one. Without
`STREAMING_COLUMN_PRUNING`, `prunesColumns` is false (L429-430), so every
attempt has all the columns, and `outputOfAllColumns` returns `output` without
calling `readSchema()` (L503-505), so without L522-523 the scans, their outputs
and the logs stay the same. Likewise, in `values` (L766-769), with t for
`column.dataType` and v for its value, `hasExactEquality(t) || isFloating(t) ||
(hasExactEquality(t, floating = true) && hasNoFloatingZero(v, t))` is
`hasExactEquality(t, floating = true) && (isFloating(t) || hasNoFloatingZero(v,
t))`, so `hasExactEquality` could always accept the floating types, with a doc
that says so, and lose its `floating` parameter. Could these be simplified?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -449,6 +621,219 @@ 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 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]] =
rewrites(condition) {
+ 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
+ }
+ }
+ 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, 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. 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]]]()
+
+ def apply(condition: Expression)(
+ rewrite: => Option[Seq[Expression]]): Option[Seq[Expression]] = {
+ val key = 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.
+ 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)
=>
Review Comment:
Minor: this inlines the aliases of every deterministic projection, also of
those that `CollapseProject` and `PhysicalOperation` keep apart because an
expensive alias, such as a UDF, is used more than once. With a chain of such
projections, each using the alias below it twice, the conditions double at each
level, and the check builds and canonicalizes them again in every micro-batch.
For example, `where("x > 0").select(f1($"x").as("a1")).select(f2($"a1",
$"a1").as("a2"))` and so on for k UDF projections, then `.where("z > 0")`:
`PushPredicateThroughNonJoin` keeps `z > 0` above them
(Optimizer.scala:2673-2695), and `replaceAlias` copies the body of each alias
at each level, so the conditions over the relation hold about 2^k copies of
`f1(x)`, millions at k = 20, although the scan got no filter from above these
projections. Could each conjunct go down through a projection only while
`CollapseProject.canCollapseExpressions(Seq(conjunct), aliases)` holds for it?
It needs to be per conj
unct, as a condition that a micro-batch infers next to a pushed one may use
the same alias.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -21,67 +21,125 @@ 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
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, Generator, Literal, 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.{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}
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,
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,
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) => l.semanticEquals(r)
}.map(_._1)
Review Comment:
**`semanticEquals` finds `x IN (0.0, 1.0)` and `x IN (-0.0, 1.0)` equal,
while the check looks the pushed filters up in an `ExpressionSet` (L753-754),
where the two zeros hash differently, so an occurrence can get a filter that
its own conditions never match.** `Literal.equals` compares 0.0 and -0.0 as
equal, while their hash codes differ. For example, with a V2 or Catalyst
builder, `val s = spark.readStream.table(t)` and `s.where($"x".isin(0.0,
1.0)).union(s.where($"x".isin(-0.0, 1.0)))` push `x IN (0.0, 1.0)`, the filter
of the first occurrence. The second occurrence has `x IN (-0.0, 1.0)`, which
`known` does not match with it, and no column has a value, so every micro-batch
with data fails with `STREAMING_SCAN_FILTERS_CHANGED`, while the query succeeds
without the pushdown. No row is lost, as the check stays sound. Could this
compare the filters as the check does, e.g. with `l.semanticEquals(r) &&
l.semanticHash() == r.semanticHash()`, or with an `ExpressionSet` as
`filtersInAn
yOrder` does at L114?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +383,201 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
/**
* Builds the scan of a streaming source, and creates its stream with
`createStream`. If the
- * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its
scan builder supports
- * the pushdown, and `conf` enables it, the scan only reads the columns of
`output` that the query
- * reads (see `requiredColumnsOfSources`). `requiredColumns` is only
evaluated for such a scan.
- * Otherwise, the scan reads all the columns of `output`, as the scans of
streaming queries did
- * before this pushdown.
+ * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+ * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and
`conf` enables it,
+ * the scan only reads the columns of `output` that the query reads, or gets
the filters that the
+ * query applies to all the rows that it reads from the source (see
`columnsAndFiltersOfSources`).
+ * `reads` is only evaluated for such a scan. Otherwise, the scan reads all
the columns of
+ * `output` with no filter, as the scans of streaming queries did before
these pushdowns.
*
- * The streams of the scans of a table with the capability return the
columns of the read
- * schemas of the scans, in their order, so Spark asks each scan of such a
table for its read
+ * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING`
return the columns of the
+ * read schemas of the scans, in their order, so Spark asks each scan of
such a table for its read
* schema before it creates the stream, whether the scan reads all the
columns or not. A pruned
* scan must read the required columns and only columns of `output`, each
once and with its
* type, as `SupportsPushDownRequiredColumns` requires. If the scan builder
or the scan fails
- * with the pruning, or the read schema of a pruned scan cannot be read or
does not follow
- * `SupportsPushDownRequiredColumns`, a scan of all the columns is built
instead, from a new scan
- * builder, as without this pushdown. If the read schema of a scan of all
the columns of such a
- * table does not follow the relation, the query fails with
STREAMING_SCAN_INVALID_READ_SCHEMA,
- * unless `conf` disables the column pruning, with which the scan node
outputs the columns of
- * the relation, as it did before the capability.
+ * with the pushdowns, or the read schema of a pruned scan cannot be read or
does not follow
+ * `SupportsPushDownRequiredColumns`, the scan is built again from a new
scan builder: with the
+ * column pruning alone and then with the filters alone if it had both, and
then with all the
+ * columns and no filter, as without these pushdowns. If the read schema of
a scan of all the
+ * columns of such a table, with or without filters, does not follow the
relation, the query
+ * fails with STREAMING_SCAN_INVALID_READ_SCHEMA, unless `conf` disables the
column pruning, with
+ * which the scan node outputs the columns of the relation, as it did before
the capability.
*
* The stream is created once, from the scan that the source reads, outside
of the fallback: a
* stream can start to use the checkpoint of the source, or other resources,
before it fails, so
- * a failure of `createStream` fails the query, as it did without this
pushdown.
+ * a failure of `createStream` fails the query, as it did without these
pushdowns.
*
* @param output the output of the relation of the source, with the metadata
columns that the
* query reads, which the analyzer added to it, so that
connectors implementing
* `SupportsMetadataColumns` include them in `readSchema()`
* @param conf the configuration of the query
- * @param requiredColumns the columns that the query reads from the
relation, or None to read
- * all its columns
+ * @param reads what the query reads from the relation, or None to read all
its columns with no
+ * filter
* @param source the name of the source in the errors of its scan, see
`sourceName`
*/
def buildScan(
table: SupportsRead,
options: CaseInsensitiveStringMap,
output: Seq[AttributeReference],
conf: SQLConf,
- requiredColumns: => Option[AttributeSet],
+ reads: => Option[Reads],
source: Seq[String])(
createStream: Scan => SparkDataStream): StreamingScan = {
- val returnsReadSchema =
table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+ val capabilities = table.capabilities()
+ val returnsReadSchema =
capabilities.contains(TableCapability.STREAMING_COLUMN_PRUNING)
val builder = table.newScanBuilder(options)
val prunesColumns = returnsReadSchema &&
conf.streamingV2ColumnPruningEnabled &&
builder.isInstanceOf[SupportsPushDownRequiredColumns]
- val requiredOutput = (if (prunesColumns) requiredColumns else None)
- .map(columns => output.filter(columns.contains))
+ val pushesFilters = conf.streamingV2FilterPushdownEnabled &&
+ capabilities.contains(TableCapability.STREAMING_FILTER_PUSHDOWN) &&
+ PushDownUtils.supportsFilters(builder)
+ val known = if (prunesColumns || pushesFilters) reads else None
+ val requiredOutput = known.filter(_ => prunesColumns)
+ .map(r => output.filter(r.requiredColumns.contains))
.getOrElse(output)
+ // The filters that the scan builder gets in some form, which each
micro-batch applies first:
+ // the others, such as a filter with a UDF that cannot be translated to a
filter of the source,
+ // are evaluated after them, as for the scans of batch queries, rather
than on all the rows of
+ // the source. The filters of a `SupportsPushDownFilters` builder compare
columns with values,
+ // which cannot fail, so it gets those that all the reads apply, wherever
they are. The
+ // predicates of a `SupportsPushDownV2Filters` builder and the filters of
the others may fail
+ // on some rows, as a cast does with ANSI, so they are the leading filters
of the reads, up to
+ // the first that the builder does not get, in their order, which the
streams evaluate them in
+ // (see `TableCapability.STREAMING_FILTER_PUSHDOWN`): none runs before a
filter written before
+ // it. `PushDownUtils.pushFilters` decides which filters the builder gets
in the same way.
+ def gets(filter: Expression): Boolean = PushDownUtils.getsFilter(builder,
filter)
+ val filters = known.filter(_ => pushesFilters)
+ .map { r =>
+ builder match {
+ case _: SupportsPushDownFilters =>
+ DataSourceStrategy.normalizeExprs(r.filtersInAnyOrder,
output).filter(gets)
Review Comment:
Minor: following up on items 14
([thread](https://github.com/apache/spark/pull/60129#discussion_r4488254780))
and 47
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395315)):
a V1 builder gets the pushable filters wherever they are (this line), while V2
and Catalyst builders get only the leading ones (L455), so they lose every
filter after one that is not pushed, even a filter that cannot fail. For
example, `where("ts > current_timestamp() - INTERVAL 1 HOUR AND country =
'US'")` pushes `country = 'US'` to a V1 builder and nothing to the others,
since the first filter has a placeholder, while the same filters in the other
order push it to every builder. In item 47 you did not take the option of
giving a builder no filter after one that may fail, since that is not known in
general. The converse is known, conservatively:
`ExprUtils.canEvaluateUnconditionally` (ExprUtils.scala:265-273), which
`ConstantPropagation.moveEqualitiesFirst` uses (expressions.scala:304),
only accepts total, deterministic expressions such as `country = 'US'`. Could
these builders also get, after the leading filters, the filters of
`filtersInAnyOrder` that they take and that pass `canEvaluateUnconditionally`,
with the order of `STREAMING_FILTER_PUSHDOWN` required only for the filters
that may fail?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -830,31 +1381,233 @@ class StreamingV2ScanPushDownSuite extends StreamTest
with BeforeAndAfter {
}
}
- test("fail the start of a query whose optimization for the pruning fails, in
tests") {
- // A rule that fails in the optimization when the query starts, whose plan
has the relations of
- // the sources, unlike the plans of the micro-batches.
- val failing = new Rule[LogicalPlan] {
- override def apply(plan: LogicalPlan): LogicalPlan = {
- if (plan.exists(_.isInstanceOf[StreamingRelationV2])) {
- throw new IllegalStateException("The optimization at the start
failed.")
+ Seq(true, false).foreach { failOnError =>
+ test(s"handle a failure of the optimization when the query starts:
$failOnError") {
+ // A rule that fails in the optimization when the query starts, whose
plan has the relations
+ // of the sources, unlike the plans of the micro-batches.
+ val failing = new Rule[LogicalPlan] {
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ if (plan.exists(_.isInstanceOf[StreamingRelationV2])) {
+ throw new IllegalStateException("The optimization at the start
failed.")
+ }
+ plan
+ }
+ }
+ withSourceTable() {
+ spark.experimental.extraOptimizations = Seq(failing)
+ val logs = new LogAppender("the failure of the optimization at the
start")
+ try {
+ val failOnErrorConf =
SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR.key
+ withSQLConf(failOnErrorConf -> failOnError.toString) {
Review Comment:
Minor: following up on the
[thread](https://github.com/apache/spark/pull/60129#discussion_r4498805717) of
the seventh round: no test pins the default of
`spark.sql.streaming.v2ScanPushDown.failOnOptimizationError`,
`Utils.isTesting`, which that thread asked for, since this test sets the conf
in both branches. If the default went back to `false`, every suite would still
pass, while a failing optimization at the start would again make the other
suites read all the columns with no filter, which that thread was about. Could
the `true` case run without `withSQLConf`, or could the test assert
`SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR.defaultValue.get`, as L650
and L1897 do for the other defaults?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -1175,6 +2279,27 @@ private class PruningContinuousReaderFactory(
}
}
+/** A table whose scan builder takes V2 predicates, which it records. */
+private class V2FilterTable extends Table with SupportsRead {
Review Comment:
Nit: this repeats the V2 branch of `FilterStreamTable(input, catalyst =
false)` (L2544-2587), and `UnknownColumnFilterTable` (L2344-2375) is
`UnknownColumnReadSchemaTable` (L2324-2337) with STREAMING_FILTER_PUSHDOWN and
a V1 builder that records its filters. Also, the `AssertOnQuery` at L1249-1255
repeats `assertPushedFilters()` at L1248 under a comment from the removed
design, and the inline-table test re-implements `requiredColumns(df)` and
`pushed(df)` at L1741-1745. Could the test at L2108 use `new
FilterStreamTable(MemoryStream[(Long, String)], catalyst = false)`,
`UnknownColumnReadSchemaTable` take a `takesFilters` flag as
`PruningContinuousTable` does (L2174), L1249-1255 go, and L1741-1745 use the
two helpers?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -311,7 +314,8 @@ class MicroBatchExecution(
sourceIdentifyingName
)
StreamingDataSourceV2ScanRelation(relation, streamingScan.scan,
output,
- streamingScan.stream, scanOutput = streamingScan.scanOutput)
+ streamingScan.stream, scanOutput = streamingScan.scanOutput,
+ pushedFilters = streamingScan.pushedFilters)
Review Comment:
Minor: no test runs the filter pushdown or `checkPushedFilters` in Real-Time
Mode, although this line gives the relations of real-time queries (L310-313)
their pushed filters too, which `DataSourceV2Strategy` plans as
`RealTimeStreamScanExec` (DataSourceV2Strategy.scala:294).
`StreamingV2ScanPushDownRealTimeSuite` only enables the column pruning (L45-46
there), and its table declares only `MICRO_BATCH_READ` and
`STREAMING_COLUMN_PRUNING` (L110-111 there), while the micro-batch and
continuous paths each have an end-to-end test with filters. That suite is
outside this diff, so I left this here. Could it get a case with a table that
declares `STREAMING_FILTER_PUSHDOWN`, with the filter pushdown enabled?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -830,31 +1381,233 @@ class StreamingV2ScanPushDownSuite extends StreamTest
with BeforeAndAfter {
}
}
- test("fail the start of a query whose optimization for the pruning fails, in
tests") {
- // A rule that fails in the optimization when the query starts, whose plan
has the relations of
- // the sources, unlike the plans of the micro-batches.
- val failing = new Rule[LogicalPlan] {
- override def apply(plan: LogicalPlan): LogicalPlan = {
- if (plan.exists(_.isInstanceOf[StreamingRelationV2])) {
- throw new IllegalStateException("The optimization at the start
failed.")
+ Seq(true, false).foreach { failOnError =>
+ test(s"handle a failure of the optimization when the query starts:
$failOnError") {
+ // A rule that fails in the optimization when the query starts, whose
plan has the relations
+ // of the sources, unlike the plans of the micro-batches.
+ val failing = new Rule[LogicalPlan] {
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ if (plan.exists(_.isInstanceOf[StreamingRelationV2])) {
+ throw new IllegalStateException("The optimization at the start
failed.")
+ }
+ plan
+ }
+ }
+ withSourceTable() {
+ spark.experimental.extraOptimizations = Seq(failing)
+ val logs = new LogAppender("the failure of the optimization at the
start")
+ try {
+ val failOnErrorConf =
SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR.key
+ withSQLConf(failOnErrorConf -> failOnError.toString) {
+ val df = spark.readStream.table(tbl).where("extra >
10").select("data")
+ if (failOnError) {
+ testStream(df)(
+ StartStream(),
+ ExpectFailure[IllegalStateException](e =>
+ assert(e.getMessage.contains("The optimization at the start
failed."))))
+ } else {
+ // As outside of the tests, the scan reads all the columns with
no filter instead.
+ withLogAppender(logs,
+ loggerNames =
Seq(StreamingV2ScanPushDown.getClass.getName.stripSuffix("$")),
+ level = Some(Level.WARN)) {
+ testStream(df)(
+ ProcessAllAvailable(),
+ assertReadSchema("id", "data", "extra"),
+ assertPushedFilters(),
+ CheckAnswer(Row("b")))
+ }
+
assert(logs.loggingEvents.exists(_.getMessage.getFormattedMessage.contains(
+ "Could not optimize the streaming query to push down what it
reads")))
+ }
+ }
+ } finally {
+ spark.experimental.extraOptimizations = Nil
}
- plan
}
}
+ }
+
+ test("fail a micro-batch whose query no longer applies the filters that its
scan got") {
withSourceTable() {
- spark.experimental.extraOptimizations = Seq(failing)
+ // The filter has a value that changes each time that it is evaluated,
which the optimization
+ // at the start folds, as it would fold a function of the time that it
does not replace.
+ ChangingValue.values.set(0)
+ val df = spark.readStream.table(tbl)
+ .where(col("extra") <
ExpressionUtils.column(ChangingValue())).select("data")
+ // The scan drops the rows that fail extra < 1, while the plan of the
micro-batch has a
+ // larger value, so it would keep some of them: the micro-batch fails
before it reads them.
+ testStream(df)(
+ StartStream(),
+ ExpectFailure[SparkException] { e =>
+ checkError(e.asInstanceOf[SparkException],
+ condition = "STREAMING_SCAN_FILTERS_CHANGED",
+ parameters = Map(
+ "filters" -> "(testcat.t.extra < 1)",
+ "source" -> "`testcat`.`t`",
+ "config" ->
s"\"${SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key}\""))
+ })
+ }
+ }
+
+ test("check that the plan of each micro-batch implies the filters that its
scans got") {
+ withTable(tbl) {
+ createTable(tbl,
+ "id bigint, data string, d double, e int, t time, k struct<a: int>, xs
array<int>, " +
+ "f struct<a: double>")
+ // A relation of the source, whose pushed filters each case sets.
+ var relation: StreamingDataSourceV2ScanRelation = null
+ testStream(spark.readStream.table(tbl))(
+ ProcessAllAvailable(),
+ AssertOnQuery { query =>
+ relation = query.logicalPlan.collectFirst {
+ case relation: StreamingDataSourceV2ScanRelation => relation
+ }.get
+ true
+ })
+ val Seq(id, data, d, e, t, k, xs, f) = relation.output
+ // Checks the plan of a micro-batch that `plan` makes of the relation,
once the scan of the
+ // relation got `pushed`.
+ def check(pushed: Expression)(plan: LogicalPlan => LogicalPlan): Unit = {
+ StreamingV2ScanPushDown.checkPushedFilters(
+ spark, plan(relation.copy(pushedFilters = Seq(pushed))))
+ }
+ // Whether the check accepts that plan.
+ def accepts(pushed: Expression)(plan: LogicalPlan => LogicalPlan):
Boolean = {
+ try {
+ check(pushed)(plan)
+ true
+ } catch {
+ case e: SparkException if e.getCondition ==
"STREAMING_SCAN_FILTERS_CHANGED" => false
+ }
+ }
+ val idAbove1 = GreaterThan(id, Literal(1L))
+ val random = GreaterThan(Rand(Literal(0L)), Literal(0.5))
+ // The plan applies the filter, with others or not, or a weaker one, or
none.
+ assert(accepts(idAbove1)(Filter(And(EqualTo(data, Literal("a")),
idAbove1), _)))
+ assert(!accepts(idAbove1)(Filter(GreaterThan(id, Literal(0L)), _)))
+ assert(!accepts(idAbove1)(identity))
+ // Or it keeps no row.
+ assert(accepts(idAbove1)(Filter(Literal(false), _)))
+ assert(accepts(idAbove1)(
+ Filter(And(EqualTo(data, Literal("a")), Literal.create(null,
BooleanType)), _)))
+ // Through a projection, under an alias, but not through a projection or
above a filter that
+ // is not deterministic, as these get the rows that the filter would
drop.
+ assert(accepts(idAbove1) { relation =>
+ val alias = Alias(id, "i")()
+ Filter(GreaterThan(alias.toAttribute, Literal(1L)), Project(Seq(alias,
data), relation))
+ })
+ assert(!accepts(idAbove1) { relation =>
+ Filter(idAbove1, Project(Seq(id, Alias(Rand(Literal(0L)), "r")()),
relation))
+ })
+ assert(!accepts(idAbove1)(relation => Filter(idAbove1, Filter(random,
relation))))
+ // A filter that is not deterministic gets its rows before its conjuncts
after the first
+ // nondeterministic one, but not before those that it evaluates first.
+ assert(!accepts(idAbove1)(Filter(And(random, idAbove1), _)))
+ assert(accepts(idAbove1)(Filter(And(idAbove1, random), _)))
+ // With the values of the columns that the plan makes equal to literals.
+ assert(accepts(idAbove1)(Filter(EqualTo(id, Literal(5L)), _)))
+ assert(!accepts(idAbove1)(Filter(EqualTo(id, Literal(0L)), _)))
+ val either = Or(EqualTo(data, Literal("")), GreaterThan(id, Literal(5L)))
+ assert(accepts(either)(
+ Filter(And(EqualTo(data, Literal("a")), GreaterThan(id, Literal(5L))),
_)))
+ assert(!accepts(either)(Filter(EqualTo(data, Literal("a")), _)))
+ assert(accepts(EqualTo(Cast(id, StringType), Literal("5")))(
+ Filter(EqualTo(id, Literal(5L)), _)))
+ assert(accepts(GreaterThan(t, Literal(LocalTime.of(0, 0, 1))))(
+ Filter(EqualTo(t, Literal(LocalTime.of(12, 0))), _)))
+ // Also for a struct or an array of such values, whose literal may have
another nullability.
+ val struct = Literal.create(InternalRow(1),
+ StructType(Seq(StructField("a", IntegerType, nullable = false))))
+ assert(accepts(GreaterThan(GetStructField(k, 0, Some("a")), Literal(0)))(
+ Filter(EqualTo(k, struct), _)))
+ val array = Literal.create(ArrayData.toArrayData(Array(1, 2)),
+ ArrayType(IntegerType, containsNull = false))
+ assert(accepts(ArrayContains(xs, Literal(2)))(Filter(EqualTo(xs, array),
_)))
+ // A struct of a double gets its value if it is not 0.0 or -0.0.
+ def structOf(value: Double): Literal = Literal.create(InternalRow(value),
+ StructType(Seq(StructField("a", DoubleType, nullable = false))))
+ val kd = GetStructField(f, 0, Some("a"))
+ assert(accepts(GreaterThan(kd, Literal(0.0)))(Filter(EqualTo(f,
structOf(1.0)), _)))
+ assert(!accepts(EqualTo(Cast(kd, StringType), Literal("0.0")))(
+ Filter(EqualTo(f, structOf(0.0)), _)))
+ // And once the optimizer of the micro-batch rewrote it, as it rewrites
the plan.
+ assert(accepts(LessThan(Cast(e, LongType), id))(
+ Filter(And(EqualTo(id, Literal(5L)), LessThan(e, Literal(5))), _)))
+ assert(accepts(If(EqualTo(data, Literal("")), GreaterThan(id,
Literal(5L)),
Review Comment:
Minor: following up on item 46
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395309)):
since SPARK-60983 came in with f104507, the optimizer of a micro-batch no
longer makes the plans of this case and of L1525. `replaceInCondition`
(expressions.scala:264-271) only goes into comparisons and total operators, so
`ConstantPropagation` leaves `IF(data = '', id > 5, id > 3)` next to `data =
'a'`, and `array_contains(xs, 2)` next to `xs = [1, 2]`, as they are, and
`holds` finds them in the facts directly. The `IF` example of item 46 was right
on 7b39a35, and the merge made it outdated, so the comment at L1533, "as it
rewrites the plan", and the Scaladoc of `impliedBy`
(StreamingV2ScanPushDown.scala:730-735) no longer describe the optimizer. No
case covers a filter that the micro-batch rewrites only in part, as in item 66.
Could these cases build their plans with the optimizer, e.g.
`optimizer.execute(Filter(And(fact, pushed), relation))` with the rules that
infer f
ilters excluded, use shapes that it rewrites, and add `(a + b) > 3 OR a > b +
8` with `b = 1`?
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ScanPushDownSuite.scala:
##########
@@ -84,8 +97,15 @@ class StreamingV2ScanPushDownSuite extends StreamTest with
BeforeAndAfter {
}
/** The columns that a streaming query needs from each of its sources, when
it starts. */
Review Comment:
Nit: following up on items 18
([thread](https://github.com/apache/spark/pull/60129#discussion_r4488254797))
and 50
([thread](https://github.com/apache/spark/pull/60129#discussion_r4499395332)),
at a new place: the merge 18fc8c0 put `reads` between `requiredColumns` and its
Scaladoc, so this doc now describes `reads`, which returns the filters too, and
`requiredColumns` has none. Also, L80-81 says "the capability
STREAMING_COLUMN_PRUNING and STREAMING_FILTER_PUSHDOWN". Could `reads` get its
own doc, with this one back above `requiredColumns`, and L80 say "capabilities"?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -294,118 +383,201 @@ private[sql] object StreamingV2ScanPushDown extends
Logging {
/**
* Builds the scan of a streaming source, and creates its stream with
`createStream`. If the
- * table of the source has the capability `STREAMING_COLUMN_PRUNING`, its
scan builder supports
- * the pushdown, and `conf` enables it, the scan only reads the columns of
`output` that the query
- * reads (see `requiredColumnsOfSources`). `requiredColumns` is only
evaluated for such a scan.
- * Otherwise, the scan reads all the columns of `output`, as the scans of
streaming queries did
- * before this pushdown.
+ * table of the source has the capability `STREAMING_COLUMN_PRUNING` or
+ * `STREAMING_FILTER_PUSHDOWN`, its scan builder supports the pushdown, and
`conf` enables it,
+ * the scan only reads the columns of `output` that the query reads, or gets
the filters that the
+ * query applies to all the rows that it reads from the source (see
`columnsAndFiltersOfSources`).
+ * `reads` is only evaluated for such a scan. Otherwise, the scan reads all
the columns of
+ * `output` with no filter, as the scans of streaming queries did before
these pushdowns.
*
- * The streams of the scans of a table with the capability return the
columns of the read
- * schemas of the scans, in their order, so Spark asks each scan of such a
table for its read
+ * The streams of the scans of a table with `STREAMING_COLUMN_PRUNING`
return the columns of the
+ * read schemas of the scans, in their order, so Spark asks each scan of
such a table for its read
* schema before it creates the stream, whether the scan reads all the
columns or not. A pruned
* scan must read the required columns and only columns of `output`, each
once and with its
* type, as `SupportsPushDownRequiredColumns` requires. If the scan builder
or the scan fails
- * with the pruning, or the read schema of a pruned scan cannot be read or
does not follow
- * `SupportsPushDownRequiredColumns`, a scan of all the columns is built
instead, from a new scan
- * builder, as without this pushdown. If the read schema of a scan of all
the columns of such a
- * table does not follow the relation, the query fails with
STREAMING_SCAN_INVALID_READ_SCHEMA,
- * unless `conf` disables the column pruning, with which the scan node
outputs the columns of
- * the relation, as it did before the capability.
+ * with the pushdowns, or the read schema of a pruned scan cannot be read or
does not follow
+ * `SupportsPushDownRequiredColumns`, the scan is built again from a new
scan builder: with the
Review Comment:
Minor: following up on item 65
([thread](https://github.com/apache/spark/pull/60129#discussion_r4500701263)):
since 8ed500a, after a read schema that does not follow the column pruning,
`firstScan` skips the attempts with the same columns and tries `(output,
filters)` next (L547-549), while this still says that the scan is built again
"with the column pruning alone and then with the filters alone". The test at
StreamingV2ScanPushDownSuite.scala:2017-2037 asserts that the single warning
tries "(columns: all, filters: (testcat.t.extra > 10))" next. The bullet of the
PR description, which becomes the commit message, leaves the skip out too.
After an exception the order is still right, and it should stay so, since the
filters may be what failed. Could it say e.g. "with the column pruning alone,
unless the read schema of the pruned scan did not follow it, and then with the
filters alone if it had both"?
--
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]