HyukjinKwon commented on code in PR #59929:
URL: https://github.com/apache/spark/pull/59929#discussion_r4515574077


##########
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:
   Done in 3f7f56e. `constraint` now returns `All` for an AND or an OR whose 
children are not exactly two predicates. Inside a chain, `operands` only splits 
such nodes, so a malformed one becomes an operand, which then constrains no 
column. The new test "an AND or an OR whose children are not two predicates 
constrains no column" covers these, without a `StackOverflowError`:
   - an AND and an OR of two `FieldReference`s, and their negations;
   - an AND and an OR of a single predicate;
   - a malformed predicate next to `id > 5` in an AND, which keeps the domain 
of `id`, and in an OR.



##########
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:
   Done in 3f7f56e. A second `pushPredicates` throws an internal error, "The 
predicates of a scan were pushed again.", before it calls `push_domains`, as 
`pruneColumns` does for columns that the scan does not read. The new test "push 
the predicates of a scan once, to a data source that takes domains" checks it, 
and that the first push stays.



##########
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:
   Done in 3f7f56e. `exportDomains` now registers the cleanup of each root, 
`ArrowArray` and `ArrowSchema` right after it is allocated, and runs them in 
the reverse order in the `finally`, so an allocation that fails frees the ones 
before it. The ranges are still released before their root is closed, as before.



-- 
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]

Reply via email to