HyukjinKwon commented on code in PR #59929: URL: https://github.com/apache/spark/pull/59929#discussion_r4515572163
########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala: ########## @@ -0,0 +1,579 @@ +/* + * 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.datasources.v2.columnar + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.Literal +import org.apache.spark.sql.catalyst.types.PhysicalDataType +import org.apache.spark.sql.catalyst.util.quoteIfNeeded +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference} +import org.apache.spark.sql.connector.expressions.filter.Predicate +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +/** + * The values that a column can have in the rows that match the filters of a query: null if + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics + * show that it has no value in the domain of a column, but never a row whose values are in their + * domains: Spark evaluates the filters after reading anyway. + * + * @param path the index of the column in the read schema, and then the index of the field in each Review Comment: Done in 3f7f56e, as you suggest. The domain docs now say "the schema that create_reader got", not "the read schema" or "the schema to read": - the `path` of `SparkDsDomain` in `spark_datasource.h`, which also says that Spark prunes the columns after it pushes the domains down, so the schema to read in `SparkDsReadInfo` may have fewer columns, at other indices, and a library that applies a domain in `read` must map its column to that schema; - the bounds of its `ranges`; - the `path` of the guide, with the same note; - the scaladoc of `ColumnDomain.path`, which names the schema that the planner got from `ColumnarDataSource.batchPlanner`; - the scaladoc of `NativeArrow.exportDomains`. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnDomains.scala: ########## @@ -0,0 +1,579 @@ +/* + * 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.datasources.v2.columnar + +import scala.collection.mutable +import scala.collection.mutable.ArrayBuffer + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.Literal +import org.apache.spark.sql.catalyst.types.PhysicalDataType +import org.apache.spark.sql.catalyst.util.quoteIfNeeded +import org.apache.spark.sql.connector.expressions.{Expression, LiteralValue, NamedReference} +import org.apache.spark.sql.connector.expressions.filter.Predicate +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +/** + * The values that a column can have in the rows that match the filters of a query: null if + * `nullAllowed`, NaN if `nanAllowed`, for a float or double column, and the other values in one + * of the `ranges`, or any of them without ranges. A data source can skip the data whose statistics + * show that it has no value in the domain of a column, but never a row whose values are in their + * domains: Spark evaluates the filters after reading anyway. + * + * @param path the index of the column in the read schema, and then the index of the field in each + * struct, for a field of a struct + * @param name the names of the column and of its fields + * @param ranges sorted ranges, which neither overlap nor touch, of the values other than null and + * NaN, in the internal representation of Spark. None if the column can have any of + * them, and empty if it can have none. + */ +case class ColumnDomain( + path: Seq[Int], + name: Seq[String], + dataType: DataType, + nullAllowed: Boolean, + nanAllowed: Boolean, + ranges: Option[Seq[ValueRange]]) { + + private def ordering: Ordering[Any] = PhysicalDataType.ordering(dataType) + + /** Whether the domain has the value, in the internal representation of Spark. */ + def contains(value: Any): Boolean = value match { + case null => nullAllowed + case f: Float if f.isNaN => nanAllowed + case d: Double if d.isNaN => nanAllowed + case _ => ranges.forall(_.exists(_.contains(value, ordering))) + } + + override def toString: String = { + def literal(value: Any): String = Literal(value, dataType).sql + val values = ranges match { + case None => Seq("ANY") + case Some(ranges) => ranges.map { + case ValueRange(Some(low), true, Some(high), true) if ordering.equiv(low, high) => + literal(low) + case range => + (if (range.lowInclusive) "[" else "(") + range.low.map(literal).getOrElse("-inf") + + ", " + range.high.map(literal).getOrElse("+inf") + + (if (range.highInclusive) "]" else ")") + } + } + val special = (if (nullAllowed) Seq("NULL") else Nil) ++ (if (nanAllowed) Seq("NaN") else Nil) + val all = special ++ values + s"${name.map(quoteIfNeeded).mkString(".")}: ${if (all.isEmpty) "NONE" else all.mkString(", ")}" + } +} + +/** + * A range of values in the internal representation of Spark: the values above `low`, or equal to + * it if `lowInclusive`, and below `high`, or equal to it if `highInclusive`. A bound that is None + * is unbounded, and is not inclusive. + */ +case class ValueRange(low: Option[Any], lowInclusive: Boolean, high: Option[Any], + highInclusive: Boolean) { + + def contains(value: Any, ordering: Ordering[Any]): Boolean = { + low.forall { l => + val c = ordering.compare(value, l) + c > 0 || (c == 0 && lowInclusive) + } && high.forall { h => + val c = ordering.compare(value, h) + c < 0 || (c == 0 && highInclusive) + } + } +} + +/** + * The domains that a query passes to a data source, and the predicates that each of them comes + * from. + * + * @param domains the domains, at most one for each column, sorted by path + * @param columns the paths of the columns that each predicate constrains + */ +case class ColumnDomains(domains: Seq[ColumnDomain], columns: Seq[Set[Seq[Int]]]) { + + /** + * Returns the predicates that constrain only the columns whose domains are used, given whether + * the data source uses each domain. + */ + def pushedPredicates(predicates: Array[Predicate], used: Seq[Boolean]): Array[Predicate] = { + val usedPaths = domains.zip(used).collect { case (domain, true) => domain.path }.toSet + predicates.zip(columns).collect { + case (predicate, paths) if paths.nonEmpty && paths.subsetOf(usedPaths) => predicate + } + } +} + +/** + * Derives the domains of the columns that the predicates of a query constrain, the ones that Data + * Source V2 pushes to a scan, combined with AND. A domain is a superset of the values that a column + * has in the rows for which all the predicates are true: Spark derives it from the comparisons of + * a column with literals, IN, IS NULL, IS NOT NULL and STARTS_WITH, under AND, OR and NOT, with the + * semantics of Spark SQL. Comparisons with null are null, NaN is equal to NaN and greater than any + * other value, -0.0 is equal to 0.0, and strings and binary values are compared by their bytes, as + * unsigned bytes. A predicate that cannot be expressed this way does not constrain any column. Only + * the columns and the fields of structs of the types that a data source can compare get a domain: + * not the strings of a non-binary collation, nor arrays, maps and structs. A field of a struct only + * gets a domain that does not have null. + */ +object ColumnDomains { + + // A column that a predicate constrains, with its type. + private case class Column(path: Seq[Int], name: Seq[String], dataType: DataType) { + val ordering: Ordering[Any] = PhysicalDataType.ordering(dataType) + val isFloating: Boolean = dataType == FloatType || dataType == DoubleType + } + + // The values that a column can have: see ColumnDomain. + private case class Values(nullAllowed: Boolean, nanAllowed: Boolean, + ranges: Option[Seq[ValueRange]]) + + private val NoValue = Values(nullAllowed = false, nanAllowed = false, Some(Nil)) + private val OnlyNull = Values(nullAllowed = true, nanAllowed = false, Some(Nil)) + + // The columns that the predicates constrain, with their values: a row can only make the + // predicates true if each of these columns has one of the values. None when no row can. + private type Constraint = Option[Map[Column, Values]] + private val All: Constraint = Some(Map.empty) + private val NoRow: Constraint = None + + /** Derives the domains of the predicates for a scan of the schema. */ + def derive(predicates: Seq[Predicate], schema: StructType): ColumnDomains = { + val constraints = predicates.map(constraint(_, negated = false, schema)) + val columns = constraints.map(_.map(_.keySet.map(_.path)).getOrElse(Set.empty[Seq[Int]])) + val domains = constraints.foldLeft(All)(and) match { Review Comment: Done in 3f7f56e. The new `andAll` intersects the constraints as a balanced tree: it intersects the two halves recursively, so the ranges of each constraint go through about log N intersections. `derive` uses it for the predicates that it gets, and `constraint` uses it for a chain of ANDs. `constraint` no longer recurses for each level of a chain of ANDs. `disjuncts` became `operands`, which collects the operands of a conjunction (an AND or a negated OR) as well as of a disjunction (an OR or a negated AND) with a stack of its own, so a chain under an OR is walked once too. The new test "the domains of long chains of ANDs" checks 50,000 conjuncts of `id <> v` in four forms, each giving the same 50,001 gaps as `NOT (id IN (...))`, within 20 seconds: - as separate predicates; - as one chain of ANDs; - as `NOT` of a chain of ORs of `id = v`; - as a chain of ANDs under an OR. It takes about 0.75 s. With the fold back in `derive` and `constraint`, it fails. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala: ########## @@ -278,6 +281,19 @@ class NativeBatchPlanner( private var readSchema: StructType = schema + override def pushDomains(domains: Seq[ColumnDomain]): Seq[Boolean] = { + // The table of a library built against a header without push_domains ends before it. + if (!library.hasFunction(NativeLibrary.Function.PUSH_DOMAINS)) { Review Comment: Done in 3f7f56e, as you suggest. `ColumnarDataSource` has a new method, `supportsDomainPushdown()`, false by default. `NativeDataSource` answers it with `hasFunction(PUSH_DOMAINS)`. `pushPredicates` only derives the domains, and only creates the planner of the scan, when it is true, so a library built against an older header, and a JVM data source that keeps the default `pushDomains`, pay nothing during optimization. The check in `NativeBatchPlanner.pushDomains` is gone, and the scaladoc of `ColumnarBatchPlanner.pushDomains` says that Spark only calls it for such a data source. Tests: - "push no domain to a library built against a header without push_domains" now also reads with the option `zero` set to `create_reader`: the optimized plan builds, and only the read fails with "create_reader returned a NULL handle."; - the new "push the predicates of a scan once, to a data source that takes domains" checks that a JVM data source that takes no domain gets no planner before the scan plans its partitions. -- 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]
