You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2021/12/10 19:02:01 UTC

[GitHub] [spark] bersprockets commented on a change in pull request #34367: [SPARK-37099][SQL] Impl a rank-based filter to optimize top-k computation

bersprockets commented on a change in pull request #34367:
URL: https://github.com/apache/spark/pull/34367#discussion_r766913169



##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/window/RankLimitExec.scala
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.window
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.codegen._
+import org.apache.spark.sql.catalyst.plans.physical._
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.metric.SQLMetrics
+import org.apache.spark.util.collection.Utils
+
+
+sealed trait RankLimitMode
+
+case object Partial extends RankLimitMode
+
+case object Final extends RankLimitMode
+
+
+
+/**
+ * This operator is designed to filter out unnecessary rows before WindowExec,
+ * for top-k computation.
+ * @param partitionSpec Should be the same as [[WindowExec#partitionSpec]]
+ * @param orderSpec Should be the same as [[WindowExec#orderSpec]]
+ * @param rankFunction The function to compute row rank, should be RowNumber/Rank/DenseRank.
+ */
+case class RankLimitExec(
+    partitionSpec: Seq[Expression],
+    orderSpec: Seq[SortOrder],
+    rankFunction: Expression,
+    limit: Int,
+    mode: RankLimitMode,
+    child: SparkPlan) extends UnaryExecNode {
+  assert(orderSpec.nonEmpty && limit > 0)
+
+  private val shouldPass = child match {
+    case r: RankLimitExec =>
+      partitionSpec.size == r.partitionSpec.size &&
+        partitionSpec.zip(r.partitionSpec).forall(p => p._1.semanticEquals(p._2)) &&
+        orderSpec.size == r.orderSpec.size &&
+        orderSpec.zip(r.orderSpec).forall(o => o._1.semanticEquals(o._2)) &&
+        rankFunction.semanticEquals(r.rankFunction) &&
+        mode == Final && r.mode == Partial && limit == r.limit
+    case _ => false
+  }
+
+  private val shouldApplyTakeOrdered: Boolean = {
+    rankFunction match {
+      case _: RowNumber => limit < conf.topKSortFallbackThreshold
+      case _: Rank => false
+      case _: DenseRank => false
+      case f => throw new IllegalArgumentException(s"Unsupported rank function: $f")
+    }
+  }
+
+  override def output: Seq[Attribute] = child.output
+
+  override def requiredChildOrdering: Seq[Seq[SortOrder]] = {
+    if (shouldApplyTakeOrdered) {
+      Seq(partitionSpec.map(SortOrder(_, Ascending)))
+    } else {
+      // Should be the same as [[WindowExec#requiredChildOrdering]]
+      Seq(partitionSpec.map(SortOrder(_, Ascending)) ++ orderSpec)
+    }
+  }
+
+  override def outputOrdering: Seq[SortOrder] = {
+    partitionSpec.map(SortOrder(_, Ascending)) ++ orderSpec
+  }
+
+  override def requiredChildDistribution: Seq[Distribution] = mode match {
+    case Partial => super.requiredChildDistribution
+    case Final =>
+      // Should be the same as [[WindowExec#requiredChildDistribution]]
+      if (partitionSpec.isEmpty) {
+        AllTuples :: Nil
+      } else ClusteredDistribution(partitionSpec) :: Nil
+  }
+
+  override def outputPartitioning: Partitioning = child.outputPartitioning
+
+  override lazy val metrics = Map(
+    "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows"))
+
+  private lazy val ordering = GenerateOrdering.generate(orderSpec, output)
+
+  private lazy val limitFunction = rankFunction match {
+    case _: RowNumber if shouldApplyTakeOrdered =>
+      (stream: Iterator[InternalRow]) =>
+        Utils.takeOrdered(stream.map(_.copy()), limit)(ordering)

Review comment:
       By default, `spark.sql.execution.topKSortFallbackThreshold` is set to a pretty big number (Integer.MAX_VALUE - 15). Therefore, by default anyway, this line of code will attempt to do a sort with guava regardless of the size of the rank limit.
   
   For example, using your example [here](https://github.com/apache/spark/pull/34367#issuecomment-949516811), but changing the where clause to `col("rank") <= 1000000`, I get:
   
   ```
   java.lang.OutOfMemoryError: GC overhead limit exceeded
   ```
   
   Whereas I don't get that with `spark.sql.rankLimit.enabled=false`.
   
   If I set `spark.sql.execution.topKSortFallbackThreshold=10000`, it succeeds with `spark.sql.rankLimit.enabled=true`.
   
   Maybe it needs its own threshold? Or something to make users more aware (since it is not always super clear from the stack traces what was causing the OOMs).




-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org