dongjoon-hyun commented on code in PR #59929: URL: https://github.com/apache/spark/pull/59929#discussion_r4515193765
########## 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: **[2] A long chain of conjuncts on one column is still quadratic.** Following up on the [thread](https://github.com/apache/spark/pull/59929#discussion_r4469485218) about chains of ORs: `orAll` now merges the disjuncts at once, but `derive` still folds the conjuncts two at a time. `ids.map(v => col("id") =!= v).reduce(_ && _)`, or `!ids.map(v => col("id") === v).reduce(_ || _)`, which `BooleanSimplification` turns into the same conjuncts, reaches `derive` as one predicate for each value, each with the ranges `(-inf, v)` and `(v, +inf)`. The i-th `and` copies the i ranges accumulated so far with `toIndexedSeq` and sweeps them in `intersectRanges`, so N conjuncts take on the order of N^2 / 2 range steps, about 2 * 10^8 for 20,000 values, on the driver while it plans the query. `both(and, ...)` at L196-197 also recurses once for each level of a nested chain of ANDs, such as one under an OR. Could `derive` combine the constraints as a balanced tree, for example by intersecting the two halves of the sequence recursively, so that each range goes through about log N intersections, and could the test of long chains also cover a chain of `=!=`? ########## 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: **[3] Minor: Spark derives the domains and creates the reader before it checks whether the library has `push_domains`.** `ColumnarScanBuilder.pushPredicates` (ColumnarTable.scala:134-136) runs `ColumnDomains.derive` and then `batchPlanner`, which calls `create` and `create_reader` (L114-127), and only this line finds that a library built against an older header takes no domain. Before this PR, a filtered scan without a pushed limit created its reader only when it planned its partitions. With such a library, every filtered query, `explain()` included, now creates the reader during optimization, and an `IN` list of 100,000 values is sorted and turned into ranges only to be dropped. A JVM `ColumnarBatchPlanner` that keeps the default `pushDomains` pays the same. Could the data source say up front whether it takes domains, for example with a method of `ColumnarDataSource` that `NativeDataSource` answers with `hasFunction(PUSH_DOMAINS)`, so that `pushPredicates` returns the predicates without deriving anything otherwise? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala: ########## @@ -122,6 +129,26 @@ class ColumnarScanBuilder( planner } + override def pushPredicates(predicates: Array[Predicate]): Array[Predicate] = { Review Comment: **[5] Nit: `pushPredicates` relies on being called once.** The header promises that Spark calls `push_domains` at most once for a reader (spark_datasource.h:973-974), and `pushLimit` and `pruneColumns` keep their promises with `limitResult` and `pruned`. `pushPredicates` has no such state: Spark calls it once only because `supportsIterativePushdown` is false. A second call would call `push_domains` again and replace `pushed` and `usedDomains`, while `SupportsPushDownV2Filters` asks a builder to accumulate them. Could it throw an internal error on a second call, as `pruneColumns` does for columns that it does not read? ########## 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: **[1] `path` indexes the schema that `create_reader` got, but the docs call it the read schema.** `derive` gets the full `schema` of `ColumnarScanBuilder` (ColumnarTable.scala:134), the one that `batchPlanner`, and so `create_reader`, gets, and Spark prunes the columns only after the pushdown. But this line says "the read schema", which `ColumnarScan` (ColumnarTable.scala:199-200) uses for the pruned top-level columns. The other docs mix the two too: - sql-native-data-sources.md:249 says "the schema to read", which L124 of the guide defines as the columns that `prune_columns` got; - spark_datasource.h:401-402 says "the schema to read, the one that create_reader got", while `SparkDsReadInfo` (spark_datasource.h:580) calls the pruned columns the schema to read. spark_datasource.h:423-424 and the scaladoc of `NativeArrow.exportDomains` (NativeDataSource.scala:1537) use the same words for the types of the bounds. For example, with the columns `(id, name, value, ts)` and `SELECT id, value, ts ... WHERE value > 10`, the domain of `value` has the path `[2]`. A library that keeps the path in its state and applies it in `read` to the schema of `SparkDsReadInfo`, `(id, value, ts)`, skips data by the statistics of `ts`, and Spark cannot get those rows back. Could all of them say "the schema that create_reader got" instead? ########## 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) Review Comment: **[11] Nit: `ordering` is computed on every use.** `private def ordering` calls `PhysicalDataType.ordering(dataType)` each time: once for each range in `contains`, and once for each range in `toString`, which builds `PushedDomains`, for up to 100,000 ranges of an `IN` list. `Column` keeps the same ordering in a `val` (L138). Could this be a `@transient private lazy val`? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala: ########## @@ -1516,6 +1532,58 @@ object NativeArrow { } } + /** + * Exports the domains, with their ranges as struct arrays whose fields are low and high, of the + * Arrow type of the column in the exported schema to read, and low_inclusive and high_inclusive, + * and calls `f` with them. + * + * @param timeZoneId the time zone of the timestamps of the schema that the reader got + */ + def exportDomains[T](domains: Seq[ColumnDomain], timeZoneId: String)( + f: Seq[NativeLibrary.Domain] => T): T = { + val exported = ArrayBuffer.empty[(VectorSchemaRoot, ArrowArray, ArrowSchema)] + try { + val structs = domains.map { domain => + val (ranges, rangesSchema) = domain.ranges match { + case None => (0L, 0L) + case Some(values) => + val schema = StructType(Seq( + StructField("low", domain.dataType), + StructField("high", domain.dataType), + StructField("low_inclusive", BooleanType, nullable = false), + StructField("high_inclusive", BooleanType, nullable = false))) + val root = VectorSchemaRoot.create( + ArrowUtils.toArrowSchema( + schema, timeZoneId, errorOnDuplicatedFieldNames = true, largeVarTypes = false), + ArrowUtils.rootAllocator) + val array = ArrowArray.allocateNew(ArrowUtils.rootAllocator) + val arrowSchema = ArrowSchema.allocateNew(ArrowUtils.rootAllocator) + exported += ((root, array, arrowSchema)) Review Comment: **[6] Nit: the ranges go into `exported` only after all their allocations.** If `ArrowSchema.allocateNew` at L1560 throws, the `ArrowArray` of L1559 and the root of L1555 are not in `exported` yet, so the `finally` closes neither, and `ArrowUtils.rootAllocator` keeps the memory of the `ArrowArray`. Could each of them be added to the cleanup right after it is allocated? ########## 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] = { Review Comment: **[9] Nit: `pushedPredicates` relies on getting the same array as `derive`.** `columns` is parallel to the predicates that `derive` got, and `pushedPredicates(predicates, used)` zips it with the array that its caller passes again (ColumnarTable.scala:142). Another array, or the same predicates in another order, would show the wrong predicates as pushed without any error. Could `ColumnDomains` keep the predicates with their columns, so that `pushedPredicates` only takes `used`? ########## 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 { + case Some(values) => + values.toSeq.collect { + // A field of a struct is null in the rows where the struct, or a struct that contains it, + // is null, which the statistics of its Arrow child array may not count as nulls. So a + // field only gets a domain without null, which these rows never match. + case (column, v) if column.path.length == 1 || !v.nullAllowed => + ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed, + v.ranges) + }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int]) + // A predicate that is always false, which Spark usually removes before it scans the data. + case None => Nil + } + ColumnDomains(domains, columns) + } + + // The rows for which the predicate is true, or false if negated: NOT moves to the leaves. + private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = { + def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect { + case p: Predicate => p + } + def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = { + (child(0), child(1)) match { + case (Some(left), Some(right)) => + combine(constraint(left, negated, schema), constraint(right, negated, schema)) + case _ => All + } + } + predicate.name() match { + // The disjuncts of a chain of ORs, such as one that the DataFrame API builds with + // reduce(_ || _), are merged at once rather than two at a time. + case "AND" if negated => orAll(disjuncts(predicate, negated).map { Review Comment: **[4] Minor: an OR whose children are not two predicates makes `constraint` recurse until the stack overflows.** For an `OR`, or a negated `AND`, with fewer than two `Predicate` children, such as `new Predicate("OR", Array[Expression](FieldReference("a"), FieldReference("b")))`, `disjuncts` returns the predicate itself (the `case _` at L223). `orAll` then calls `constraint` on it with the same `negated`, which calls `disjuncts` again, until `StackOverflowError`. The `V2Or` and `V2And` that Spark translates always have two predicates, so only a `Predicate` built directly through the public API gets here, but `both` handles the same shape with `case _ => All` (L184). Could these cases return `All` too, for example when `disjuncts` gives back only the predicate itself? ########## docs/sql-native-data-sources.md: ########## @@ -237,13 +238,68 @@ I/O, should check `is_interrupted` regularly and use timeouts. The task reaper, `spark.task.reaper.enabled` and `spark.task.reaper.killTimeout`, kills an executor whose killed task does not end. +### Filter Pushdown + +Spark does not pass the filters of a query to a library as expressions, which a library would have +to evaluate with the exact semantics of Spark SQL. It passes the *domains* of the columns that the +filters constrain instead: for each column, the values that it can have in the rows that match, +which a library compares with the statistics of its data to skip what cannot match, such as files, +row groups or blocks. With `push_domains`, a reader gets a `SparkDsDomain` for each column, with: Review Comment: **[7] Nit: a reader does not get a `SparkDsDomain` for each column.** L244-245 and L277-281 make it clear in context, but read alone, "a reader gets a `SparkDsDomain` for each column" says all the columns of the scan, while a reader only gets the domains of the columns that the filters constrain, of the types that Spark compares, as spark_datasource.h:969-975 says. Could this say "for each column that the filters constrain"? ########## 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 { + case Some(values) => + values.toSeq.collect { + // A field of a struct is null in the rows where the struct, or a struct that contains it, + // is null, which the statistics of its Arrow child array may not count as nulls. So a + // field only gets a domain without null, which these rows never match. + case (column, v) if column.path.length == 1 || !v.nullAllowed => + ColumnDomain(column.path, column.name, column.dataType, v.nullAllowed, v.nanAllowed, + v.ranges) + }.sortBy(_.path)(Ordering.Implicits.seqOrdering[Seq, Int]) + // A predicate that is always false, which Spark usually removes before it scans the data. + case None => Nil + } + ColumnDomains(domains, columns) + } + + // The rows for which the predicate is true, or false if negated: NOT moves to the leaves. + private def constraint(predicate: Predicate, negated: Boolean, schema: StructType): Constraint = { + def child(i: Int): Option[Predicate] = predicate.children().lift(i).collect { + case p: Predicate => p + } + def both(combine: (Constraint, Constraint) => Constraint, negated: Boolean): Constraint = { + (child(0), child(1)) match { + case (Some(left), Some(right)) => + combine(constraint(left, negated, schema), constraint(right, negated, schema)) + case _ => All + } + } + predicate.name() match { + // The disjuncts of a chain of ORs, such as one that the DataFrame API builds with + // reduce(_ || _), are merged at once rather than two at a time. + case "AND" if negated => orAll(disjuncts(predicate, negated).map { + case (disjunct, disjunctNegated) => constraint(disjunct, disjunctNegated, schema) + }) + case "OR" if !negated => orAll(disjuncts(predicate, negated).map { + case (disjunct, disjunctNegated) => constraint(disjunct, disjunctNegated, schema) + }) + case "AND" => both(and, negated = false) + case "OR" => both(and, negated = true) + case "NOT" => child(0).map(constraint(_, !negated, schema)).getOrElse(All) + case "ALWAYS_TRUE" => if (negated) NoRow else All + case "ALWAYS_FALSE" => if (negated) All else NoRow + case _ => leaf(predicate, negated, schema).getOrElse(All) + } + } + + /** + * Returns the disjuncts of a predicate that is a disjunction, an OR or a negated AND, with the + * disjunctions that it nests, under NOT too, as the predicates and whether they are negated, in + * their order. It walks the predicate with a stack of its own, since a chain of ORs can be deeper + * than the stack of the thread. + */ + private def disjuncts(predicate: Predicate, negated: Boolean): Seq[(Predicate, Boolean)] = { + val result = mutable.ArrayBuffer.empty[(Predicate, Boolean)] + val pending = mutable.Stack(predicate -> negated) + while (pending.nonEmpty) { + val (next, isNegated) = pending.pop() + val children = next.children().toSeq.collect { case p: Predicate => p } + next.name() match { + case "OR" | "AND" if children.length == 2 && (next.name() == "OR") != isNegated => + // The left child is visited first. + pending.push(children(1) -> isNegated) + pending.push(children(0) -> isNegated) + case "NOT" if children.length == 1 => pending.push(children.head -> !isNegated) + case _ => result += next -> isNegated + } + } + result.toSeq + } + + private def leaf( + predicate: Predicate, + negated: Boolean, + schema: StructType): Option[Constraint] = { + val children = predicate.children() + predicate.name() match { + case "IS_NULL" | "IS_NOT_NULL" if children.length == 1 => + column(children(0), schema).map { col => + val isNull = (predicate.name() == "IS_NULL") != negated + single(col, if (isNull) OnlyNull else anyValue(col)) + } + case op @ ("=" | "<>" | "<=>" | "<" | "<=" | ">" | ">=") if children.length == 2 => + val operands = (column(children(0), schema), column(children(1), schema)) match { + case (Some(col), _) => literal(children(1), col).map((col, _, op)) + case (_, Some(col)) => literal(children(0), col).map((col, _, flip(op))) + case _ => None + } + operands.map { case (col, value, op) => compare(col, value, op, negated) } + case "IN" if children.nonEmpty => + column(children(0), schema).flatMap { col => + val values = children.tail.map(literal(_, col)) + if (values.forall(_.isDefined)) Some(in(col, values.map(_.get).toSeq, negated)) else None + } + case "STARTS_WITH" if children.length == 2 => + column(children(0), schema).filter(_.dataType.isInstanceOf[StringType]).flatMap { col => + literal(children(1), col).map(prefix => startsWith(col, prefix, negated)) + } + case _ => None + } + } + + private def flip(op: String): String = op match { + case "<" => ">" + case "<=" => ">=" + case ">" => "<" + case ">=" => "<=" + case other => other + } + + private def compare(column: Column, value: Any, op: String, negated: Boolean): Constraint = { + // NOT (x <=> v) is true for null, unless v is null. + val nullAllowed = op == "<=>" && negated && value != null + if (value == null) { + // A comparison with null is null, and so is its negation, but x <=> NULL is x IS NULL. + if (op == "<=>") single(column, if (negated) anyValue(column) else OnlyNull) + else single(column, NoValue) + } else if (isNaN(value)) { + // NaN is equal to NaN and greater than any other value: (NaN, other values). + val (nan, others) = (op, negated) match { + case ("=" | "<=>" | ">=", false) | ("<>" | "<", true) => (true, Some(Nil)) + case ("=" | "<=>" | ">=", true) | ("<>" | "<", false) => (false, None) + case ("<=", false) | (">", true) => (true, None) + case ("<=", true) | (">", false) => (false, Some(Nil)) + case _ => throw SparkException.internalError(s"Unexpected comparison $op.") + } + single(column, Values(nullAllowed, nan, others)) + } else { + val v = normalize(value) + // NaN is greater than v, and not equal to it. + val (nan, ranges) = (op, negated) match { + case ("=" | "<=>", false) | ("<>", true) => (false, Seq(point(v))) + case ("=" | "<=>", true) | ("<>", false) => + (true, Seq(below(v, inclusive = false), above(v, inclusive = false))) + case ("<", false) | (">=", true) => (false, Seq(below(v, inclusive = false))) + case ("<=", false) | (">", true) => (false, Seq(below(v, inclusive = true))) + case (">", false) | ("<=", true) => (true, Seq(above(v, inclusive = false))) + case (">=", false) | ("<", true) => (true, Seq(above(v, inclusive = true))) + case _ => throw SparkException.internalError(s"Unexpected comparison $op.") + } + single(column, Values(nullAllowed, nan, Some(ranges))) + } + } + + private def in(column: Column, values: Seq[Any], negated: Boolean): Constraint = { + val nonNull = values.filter(_ != null) + val hasNaN = nonNull.exists(isNaN) + val points = nonNull.filterNot(isNaN).map(normalize).sorted(column.ordering) + .foldLeft(List.empty[Any]) { + case (last :: rest, v) if column.ordering.equiv(last, v) => last :: rest + case (acc, v) => v :: acc + }.reverse + if (values.isEmpty) { + // x IN () is false, also for null, unless spark.sql.legacy.nullInEmptyListBehavior makes it + // null for null. So it is never true, and NOT (x IN ()) is true for any value, and by + // default for null. + if (negated) All else single(column, NoValue) + } else if (!negated) { + single(column, Values(nullAllowed = false, hasNaN, Some(points.map(point)))) + } else if (nonNull.length < values.length) { + // NOT (x IN (..., NULL)) is never true: it is false or null. + single(column, NoValue) + } else if (points.isEmpty) { + // NOT (x IN (NaN)) is true for the values other than NaN. + single(column, Values(nullAllowed = false, !hasNaN, None)) + } else { + // The values between the points. + val bounds = None +: points.map(Some(_)) :+ None + val gaps = bounds.zip(bounds.tail).map { case (low, high) => + ValueRange(low, lowInclusive = false, high = high, highInclusive = false) + } + single(column, Values(nullAllowed = false, !hasNaN, Some(gaps))) + } + } + + private def startsWith(column: Column, prefix: Any, negated: Boolean): Constraint = { + (prefix, negated) match { + case (null, _) => single(column, NoValue) + // The strings that do not start with the prefix are not a range. A value whose bytes are not + // valid UTF-8 could even be in the range of the strings that do. + case (_, true) => single(column, anyValue(column)) + case (prefix: UTF8String, false) if prefix.numBytes() == 0 => single(column, anyValue(column)) + case (prefix: UTF8String, false) => + val range = ValueRange(Some(prefix), lowInclusive = true, high = nextPrefix(prefix), + highInclusive = false) + single(column, Values(nullAllowed = false, nanAllowed = false, Some(Seq(range)))) + case _ => All + } + } + + /** + * Returns the smallest string that is greater than all the strings that start with the prefix, + * in the order of their UTF-8 bytes, which is the order of their code points, or None if there + * is none: the prefix with its last code point incremented, after dropping the trailing + * U+10FFFF, the largest code point. + */ + private[columnar] def nextPrefix(prefix: UTF8String): Option[UTF8String] = { + val codePoints = prefix.toString.codePoints().toArray.toBuffer + while (codePoints.nonEmpty && codePoints.last == Character.MAX_CODE_POINT) { + codePoints.remove(codePoints.length - 1) + } + if (codePoints.isEmpty) { + None + } else { + val last = codePoints.last + 1 + // Skips the surrogates, which are not code points of characters. + codePoints(codePoints.length - 1) = + if (last >= Character.MIN_SURROGATE && last <= Character.MAX_SURROGATE) { + Character.MAX_SURROGATE + 1 + } else { + last + } + Some(UTF8String.fromString(new String(codePoints.toArray, 0, codePoints.length))) + } + } + + private def single(column: Column, values: Values): Constraint = { + // Only floating-point columns have NaN. + val normalized = values.copy(nanAllowed = values.nanAllowed && column.isFloating) + if (isAll(column, normalized)) All else Some(Map(column -> normalized)) + } + + private def point(v: Any): ValueRange = + ValueRange(Some(v), lowInclusive = true, high = Some(v), highInclusive = true) + + private def below(v: Any, inclusive: Boolean): ValueRange = + ValueRange(None, lowInclusive = false, high = Some(v), highInclusive = inclusive) + + private def above(v: Any, inclusive: Boolean): ValueRange = + ValueRange(Some(v), lowInclusive = inclusive, high = None, highInclusive = false) + + private def anyValue(column: Column): Values = { + Values(nullAllowed = false, nanAllowed = column.isFloating, None) + } + + private def isAll(column: Column, values: Values): Boolean = { + values.nullAllowed && values.ranges.isEmpty && (values.nanAllowed || !column.isFloating) + } + + private def isEmpty(values: Values): Boolean = { + !values.nullAllowed && !values.nanAllowed && values.ranges.exists(_.isEmpty) + } + + // Whether no row can make the predicates true. + private def matchesNoRow(constraint: Constraint): Boolean = { + constraint.forall(_.values.exists(isEmpty)) + } + + private def and(left: Constraint, right: Constraint): Constraint = (left, right) match { + case (Some(l), Some(r)) => + // Through an iterator, so that only the columns are hashed, not their values. + Some((l.keySet ++ r.keySet).iterator.map { column => + column -> ((l.get(column), r.get(column)) match { + case (Some(a), Some(b)) => intersect(column, a, b) + case (a, b) => a.orElse(b).get + }) + }.toMap) + case _ => NoRow + } + + // A column that only some of the disjuncts constrain can have any value in the rows of the + // others, so only the columns that all of them constrain are constrained. A disjunct that matches + // no row adds no row. + private def orAll(disjuncts: Seq[Constraint]): Constraint = { + disjuncts.filterNot(matchesNoRow) match { + case Seq() => disjuncts.lastOption.getOrElse(NoRow) + case Seq(only) => only + case matching => + val values = matching.map(_.get) + val columns = values.map(_.keySet).reduce(_ intersect _) + Some(columns.iterator.map(column => column -> union(column, values.map(_(column)))) + .filterNot { case (column, v) => isAll(column, v) }.toMap) + } + } + + private def intersect(column: Column, a: Values, b: Values): Values = Values( + a.nullAllowed && b.nullAllowed, + a.nanAllowed && b.nanAllowed, + (a.ranges, b.ranges) match { + case (Some(x), Some(y)) => Some(intersectRanges(x, y, column.ordering)) + case (x, y) => x.orElse(y) + }) + + private def union(column: Column, all: Seq[Values]): Values = Values( + all.exists(_.nullAllowed), + all.exists(_.nanAllowed), + if (all.forall(_.ranges.isDefined)) { + unionRanges(all.flatMap(_.ranges.get), column.ordering) match { + // All the values. + case Seq(ValueRange(None, _, None, _)) => None + case ranges => Some(ranges) + } + } else { + None + }) + + // A negative value when `a` starts before `b`. + private def compareLows(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = { + (a.low, b.low) match { + case (None, None) => 0 + case (None, _) => -1 + case (_, None) => 1 + case (Some(x), Some(y)) => + val c = ordering.compare(x, y) + if (c != 0 || a.lowInclusive == b.lowInclusive) c else if (a.lowInclusive) -1 else 1 + } + } + + // A negative value when `a` ends before `b`. + private def compareHighs(a: ValueRange, b: ValueRange, ordering: Ordering[Any]): Int = { + (a.high, b.high) match { + case (None, None) => 0 + case (None, _) => 1 + case (_, None) => -1 + case (Some(x), Some(y)) => + val c = ordering.compare(x, y) + if (c != 0 || a.highInclusive == b.highInclusive) c else if (a.highInclusive) 1 else -1 + } + } + + private def isEmptyRange(range: ValueRange, ordering: Ordering[Any]): Boolean = { + (range.low, range.high) match { + case (Some(low), Some(high)) => + val c = ordering.compare(low, high) + c > 0 || (c == 0 && !(range.lowInclusive && range.highInclusive)) + case _ => false + } + } + + // Intersects two lists of sorted ranges that neither overlap nor touch, by sweeping them. + private def intersectRanges( + left: Seq[ValueRange], + right: Seq[ValueRange], + ordering: Ordering[Any]): Seq[ValueRange] = { + // The ranges are usually lists, such as those of IN, so the sweep indexes copies of them. + val (a, b) = (left.toIndexedSeq, right.toIndexedSeq) + val result = ArrayBuffer.empty[ValueRange] + var i = 0 + var j = 0 + while (i < a.length && j < b.length) { + val (x, y) = (a(i), b(j)) + val low = if (compareLows(x, y, ordering) >= 0) x else y + val high = if (compareHighs(x, y, ordering) <= 0) x else y + val range = ValueRange(low.low, low.lowInclusive, high.high, high.highInclusive) + if (!isEmptyRange(range, ordering)) { + result += range + } + // Moves past the range that ends first. + if (compareHighs(x, y, ordering) <= 0) i += 1 else j += 1 + } + result.toSeq + } + + // Merges ranges, sorted by their lows, and the ranges that overlap or touch, such as [1, 2) and + // [2, 3]. + private def unionRanges(ranges: Seq[ValueRange], ordering: Ordering[Any]): Seq[ValueRange] = { + def touches(first: ValueRange, next: ValueRange): Boolean = (first.high, next.low) match { + case (Some(high), Some(low)) => + val c = ordering.compare(low, high) + c < 0 || (c == 0 && (first.highInclusive || next.lowInclusive)) + case _ => true + } + ranges.sortWith(compareLows(_, _, ordering) < 0).foldLeft(List.empty[ValueRange]) { + case (last :: rest, range) if touches(last, range) => + val high = if (compareHighs(last, range, ordering) >= 0) last else range + last.copy(high = high.high, highInclusive = high.highInclusive) :: rest + case (merged, range) => range :: merged + }.reverse + } + + // The column of a reference, if it has a type that a data source can compare. + private def column(expression: Expression, schema: StructType): Option[Column] = { + expression match { + case reference: NamedReference => + val names = reference.fieldNames().toSeq + names.foldLeft(Option((Seq.empty[Int], schema: DataType))) { + case (Some((path, struct: StructType)), name) => + val index = struct.fieldNames.indexOf(name) + if (index < 0) None else Some((path :+ index, struct.fields(index).dataType)) + case _ => None + }.collect { + case (path, dataType) if names.nonEmpty && isComparable(dataType) => + Column(path, names, dataType) + } + case _ => None + } + } + + private def isComparable(dataType: DataType): Boolean = dataType match { + case BooleanType | ByteType | ShortType | IntegerType | LongType | FloatType | DoubleType | + _: DecimalType | BinaryType | DateType | TimestampType | TimestampNTZType => true + // A data source compares strings by their UTF-8 bytes. + case s: StringType => s.isUTF8BinaryCollation + case _ => false + } + + /** + * The value of a literal of the type of the column, or null, as Some. None for another + * expression, a literal of another type, or a string that is not valid UTF-8, which an Arrow + * array of strings cannot hold. + */ + private def literal(expression: Expression, column: Column): Option[Any] = expression match { + case LiteralValue(null, _) => Some(null) + case LiteralValue(value: UTF8String, dataType) if dataType == column.dataType => + if (value.isValid) Some(value) else None + case LiteralValue(value, dataType) if dataType == column.dataType => Some(value) + case _ => None + } + + private def isNaN(value: Any): Boolean = value match { + case f: Float => f.isNaN + case d: Double => d.isNaN + case _ => false + } + + // -0.0 is equal to 0.0, and a data source may order it before 0.0. + private def normalize(value: Any): Any = value match { Review Comment: **[10] Nit: `NormalizeFloatingNumbers` already has this.** `NormalizeFloatingNumbers.FLOAT_NORMALIZER` and `DOUBLE_NORMALIZER` turn -0.0 into 0.0 too, and NaN into the canonical NaN, which does not matter here, since NaN never reaches `normalize`. Could `normalize` use them, for example `case f: Float => NormalizeFloatingNumbers.FLOAT_NORMALIZER(f)`? -- 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]
