dongjoon-hyun commented on code in PR #60129:
URL: https://github.com/apache/spark/pull/60129#discussion_r4487829596
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/streaming/PythonStreamingDataSourceSuite.scala:
##########
@@ -583,6 +584,46 @@ class PythonStreamingDataSourceSuite extends
PythonDataSourceSuiteBase {
q.awaitTermination()
}
+ test("Filter the stream of a data source without a batch reader") {
Review Comment:
Minor: this test passes whether or not the table declares
`STREAMING_FILTER_PUSHDOWN`, so it cannot catch what its comment says. The
answer is the same either way, since Spark evaluates `id > 1` after the scan.
And if the table did declare it, `PythonScanBuilder.pushFilters` would run
`pushdownFiltersInPython` (`PythonScanBuilder.scala` L78). That calls
`data_source.reader(schema)` in `data_source_pushdown_filters.py`, which raises
`NOT_IMPLEMENTED` for this source. `buildScan` catches the failure and builds
the scan of all the columns with no filter, so the query would still return the
same rows, and the scan relation would have no pushed filters either.
Could the test check the capability directly, for example:
```scala
val table = df.queryExecution.analyzed.collectFirst {
case r: StreamingRelationV2 => r.table
}.get
assert(!table.capabilities().contains(TableCapability.STREAMING_FILTER_PUSHDOWN))
```
and, with `withLogAppender`, that `buildScan` logs no "could not be built
with the pushdowns" warning?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala:
##########
@@ -0,0 +1,530 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import org.apache.spark.internal.{Logging, LogKeys}
+import org.apache.spark.sql.catalyst.analysis.{MultiInstanceRelation,
ResolvedInlineTable}
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute,
AttributeReference, AttributeSet, Cast, Expression, SubqueryExpression,
Unevaluable}
+import org.apache.spark.sql.catalyst.optimizer.{ComputeCurrentTime,
InferFiltersFromConstraints, ReplaceExpressions, SpecialDatetimeValues}
+import org.apache.spark.sql.catalyst.planning.PhysicalOperation
+import org.apache.spark.sql.catalyst.plans.logical.{Filter, Join, LeafNode,
LogicalPlan, Project, SetOperation, Statistics}
+import org.apache.spark.sql.catalyst.streaming.StreamingRelationV2
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CAST, CURRENT_LIKE,
RUNTIME_REPLACEABLE}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.read.{Scan, ScanBuilder,
SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.connector.read.streaming.SparkDataStream
+import org.apache.spark.sql.execution.datasources.{DataSourceStrategy,
LogicalRelation}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
PushDownUtils, StreamingDataSourceV2Relation, StreamingDataSourceV2ScanRelation}
+import
org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata,
OffsetSeqMetadataBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType,
StructType, TimestampLTZNanosType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * 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
+ * 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 these pushdowns, but for a
filter of the rows
+ * of the relation with the filters that the scan builder got, which the query
applies anyway, so
+ * that the scan cannot drop a row that the plan keeps (see
`withPushedFilters`). The optimizer
+ * keeps deciding which columns every operator gets, and in which order,
including the stateful
+ * ones, and Spark still evaluates all the filters over the relation. 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.
+ *
+ * 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 {
+
+ /**
+ * 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 filters the filters that the scan of the relation may get, in the
order in which the
+ * plan evaluates them: those that every occurrence of the
relation applies first,
+ * see `pushableFilters`
+ */
+ case class Reads(requiredColumns: AttributeSet, filters: Seq[Expression])
+
+ /**
+ * The scan of a streaming source, and its stream.
+ *
+ * @param prunedOutput the columns of the relation that the scan reads, in
the order of its read
+ * schema, unless these are all its columns
+ * @param pushedFilters the filters that the scan builder got, which the
scan may apply in any
+ * form, so the plan of each micro-batch applies them
over the relation
+ */
+ case class StreamingScan(
+ scan: Scan,
+ stream: SparkDataStream,
+ prunedOutput: Option[Seq[AttributeReference]],
+ pushedFilters: Seq[Expression]) {
+
+ /** Returns the scan relation of the source whose relation is `relation`.
*/
+ def toRelation(
+ relation: StreamingDataSourceV2Relation):
StreamingDataSourceV2ScanRelation = {
+ StreamingDataSourceV2ScanRelation(relation, scan, relation.output,
stream,
+ prunedOutput = prunedOutput, pushedFilters = pushedFilters)
+ }
+ }
+
+ /**
+ * Returns what the optimized `plan` reads from each of its streaming
relations of Data Source
+ * V2: what the planner takes from the projections and the filters over each
occurrence of the
+ * relation, or all its columns and no filter where nothing is projected or
filtered over it. A
+ * relation that the optimized plan does not have has no entry, so that its
scan reads all its
+ * columns and gets no filter, as no relation has if the optimizer fails, or
if the optimized
+ * plan has a streaming relation that `plan` does not have.
+ *
+ * The plan is optimized as the micro-batches are: with the optimizer and
the configuration of
+ * the stream, the values of the configurations that the offset log of a
restarted query pins, and
+ * without the cost-based reordering of joins, which `StreamExecution`
disables for its queries.
+ * The plan does not depend on when it is optimized, and the scan of a
relation only gets what the
+ * query reads from that relation:
+ * - The expressions whose values depend on when they are evaluated or on
the state of the
+ * session, such as the current time, the casts of special strings such
as 'today' or 'now'
+ * to dates and timestamps, the casts of strings to timestamps with local
time zone, which take
+ * the current date for a string with only a time, or the current
database, which each
+ * micro-batch gets the values of, become placeholders that the optimizer
does not take as
+ * deterministic, as the current time of a micro-batch, so neither its
filters nor its columns
+ * depend on them, and no filter on them is pushed down.
+ * - The filters that the optimizer infers from the constraints of the
plan, such as those of the
+ * filters over another relation joined with the relation, are not
inferred, so that the scan
+ * only gets the filters that the query applies to the relation itself.
+ * - The relations of batch scans become placeholders, so that their scans
are neither built
+ * nor planned: they do not change what the plan reads from its streaming
relations.
+ *
+ * @param session the session of the stream
+ * @param offsetLogMetadata the metadata of the last entry of the offset log
of the query, if any
+ */
+ def reads(
+ session: SparkSession,
+ plan: LogicalPlan,
+ offsetLogMetadata: Option[OffsetSeqMetadataBase]):
Map[StreamingRelationV2, Reads] = {
+ val conf = session.sessionState.conf.clone()
+ offsetLogMetadata.foreach(OffsetSeqMetadata.setSessionConf(_, conf,
logChanges = false))
+ conf.setConf(SQLConf.CBO_ENABLED, false)
+ conf.setConfString(SQLConf.OPTIMIZER_EXCLUDED_RULES.key,
+ (conf.optimizerExcludedRules.toSeq :+
InferFiltersFromConstraints.ruleName).mkString(","))
+ // Without a source that prunes its columns, the scans can only get
filters, which come from a
+ // condition of the plan: without one, nothing can be pushed down, and the
plan is not
+ // optimized.
+ val prunesColumns = conf.streamingV2ColumnPruningEnabled && plan.exists {
+ case relation: StreamingRelationV2 =>
+
relation.table.capabilities().contains(TableCapability.STREAMING_COLUMN_PRUNING)
+ case _ => false
+ }
+ if (!prunesColumns && !mayHaveConditions(plan)) {
+ return Map.empty
+ }
+ session.withActive {
+ SQLConf.withExistingConf(conf) {
+ try {
+ val optimized =
session.sessionState.optimizer.execute(forStartup(plan))
+ // The planner of a micro-batch gets the values of the expressions
that depend on when
+ // they are evaluated, which are deterministic.
+ val planned = optimized.transformUpWithSubqueries {
+ case node => node.transformExpressions {
+ case value: StartupValue => value.copy(planned = true)
+ }
+ }
+ val occurrences = mutable.ArrayBuffer.empty[(StreamingRelationV2,
Reads)]
+ // Visits the nodes as the planner plans them: the projections and
the filters over a
+ // relation are planned with its scan, and the other nodes on their
own.
+ def visit(node: LogicalPlan): Unit = node match {
+ case PhysicalOperation(project, filters, relation:
StreamingRelationV2) =>
+ occurrences += relation -> Reads(
+ AttributeSet((project ++ filters).flatMap(_.references)),
+ pushableFilters(filtersEvaluatedOnce(node, filters, conf)))
+ case _ =>
+ node.children.foreach(visit)
+ }
+ visit(planned)
+ val relations = plan.collect { case relation: StreamingRelationV2 =>
relation }.toSet
+ val unknown = occurrences.map(_._1).filterNot(relations.contains)
+ if (unknown.nonEmpty) {
+ // The optimizer does not copy streaming relations:
`DeduplicateRelations` keeps
+ // streaming plans as they are, so all the references to a common
table expression,
+ // for example, have the same relation. A copy would share the
scan of its relation in
+ // the micro-batches, so the scan would have to read what the copy
reads too.
+ logWarning(log"The optimized streaming query reads the streaming
relations " +
+ log"${MDC(LogKeys.STREAMING_TABLE, unknown.distinct.mkString(",
"))} that its " +
+ log"plan does not have, so the scans of its sources read all
their columns with " +
+ log"no filter.")
+ Map.empty
+ } else {
+ combine(occurrences.toSeq)
+ }
+ } catch {
+ case NonFatal(e) =>
+ logWarning(log"Could not optimize the streaming query to push down
what it reads " +
+ log"to the scans of its sources, which read all their columns
with no filter.", e)
+ Map.empty
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns what the occurrences of each relation read, combined: the scan of
a relation reads the
+ * rows of all its occurrences, so it reads the columns that any of them
reads, and can only
+ * apply the filters that all of them apply. Each occurrence evaluates the
pushed filters before
+ * its own, so the pushed filters are those that all the occurrences
evaluate first, in the same
+ * order: the longest common prefix of their filters, see `pushableFilters`.
+ */
+ private def combine(
+ occurrences: Seq[(StreamingRelationV2, Reads)]):
Map[StreamingRelationV2, Reads] = {
+ occurrences.groupBy(_._1).map { case (relation, reads) =>
+ val filters = reads.map(_._2.filters).reduce { (left, right) =>
+ left.zip(right).takeWhile { case (l, r) => l.semanticEquals(r)
}.map(_._1)
+ }
+ relation ->
Reads(AttributeSet.fromAttributeSets(reads.map(_._2.requiredColumns)), filters)
+ }
+ }
+
+ /**
+ * Returns whether `plan` has a node with a condition that the optimizer
could push down to a
+ * relation: a filter, or a join or a set operation, which it may turn into
one.
+ */
+ private def mayHaveConditions(plan: LogicalPlan): Boolean = plan.exists {
Review Comment:
Minor: `Filter`, `Join` and set operations are not the only nodes from which
a condition reaches a source. Below a non-outer `explode` or `inline` of an
attribute, `InferFiltersFromGenerate` adds `size(arr) > 0 AND isnotnull(arr)`
(`Optimizer.scala` L2228-L2235). `reads` excludes only
`InferFiltersFromConstraints`, so the startup plan has that `Filter` over the
relation, and `isnotnull(arr)` translates to `IsNotNull(arr)` for a
`SupportsPushDownFilters` builder. So for a table that declares only
`STREAMING_FILTER_PUSHDOWN`:
- `readStream.table(t).select(explode($"arr"))` has none of these nodes, so
`reads` returns early and the scan gets no filter.
- `readStream.table(t).where("id > 0").select(explode($"arr"))` is
optimized, and the scan gets `IsNotNull(arr)` next to `GreaterThan(id,0)`.
- The first query also gets `IsNotNull(arr)` when the table declares
`STREAMING_COLUMN_PRUNING` too, since `reads` then optimizes it either way.
This is about the check added for [item 3 of round
1](https://github.com/apache/spark/pull/60129#discussion_r4483802586). Could
`mayHaveConditions` also take a `Generate`, or could `reads` exclude
`InferFiltersFromGenerate` as it does `InferFiltersFromConstraints`? The test
of the queries that are not optimized could pin the choice with an `explode`
query. I traced this from the code and did not run it.
--
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]