HyukjinKwon commented on code in PR #60129: URL: https://github.com/apache/spark/pull/60129#discussion_r4499941725
########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala: ########## @@ -0,0 +1,790 @@ +/* + * 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.SparkException +import org.apache.spark.internal.{Logging, LogKeys} +import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation +import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, AttributeMap, AttributeReference, AttributeSet, BinaryComparison, 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.{InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions} +import org.apache.spark.sql.catalyst.planning.PhysicalOperation +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.classic.SparkSession +import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsRead, Table, TableCapability} +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, BinaryType, BooleanType, DataType, DatetimeType, DateType, DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, YearMonthIntervalType} +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 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 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) + }.getOrElse(Nil) + } + + /** + * The pushable filters that every occurrence applies, in the order of the first occurrence, + * wherever they are. These are the filters for a scan builder whose filters cannot fail, which + * may run before the filters written before them. + */ + def filtersInAnyOrder: Seq[Expression] = { + occurrenceFilters.map(_.filter(isPushable)) match { + case Seq() => Nil + case first +: others => + val sets = others.map(ExpressionSet(_)) + first.filter(filter => sets.forall(_.contains(filter))) + } + } + } + + /** + * Returns whether the scan of a relation may get `filter`, a deterministic filter over the + * relation: if it has no subquery and no placeholder, whose value each micro-batch gets on its + * own (see `forStartup`). + */ + private def isPushable(filter: Expression): Boolean = { + !SubqueryExpression.hasSubquery(filter) && !filter.exists(_.isInstanceOf[StartupValue]) + } + + /** + * The scan of a streaming source, and its stream. + * + * @param scanOutput the columns of the relation that the scan reads, in the order of its read + * schema, unless these are all its columns in their order + * @param pushedFilters the filters that the scan builder got, which the scan may apply in any + * form, so the plan of each micro-batch must apply them too (see + * `checkPushedFilters`) + */ + case class StreamingScan( + scan: Scan, + stream: SparkDataStream, + scanOutput: Option[Seq[AttributeReference]], + pushedFilters: Seq[Expression]) + + /** + * Returns the name of a streaming source in the errors of its scan: the parts of its identifier, + * with its catalog, or the name of its table. + */ + def sourceName( + table: Table, + catalog: Option[CatalogPlugin], + identifier: Option[Identifier]): Seq[String] = (catalog, identifier) match { + case (Some(catalog), Some(identifier)) => + (catalog.name +: identifier.namespace.toSeq) :+ identifier.name + case _ => Seq(table.name()) + } + + /** + * Returns the columns that each streaming relation of Data Source V2 needs to read, and the + * filters that its scan may get, from `plan` optimized as the micro-batches are (see + * `forStartup`), without the filters that the optimizer infers from the constraints of the plan + * or from generators, so that a scan only gets the filters that the query applies to its own + * source. A relation without an entry reads all its columns with no filter, as all do if the + * optimization fails, unless `spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` makes + * the failure fail the query, as in the tests. The plan is not optimized when no source prunes + * its columns and the plan has no condition, since nothing could be pushed down. + * + * @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 columnsAndFiltersOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + try { + readsOfSources(session, plan, offsetLogMetadata) + } catch { + case NonFatal(e) + if !session.sessionState.conf.getConf(SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR) => + 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 + } + } + + // What the relations of `plan` read, see `columnsAndFiltersOfSources`, or the failure of the + // optimization. + private def readsOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + val conf = session.sessionState.conf.clone() + offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf)) + conf.setConf(SQLConf.CBO_ENABLED, false) + withoutInferredFilters(conf) + 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) { + // The plan of a micro-batch is normalized before it is optimized, see `QueryExecution`. + val normalized = QueryExecution.normalize(session, plan) + val optimized = session.sessionState.optimizer.execute(forStartup(normalized)) + val planned = forPlanning(optimized) + 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. This must match + // the nodes that `DataSourceV2Strategy` plans the scans of streaming relations with. + def visit(node: LogicalPlan): Unit = node match { + case PhysicalOperation(project, filters, relation: StreamingRelationV2) => + occurrences += relation -> Reads( + AttributeSet((project ++ filters).flatMap(_.references)), + Seq(filters.takeWhile(_.deterministic))) + 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. + throw SparkException.internalError("The optimized streaming query reads the " + + s"streaming relations ${unknown.distinct.mkString(", ")} that its plan does not have.") + } else { + // 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 (see `Reads`). + occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) => + relation -> Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)), + reads.flatMap(_.occurrenceFilters)) + } + } + } + } + } + + /** + * 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. + */ + def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = { + val hasPushedFilters = plan.exists { + case relation: StreamingDataSourceV2ScanRelation => relation.pushedFilters.nonEmpty + case _ => false + } + if (hasPushedFilters) { + // The configuration of the micro-batch, without the rules that infer filters, which would + // add conditions to those that `impliedBy` gets from the optimizer. + lazy val optimizerConf = withoutInferredFilters(session.sessionState.conf.clone()) + conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) => + // The conjuncts of `condition` once the optimizer of the micro-batch optimizes a filter + // of the relation with it, none if it folds into true, or nothing if it folds into false. + def optimized(condition: Expression): Option[Seq[Expression]] = Try { + SQLConf.withExistingConf(optimizerConf) { + session.sessionState.optimizer.execute( + Filter(condition, relation.copy(pushedFilters = Nil))) + } + }.toOption.collect { + case Filter(optimizedCondition, _: StreamingDataSourceV2ScanRelation) => + splitConjunctivePredicates(optimizedCondition) + case _: StreamingDataSourceV2ScanRelation => Nil + } + val unapplied = relation.pushedFilters.filterNot(impliedBy(conditions, optimized)) + if (unapplied.nonEmpty) { + throw QueryExecutionErrors.streamingScanFiltersChangedError( + sourceName(relation.relation.table, relation.catalog, relation.identifier), + unapplied.map(_.sql)) + } + } + } + } + + // Each occurrence of a streaming relation in `plan`, with the deterministic conditions that the + // plan applies to all its rows, given `above`, those that it applies to all the rows of `plan`: + // the conditions of the filters over it, through the projections, with the aliases of these in + // place of their names, as `PhysicalOperation` finds the filters of a relation. The conditions + // over a filter or a projection that is not deterministic do not hold for the rows that it gets. + private def conditionsOverRelations( + plan: LogicalPlan, + above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation, Seq[Expression])] = { + plan match { + case relation: StreamingDataSourceV2ScanRelation => Seq(relation -> above) + case Filter(condition, child) => + val conditions = splitConjunctivePredicates(condition).filter(_.deterministic) + conditionsOverRelations(child, + if (condition.deterministic) conditions ++ above else conditions) + case Project(projectList, child) if projectList.forall(_.deterministic) => + val aliases = getAliasMap(projectList) + conditionsOverRelations(child, above.map(replaceAlias(_, aliases))) + case other => other.children.flatMap(conditionsOverRelations(_, Nil)) + } + } + + /** + * Returns whether a filter is implied by `facts`, the deterministic conditions that hold for all + * the rows that a plan keeps from a relation: the facts 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 + * anywhere for the types whose equal values are the same (see `hasExactEquality`), and only + * where the columns are compared for the floating types: Spark compares 0.0 and -0.0 as equal, + * and NaN and NaN, so a column equal to 0.0 compares with any value as 0.0 does. 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 known = ExpressionSet(facts) + def holds(condition: Expression): Boolean = known.contains(condition) || (condition match { Review Comment: Done in 03ab26e: a fact that is a false or null literal now implies every filter, since no row passes it, so the `Filter(false, relation)` that `PruneFilters` keeps over a streaming plan is accepted. The test of the stream-static join now also has `id > 5`, which each micro-batch folds into `false` with `id = 2`; it outputs nothing and raises no error. I also fixed the comment of `optimized`: a pushed filter whose values fold it into false isn't implied, unless the facts themselves are false. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala: ########## @@ -0,0 +1,790 @@ +/* + * 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.SparkException +import org.apache.spark.internal.{Logging, LogKeys} +import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation +import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, AttributeMap, AttributeReference, AttributeSet, BinaryComparison, 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.{InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions} +import org.apache.spark.sql.catalyst.planning.PhysicalOperation +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.classic.SparkSession +import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsRead, Table, TableCapability} +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, BinaryType, BooleanType, DataType, DatetimeType, DateType, DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, YearMonthIntervalType} +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 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 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) + }.getOrElse(Nil) + } + + /** + * The pushable filters that every occurrence applies, in the order of the first occurrence, + * wherever they are. These are the filters for a scan builder whose filters cannot fail, which + * may run before the filters written before them. + */ + def filtersInAnyOrder: Seq[Expression] = { + occurrenceFilters.map(_.filter(isPushable)) match { + case Seq() => Nil + case first +: others => + val sets = others.map(ExpressionSet(_)) + first.filter(filter => sets.forall(_.contains(filter))) + } + } + } + + /** + * Returns whether the scan of a relation may get `filter`, a deterministic filter over the + * relation: if it has no subquery and no placeholder, whose value each micro-batch gets on its + * own (see `forStartup`). + */ + private def isPushable(filter: Expression): Boolean = { + !SubqueryExpression.hasSubquery(filter) && !filter.exists(_.isInstanceOf[StartupValue]) + } + + /** + * The scan of a streaming source, and its stream. + * + * @param scanOutput the columns of the relation that the scan reads, in the order of its read + * schema, unless these are all its columns in their order + * @param pushedFilters the filters that the scan builder got, which the scan may apply in any + * form, so the plan of each micro-batch must apply them too (see + * `checkPushedFilters`) + */ + case class StreamingScan( + scan: Scan, + stream: SparkDataStream, + scanOutput: Option[Seq[AttributeReference]], + pushedFilters: Seq[Expression]) + + /** + * Returns the name of a streaming source in the errors of its scan: the parts of its identifier, + * with its catalog, or the name of its table. + */ + def sourceName( + table: Table, + catalog: Option[CatalogPlugin], + identifier: Option[Identifier]): Seq[String] = (catalog, identifier) match { + case (Some(catalog), Some(identifier)) => + (catalog.name +: identifier.namespace.toSeq) :+ identifier.name + case _ => Seq(table.name()) + } + + /** + * Returns the columns that each streaming relation of Data Source V2 needs to read, and the + * filters that its scan may get, from `plan` optimized as the micro-batches are (see + * `forStartup`), without the filters that the optimizer infers from the constraints of the plan + * or from generators, so that a scan only gets the filters that the query applies to its own + * source. A relation without an entry reads all its columns with no filter, as all do if the + * optimization fails, unless `spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` makes + * the failure fail the query, as in the tests. The plan is not optimized when no source prunes + * its columns and the plan has no condition, since nothing could be pushed down. + * + * @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 columnsAndFiltersOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + try { + readsOfSources(session, plan, offsetLogMetadata) + } catch { + case NonFatal(e) + if !session.sessionState.conf.getConf(SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR) => + 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 + } + } + + // What the relations of `plan` read, see `columnsAndFiltersOfSources`, or the failure of the + // optimization. + private def readsOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + val conf = session.sessionState.conf.clone() + offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf)) + conf.setConf(SQLConf.CBO_ENABLED, false) + withoutInferredFilters(conf) + 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) { + // The plan of a micro-batch is normalized before it is optimized, see `QueryExecution`. + val normalized = QueryExecution.normalize(session, plan) + val optimized = session.sessionState.optimizer.execute(forStartup(normalized)) + val planned = forPlanning(optimized) + 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. This must match + // the nodes that `DataSourceV2Strategy` plans the scans of streaming relations with. + def visit(node: LogicalPlan): Unit = node match { + case PhysicalOperation(project, filters, relation: StreamingRelationV2) => + occurrences += relation -> Reads( + AttributeSet((project ++ filters).flatMap(_.references)), + Seq(filters.takeWhile(_.deterministic))) + 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. + throw SparkException.internalError("The optimized streaming query reads the " + + s"streaming relations ${unknown.distinct.mkString(", ")} that its plan does not have.") + } else { + // 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 (see `Reads`). + occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) => + relation -> Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)), + reads.flatMap(_.occurrenceFilters)) + } + } + } + } + } + + /** + * 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. + */ + def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = { + val hasPushedFilters = plan.exists { + case relation: StreamingDataSourceV2ScanRelation => relation.pushedFilters.nonEmpty + case _ => false + } + if (hasPushedFilters) { + // The configuration of the micro-batch, without the rules that infer filters, which would + // add conditions to those that `impliedBy` gets from the optimizer. + lazy val optimizerConf = withoutInferredFilters(session.sessionState.conf.clone()) + conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) => + // The conjuncts of `condition` once the optimizer of the micro-batch optimizes a filter + // of the relation with it, none if it folds into true, or nothing if it folds into false. + def optimized(condition: Expression): Option[Seq[Expression]] = Try { Review Comment: Done in 03ab26e: a failure of the optimizer is now kept as the cause of `STREAMING_SCAN_FILTERS_CHANGED`. The error still says how to recover (disable the configuration), and its cause shows the real error. The test of the check covers it with an `extraOptimizations` rule that throws on the plan that the check optimizes. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala: ########## @@ -0,0 +1,790 @@ +/* + * 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.SparkException +import org.apache.spark.internal.{Logging, LogKeys} +import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation +import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, AttributeMap, AttributeReference, AttributeSet, BinaryComparison, 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.{InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions} +import org.apache.spark.sql.catalyst.planning.PhysicalOperation +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.classic.SparkSession +import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsRead, Table, TableCapability} +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, BinaryType, BooleanType, DataType, DatetimeType, DateType, DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, YearMonthIntervalType} +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 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 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) + }.getOrElse(Nil) + } + + /** + * The pushable filters that every occurrence applies, in the order of the first occurrence, + * wherever they are. These are the filters for a scan builder whose filters cannot fail, which + * may run before the filters written before them. + */ + def filtersInAnyOrder: Seq[Expression] = { + occurrenceFilters.map(_.filter(isPushable)) match { + case Seq() => Nil + case first +: others => + val sets = others.map(ExpressionSet(_)) + first.filter(filter => sets.forall(_.contains(filter))) + } + } + } + + /** + * Returns whether the scan of a relation may get `filter`, a deterministic filter over the + * relation: if it has no subquery and no placeholder, whose value each micro-batch gets on its + * own (see `forStartup`). + */ + private def isPushable(filter: Expression): Boolean = { + !SubqueryExpression.hasSubquery(filter) && !filter.exists(_.isInstanceOf[StartupValue]) + } + + /** + * The scan of a streaming source, and its stream. + * + * @param scanOutput the columns of the relation that the scan reads, in the order of its read + * schema, unless these are all its columns in their order + * @param pushedFilters the filters that the scan builder got, which the scan may apply in any + * form, so the plan of each micro-batch must apply them too (see + * `checkPushedFilters`) + */ + case class StreamingScan( + scan: Scan, + stream: SparkDataStream, + scanOutput: Option[Seq[AttributeReference]], + pushedFilters: Seq[Expression]) + + /** + * Returns the name of a streaming source in the errors of its scan: the parts of its identifier, + * with its catalog, or the name of its table. + */ + def sourceName( + table: Table, + catalog: Option[CatalogPlugin], + identifier: Option[Identifier]): Seq[String] = (catalog, identifier) match { + case (Some(catalog), Some(identifier)) => + (catalog.name +: identifier.namespace.toSeq) :+ identifier.name + case _ => Seq(table.name()) + } + + /** + * Returns the columns that each streaming relation of Data Source V2 needs to read, and the + * filters that its scan may get, from `plan` optimized as the micro-batches are (see + * `forStartup`), without the filters that the optimizer infers from the constraints of the plan + * or from generators, so that a scan only gets the filters that the query applies to its own + * source. A relation without an entry reads all its columns with no filter, as all do if the + * optimization fails, unless `spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` makes + * the failure fail the query, as in the tests. The plan is not optimized when no source prunes + * its columns and the plan has no condition, since nothing could be pushed down. + * + * @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 columnsAndFiltersOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + try { + readsOfSources(session, plan, offsetLogMetadata) + } catch { + case NonFatal(e) + if !session.sessionState.conf.getConf(SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR) => + 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 + } + } + + // What the relations of `plan` read, see `columnsAndFiltersOfSources`, or the failure of the + // optimization. + private def readsOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + val conf = session.sessionState.conf.clone() + offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf)) + conf.setConf(SQLConf.CBO_ENABLED, false) + withoutInferredFilters(conf) + 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) { + // The plan of a micro-batch is normalized before it is optimized, see `QueryExecution`. + val normalized = QueryExecution.normalize(session, plan) + val optimized = session.sessionState.optimizer.execute(forStartup(normalized)) + val planned = forPlanning(optimized) + 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. This must match + // the nodes that `DataSourceV2Strategy` plans the scans of streaming relations with. + def visit(node: LogicalPlan): Unit = node match { + case PhysicalOperation(project, filters, relation: StreamingRelationV2) => + occurrences += relation -> Reads( + AttributeSet((project ++ filters).flatMap(_.references)), + Seq(filters.takeWhile(_.deterministic))) + 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. + throw SparkException.internalError("The optimized streaming query reads the " + + s"streaming relations ${unknown.distinct.mkString(", ")} that its plan does not have.") + } else { + // 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 (see `Reads`). + occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) => + relation -> Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)), + reads.flatMap(_.occurrenceFilters)) + } + } + } + } + } + + /** + * 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. + */ + def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = { + val hasPushedFilters = plan.exists { + case relation: StreamingDataSourceV2ScanRelation => relation.pushedFilters.nonEmpty + case _ => false + } + if (hasPushedFilters) { + // The configuration of the micro-batch, without the rules that infer filters, which would + // add conditions to those that `impliedBy` gets from the optimizer. + lazy val optimizerConf = withoutInferredFilters(session.sessionState.conf.clone()) + conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) => + // The conjuncts of `condition` once the optimizer of the micro-batch optimizes a filter + // of the relation with it, none if it folds into true, or nothing if it folds into false. + def optimized(condition: Expression): Option[Seq[Expression]] = Try { + SQLConf.withExistingConf(optimizerConf) { + session.sessionState.optimizer.execute( + Filter(condition, relation.copy(pushedFilters = Nil))) + } + }.toOption.collect { + case Filter(optimizedCondition, _: StreamingDataSourceV2ScanRelation) => + splitConjunctivePredicates(optimizedCondition) + case _: StreamingDataSourceV2ScanRelation => Nil + } + val unapplied = relation.pushedFilters.filterNot(impliedBy(conditions, optimized)) + if (unapplied.nonEmpty) { + throw QueryExecutionErrors.streamingScanFiltersChangedError( + sourceName(relation.relation.table, relation.catalog, relation.identifier), + unapplied.map(_.sql)) + } + } + } + } + + // Each occurrence of a streaming relation in `plan`, with the deterministic conditions that the + // plan applies to all its rows, given `above`, those that it applies to all the rows of `plan`: + // the conditions of the filters over it, through the projections, with the aliases of these in + // place of their names, as `PhysicalOperation` finds the filters of a relation. The conditions + // over a filter or a projection that is not deterministic do not hold for the rows that it gets. + private def conditionsOverRelations( + plan: LogicalPlan, + above: Seq[Expression]): Seq[(StreamingDataSourceV2ScanRelation, Seq[Expression])] = { + plan match { + case relation: StreamingDataSourceV2ScanRelation => Seq(relation -> above) + case Filter(condition, child) => + val conditions = splitConjunctivePredicates(condition).filter(_.deterministic) + conditionsOverRelations(child, + if (condition.deterministic) conditions ++ above else conditions) + case Project(projectList, child) if projectList.forall(_.deterministic) => + val aliases = getAliasMap(projectList) + conditionsOverRelations(child, above.map(replaceAlias(_, aliases))) + case other => other.children.flatMap(conditionsOverRelations(_, Nil)) + } + } + + /** + * Returns whether a filter is implied by `facts`, the deterministic conditions that hold for all + * the rows that a plan keeps from a relation: the facts 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 + * anywhere for the types whose equal values are the same (see `hasExactEquality`), and only + * where the columns are compared for the floating types: Spark compares 0.0 and -0.0 as equal, + * and NaN and NaN, so a column equal to 0.0 compares with any value as 0.0 does. 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 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 equalities = facts.collect { + case EqualTo(column: Attribute, value: Literal) => column -> value + case EqualTo(value: Literal, column: Attribute) => column -> value + case EqualNullSafe(column: Attribute, value: Literal) => column -> value + case EqualNullSafe(value: Literal, column: Attribute) => column -> value + }.filter { case (column, value) => column.dataType == value.dataType } + val values = AttributeMap(equalities.filter { case (column, _) => + hasExactEquality(column.dataType) + }) + val comparedValues = AttributeMap(equalities.filter { case (column, _) => + column.dataType == FloatType || column.dataType == DoubleType + }) + def withValues(condition: Expression): Expression = condition.transformUp { + case column: Attribute if values.contains(column) => values(column) + case comparison: BinaryComparison if comparedValues.nonEmpty => Review Comment: Thanks for the correction. It turns out there is a simple sound rule, and 03ab26e uses it. Equal doubles only differ for 0.0 and -0.0, and NaN values are all equal and evaluate alike. So a column equal to any other value has that value everywhere, and a column equal to zero is either 0.0 or -0.0. The values now replace these columns anywhere, and when a column is zero, the filter must hold with both 0.0 and -0.0, with one optimizer run each, for up to three such columns in a filter. So `floor(d) >= 0` with `d = 0.0` is accepted, since `floor(0.0) >= 0` and `floor(-0.0) >= 0` both fold into true. `CAST(d AS STRING) = '0.0'` is still rejected, since `CAST(-0.0 AS STRING)` is `-0.0`. The Scaladoc of `impliedBy` describes this, and the test of the check pins `floor(d) >= 0`, the cast, and the cast of a double equal to 1.5. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ScanPushDown.scala: ########## @@ -0,0 +1,790 @@ +/* + * 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.SparkException +import org.apache.spark.internal.{Logging, LogKeys} +import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation +import org.apache.spark.sql.catalyst.expressions.{AliasHelper, And, Attribute, AttributeMap, AttributeReference, AttributeSet, BinaryComparison, 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.{InferFiltersFromConstraints, InferFiltersFromGenerate, ReplaceExpressions} +import org.apache.spark.sql.catalyst.planning.PhysicalOperation +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.classic.SparkSession +import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsRead, Table, TableCapability} +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, BinaryType, BooleanType, DataType, DatetimeType, DateType, DayTimeIntervalType, DecimalType, DoubleType, FloatType, IntegralType, StringType, StructType, TimestampNTZType, TimestampType, TimeType, VariantType, YearMonthIntervalType} +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 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 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) + }.getOrElse(Nil) + } + + /** + * The pushable filters that every occurrence applies, in the order of the first occurrence, + * wherever they are. These are the filters for a scan builder whose filters cannot fail, which + * may run before the filters written before them. + */ + def filtersInAnyOrder: Seq[Expression] = { + occurrenceFilters.map(_.filter(isPushable)) match { + case Seq() => Nil + case first +: others => + val sets = others.map(ExpressionSet(_)) + first.filter(filter => sets.forall(_.contains(filter))) + } + } + } + + /** + * Returns whether the scan of a relation may get `filter`, a deterministic filter over the + * relation: if it has no subquery and no placeholder, whose value each micro-batch gets on its + * own (see `forStartup`). + */ + private def isPushable(filter: Expression): Boolean = { + !SubqueryExpression.hasSubquery(filter) && !filter.exists(_.isInstanceOf[StartupValue]) + } + + /** + * The scan of a streaming source, and its stream. + * + * @param scanOutput the columns of the relation that the scan reads, in the order of its read + * schema, unless these are all its columns in their order + * @param pushedFilters the filters that the scan builder got, which the scan may apply in any + * form, so the plan of each micro-batch must apply them too (see + * `checkPushedFilters`) + */ + case class StreamingScan( + scan: Scan, + stream: SparkDataStream, + scanOutput: Option[Seq[AttributeReference]], + pushedFilters: Seq[Expression]) + + /** + * Returns the name of a streaming source in the errors of its scan: the parts of its identifier, + * with its catalog, or the name of its table. + */ + def sourceName( + table: Table, + catalog: Option[CatalogPlugin], + identifier: Option[Identifier]): Seq[String] = (catalog, identifier) match { + case (Some(catalog), Some(identifier)) => + (catalog.name +: identifier.namespace.toSeq) :+ identifier.name + case _ => Seq(table.name()) + } + + /** + * Returns the columns that each streaming relation of Data Source V2 needs to read, and the + * filters that its scan may get, from `plan` optimized as the micro-batches are (see + * `forStartup`), without the filters that the optimizer infers from the constraints of the plan + * or from generators, so that a scan only gets the filters that the query applies to its own + * source. A relation without an entry reads all its columns with no filter, as all do if the + * optimization fails, unless `spark.sql.streaming.v2ScanPushDown.failOnOptimizationError` makes + * the failure fail the query, as in the tests. The plan is not optimized when no source prunes + * its columns and the plan has no condition, since nothing could be pushed down. + * + * @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 columnsAndFiltersOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + try { + readsOfSources(session, plan, offsetLogMetadata) + } catch { + case NonFatal(e) + if !session.sessionState.conf.getConf(SQLConf.STREAMING_V2_SCAN_PUSHDOWN_FAIL_ON_ERROR) => + 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 + } + } + + // What the relations of `plan` read, see `columnsAndFiltersOfSources`, or the failure of the + // optimization. + private def readsOfSources( + session: SparkSession, + plan: LogicalPlan, + offsetLogMetadata: Option[OffsetSeqMetadataBase]): Map[StreamingRelationV2, Reads] = { + val conf = session.sessionState.conf.clone() + offsetLogMetadata.foreach(OffsetSeqMetadata.setConfWithoutLogging(_, conf)) + conf.setConf(SQLConf.CBO_ENABLED, false) + withoutInferredFilters(conf) + 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) { + // The plan of a micro-batch is normalized before it is optimized, see `QueryExecution`. + val normalized = QueryExecution.normalize(session, plan) + val optimized = session.sessionState.optimizer.execute(forStartup(normalized)) + val planned = forPlanning(optimized) + 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. This must match + // the nodes that `DataSourceV2Strategy` plans the scans of streaming relations with. + def visit(node: LogicalPlan): Unit = node match { + case PhysicalOperation(project, filters, relation: StreamingRelationV2) => + occurrences += relation -> Reads( + AttributeSet((project ++ filters).flatMap(_.references)), + Seq(filters.takeWhile(_.deterministic))) + 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. + throw SparkException.internalError("The optimized streaming query reads the " + + s"streaming relations ${unknown.distinct.mkString(", ")} that its plan does not have.") + } else { + // 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 (see `Reads`). + occurrences.toSeq.groupMap(_._1)(_._2).map { case (relation, reads) => + relation -> Reads(AttributeSet.fromAttributeSets(reads.map(_.requiredColumns)), + reads.flatMap(_.occurrenceFilters)) + } + } + } + } + } + + /** + * 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. + */ + def checkPushedFilters(session: SparkSession, plan: LogicalPlan): Unit = { + val hasPushedFilters = plan.exists { + case relation: StreamingDataSourceV2ScanRelation => relation.pushedFilters.nonEmpty + case _ => false + } + if (hasPushedFilters) { + // The configuration of the micro-batch, without the rules that infer filters, which would + // add conditions to those that `impliedBy` gets from the optimizer. + lazy val optimizerConf = withoutInferredFilters(session.sessionState.conf.clone()) + conditionsOverRelations(plan, Nil).foreach { case (relation, conditions) => + // The conjuncts of `condition` once the optimizer of the micro-batch optimizes a filter + // of the relation with it, none if it folds into true, or nothing if it folds into false. + def optimized(condition: Expression): Option[Seq[Expression]] = Try { + SQLConf.withExistingConf(optimizerConf) { + session.sessionState.optimizer.execute( Review Comment: Done in 03ab26e: the conjuncts that the optimizer returns for a pushed filter with the values are now cached by the canonicalized filter (`optimizedConditions`, at most 100 entries). The micro-batches of a query check the same filters with the same values, so they run the optimizer once, and its INFO lines about the excluded rules are logged once. The cache holds rewrites, which keep the meaning of the filters whatever the configuration, and the conditions of each micro-batch are still checked against them. The test of the unwrapped cast counts the plans that the check optimizes, with an `extraOptimizations` rule, over three micro-batches: the count stays at that of the first one. -- 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]
