spark-test commented on code in PR #60519:
URL: https://github.com/apache/spark/pull/60519#discussion_r4581668106
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -91,6 +93,274 @@ case class WindowGroupLimitExec(
}
}
+ // RowNumber, Rank and DenseRank are all wired up for codegen (see
`doConsume`); any future
+ // rank-like function defaults to the interpreted path above
(`WindowGroupLimitEvaluatorFactory`)
+ // by falling through to `false` here.
+ override def supportCodegen: Boolean = rankLikeFunction match {
+ case _: RowNumber | _: Rank | _: DenseRank => true
+ case _ => false
+ }
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
child.asInstanceOf[CodegenSupport].inputRDDs()
+
+ // This operator neither materializes nor reorders columns itself, so let
every column stay
+ // lazy until a downstream operator actually needs it, the same way
`FilterExec` does. Only the
+ // `partitionSpec`/`orderSpec` columns (if any) end up evaluated, by
`genKeyChangeCode`.
+ override def usedInputs: AttributeSet = AttributeSet.empty
+
+ protected override def doProduce(ctx: CodegenContext): String = {
+ child.asInstanceOf[CodegenSupport].produce(ctx, this)
+ }
+
+ override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row:
ExprCode): String = {
+ rankLikeFunction match {
+ case _: RowNumber => doConsumeRowNumber(ctx, input)
+ case _: Rank => doConsumeRank(ctx, input)
+ case _: DenseRank => doConsumeDenseRank(ctx, input)
+ case other =>
+ // Unreachable: `supportCodegen` keeps any other rank-like function
off the codegen path.
+ throw SparkException.internalError(
+ s"Codegen for rank-like function $other is not supported in
WindowGroupLimitExec.")
+ }
+ }
+
+ /**
+ * Projects `keyExprs` (bound against `child.output`) into a fresh
`UnsafeRow`, returning the
+ * code that computes it (to be emitted by the caller) together with the
Java expression that
+ * reads the resulting row. Evaluating a key this way -- rather than through
`genKeyChangeCode`
+ * below, which also does the comparison -- is for cases where the
evaluation must happen before
+ * a `consume()` call but the comparison/branch may happen after it; see the
order-key handling
+ * in `doConsumeRank`/`doConsumeDenseRank`.
+ *
+ * The returned code MUST be emitted, in the generated method, before any
`consume()` call for
+ * the same row. `usedInputs` is empty (columns stay lazy), so these
columns' evaluation code is
+ * still attached to `input` here; `evaluateRequiredVariables` evaluates and
clears it. Skipping
+ * that, or running it after `consume(ctx, input)`, would duplicate the
work: `consume()`
+ * evaluates and clears the columns `input` owes on its own internal copy of
`input` (see its
+ * `outputVars.map(_.copy())`), leaving `input`'s original `ExprCode`s --
the ones this method
+ * reads -- still holding their unclaimed evaluation code, which
`GenerateUnsafeProjection` would
+ * then copy as-is (`BoundReference.doGenCode` copies but does not clear a
source `ExprCode`'s
+ * code), re-running the same expression a second time. For a
non-deterministic expression (e.g.
+ * `ORDER BY rand()`) that would let the materialized output row and the
value used for this
+ * projection disagree, not just waste cycles.
+ */
+ private def genKeyProjection(
+ ctx: CodegenContext,
+ input: Seq[ExprCode],
+ keyExprs: Seq[Expression]): (String, String) = {
+ val requiredAttrs = AttributeSet(keyExprs.flatMap(_.references))
+ val evaluateCols = evaluateRequiredVariables(child.output, input,
requiredAttrs)
+ val keyCode = GenerateUnsafeProjection.createCode(ctx,
bindReferences(keyExprs, child.output))
+ (s"$evaluateCols\n${keyCode.code}", keyCode.value.toString)
+ }
+
+ /**
+ * Generates the code that compares an already-projected key (`keyValue`,
from
+ * `genKeyProjection`) against the mutable `UnsafeRow` snapshot of the
previous row's key
+ * (`keyTerm`), and runs `onChange` whenever they differ, per `isDifferent`
(e.g. `!a.equals(b)`,
+ * or an `Ordering.compare(a, b) != 0`). `onChange` does not run for the
very first row seen
+ * (there is nothing to compare against yet, matching `BaseLimitIterator`'s
subclasses, which
+ * only initialize their tracking state then).
+ */
+ private def genKeyChangeBranch(
+ keyTerm: String,
+ keyValue: String,
+ isDifferent: (String, String) => String,
+ onChange: String): String = {
+ s"""
+ |if ($keyTerm == null) {
+ | $keyTerm = ($keyValue).copy();
+ |} else if (${isDifferent(keyTerm, keyValue)}) {
+ | $onChange
+ | $keyTerm = ($keyValue).copy();
+ |}
+ """.stripMargin
+ }
+
+ /**
+ * `genKeyProjection` followed immediately by `genKeyChangeBranch` against
its result -- for
+ * callers that evaluate and react to a key change in one place, with
nothing else that needs to
+ * run before a `consume()` call in between. This is the partition-key
boundary check shared by
+ * `RowNumber`/`Rank`/`DenseRank` alike: see `doConsumeRowNumber` and the
grouped branches of
+ * `doConsumeRank`/`doConsumeDenseRank`. It is not used for the order-key
check in the latter two,
+ * which must evaluate before `consume()` but branch after -- see
`genKeyProjection`.
+ */
+ private def genKeyChangeCode(
+ ctx: CodegenContext,
+ input: Seq[ExprCode],
+ keyExprs: Seq[Expression],
+ keyTerm: String,
+ isDifferent: (String, String) => String,
+ onChange: String): String = {
+ val (evalCode, keyValue) = genKeyProjection(ctx, input, keyExprs)
+ s"""
+ |$evalCode
+ |${genKeyChangeBranch(keyTerm, keyValue, isDifferent, onChange)}
+ """.stripMargin
+ }
+
+ private def notEqualsCheck(a: String, b: String): String = s"!$a.equals($b)"
+
+ /**
+ * An `Ordering` over a row made up of just `orderSpec`'s columns (in order,
at ordinal
+ * positions 0..n-1), rather than the full `child.output`. Preserves each
column's own
+ * direction and null ordering, same as the interpreted
`OrderSpecProvider.ordering`, but is
+ * usable against the narrow projection `genKeyChangeCode` builds for the
order-key check.
+ *
+ * `private[sql]`, not `private`: generated code calls it by reflection-free
reference (see
+ * `genOrderKeyOrderingTerm`), and those generated classes live in
+ * `org.apache.spark.sql.catalyst.expressions`, inside this scope. The
qualifier is enforced
+ * at Scala compile time only -- the bytecode method stays public -- so
runtime-generated code
+ * links to it unchanged.
+ */
+ private[sql] def orderKeyOrdering(): BaseOrdering = {
+ val boundOrders = orderSpec.zipWithIndex.map { case (order, i) =>
+ order.copy(child = BoundReference(i, order.dataType, order.nullable))
+ }
+ GenerateOrdering.generate(boundOrders)
+ }
+
+ /**
+ * The generated `SpecificOrdering` class `orderKeyOrdering()` returns isn't
`Serializable`
+ * (codegen'd classes never are), so it can't be embedded directly as a
task-closure reference
+ * the way the mutable-state terms elsewhere in this file are. Instead,
reference `this` plan
+ * (already `Serializable`, like any other operator in the tree) and have
the generated `init()`
+ * build the ordering once per task by calling back into it -- the same
pattern `SortExec` uses
+ * for its `createSorter()`.
+ */
+ private def genOrderKeyOrderingTerm(ctx: CodegenContext, varName: String):
String = {
+ val planTerm = ctx.addReferenceObj("plan", this)
Review Comment:
**Blocking (P1):** `ctx.addReferenceObj("plan", this)` adds the operator to
the stage's references. `WholeStageCodegenExec.doExecute` passes those
references to `WholeStageCodegenEvaluatorFactory`, so they end up in every task
binary. Each task then deserializes this node and its whole child subtree. For
the Final operator that subtree runs through the exchange below it, so it is
the entire map-side plan, including any subquery plans. Each task also
registers every `SQLMetric` in that subtree with its `TaskContext`, and reports
them back even at zero. On the base branch these stages serialize no plan node.
SPARK-61661, SPARK-61666 and SPARK-61668 just removed this pattern from
`HashAggregateExec`, `SortExec` and the joins. They measured roughly 6 to 15 KB
and 100 to 200 microseconds per task for small plans, and up to about 1.2 ms
per task on a wide one. The same cost applies to every RANK and DENSE_RANK
stage this PR fuses (q44, q67, q67a, q70, q70a), but not to ROW_NUMBER. The s
caladoc above is inaccurate on three points:
- The generated `SpecificOrdering` extends `BaseOrdering`, a
`scala.math.Ordering`, which is `Serializable`. What can't ship is the Janino
class, which is why `LazilyGeneratedOrdering` regenerates the comparator in
`readObject`.
- The mutable-state terms in this file are fields of the generated class,
not task-closure references.
- `SortExec` no longer uses this pattern: `createSorter()` moved to
`SortExecSorterHolder` so that the node is not serialized into tasks.
**Verification:**
- **Regression:** For RANK and DENSE_RANK top-k queries with PARTITION BY,
in both the Partial and the Final stage and with AQE on and off, the RDD that
each codegen stage holding the operator adds on top of its inputs serializes no
plan node, the property the existing checks assert for sort, aggregate and join
stages.
- **Behavior:** The generated and interpreted paths still return identical
answers for RANK and DENSE_RANK across ascending and descending order, both
null orderings and multi-column order keys.
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameWindowFunctionsSuite.scala:
##########
@@ -1888,6 +1889,276 @@ class DataFrameWindowFunctionsSuite extends
SharedSparkSession
}
}
}
+
+ test("WindowGroupLimitExec supports codegen for row_number, rank and
dense_rank") {
+ // Ties (the repeated 2s) within each `key` group exercise `Rank`'s
skip-across-ties and
+ // `DenseRank`'s no-skip behavior, not just the simpler `RowNumber` count.
+ val df = Seq(
+ ("a", 1), ("a", 1), ("a", 2), ("a", 3),
+ ("b", 1), ("b", 2), ("b", 2), ("b", 3),
+ ("c", 1)).toDF("key", "value")
+
+ def topRows(partitioned: Boolean, rankLikeFunc: Column): DataFrame = {
+ val w = if (partitioned) {
+ Window.partitionBy($"key").orderBy($"value")
+ } else {
+ Window.orderBy($"value")
+ }
+ df.withColumn("rn", rankLikeFunc.over(w)).where($"rn" <= 2)
+ }
+
+ // None when the plan has no `WindowGroupLimitExec` at all: without a
`partitionBy`, Spark may
+ // rewrite `row_number`'s window into a `TakeOrderedAndProjectExec`
instead, which is unrelated
+ // to this change and never goes through `WindowGroupLimitExec`.
+ def windowGroupLimitIsFused(plan: SparkPlan): Option[Boolean] =
plan.collectFirst {
+ case WholeStageCodegenExec(_: WindowGroupLimitExec) => true
+ case _: WindowGroupLimitExec => false
+ }
+
+ // AQE can reshape the plan for such a tiny input (e.g. a local shuffle
reader optimization),
+ // which would make the shape assertions below flaky; disable it, as
SQLMetricsSuite's
+ // "SPARK-37099" WindowGroupLimitExec test also does.
+ Seq(true, false).foreach { partitioned =>
+ Seq(row_number(), rank(), dense_rank()).foreach { rankLikeFunc =>
+ val expectedRows = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key
-> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ topRows(partitioned, rankLikeFunc).collect().toSeq
+ }
+ withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val codegenDf = topRows(partitioned, rankLikeFunc)
+ checkAnswer(codegenDf, expectedRows)
+ val fused =
windowGroupLimitIsFused(codegenDf.queryExecution.executedPlan)
+ if (partitioned) {
+ // Partitioned top-k always goes through `WindowGroupLimitExec`,
so this must be
+ // present and fused.
+ assert(fused == Some(true),
+ s"$rankLikeFunc's WindowGroupLimit should be fused into
WholeStageCodegenExec")
+ } else {
+ fused.foreach { isFused =>
+ assert(isFused,
+ s"$rankLikeFunc's WindowGroupLimit should be fused into
WholeStageCodegenExec")
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Verifies `buildQuery()` (a `row_number`/`rank`/`dense_rank` top-k query,
named by `funcName`)
+ * gives the same answer under codegen as under the interpreted path, and --
for `rank`/
+ * `dense_rank` only -- the same answer as a ground truth computed with the
`WindowGroupLimit`
+ * optimizer rule disabled (a structurally different plan, with no
`WindowGroupLimitExec` at
+ * all). Checking against that ground truth, not just
interpreted-vs-codegen, catches a bug
+ * shared by both execution strategies, e.g. a `WindowGroupLimitExec` that
under- or
Review Comment:
**Non-blocking (P2):** The ground-truth comparison can only catch
over-filtering. Suppose the generated path admits extra rows, for instance
because `advanceRank` became a no-op, so `rank` stays 0 and every row passes.
`WindowExec` still recomputes the exact ranks, and the `rn <= k` filter trims
the extras. The answer then matches both the interpreted run and the
`WINDOW_GROUP_LIMIT_THRESHOLD = -1` plan, and every new test passes, while
every RANK top-k query windows its full input. The same holds for DENSE_RANK,
and for the Partial node of any function. Nothing in these tests reads the
operator's `numOutputRows`. The only assertion on it is SQLMetricsSuite's
SPARK-37099 test, which reads the Final node for row_number over three rows.
This scaladoc therefore claims coverage for under-filtering that the comparison
cannot provide.
**Verification:**
- **Regression:** With the rank or count advance disabled in the generated
RANK or DENSE_RANK path, the new assertions on the operator's numOutputRows
fail for both the Partial and the Final node, while the answer comparisons
still pass.
- **Behavior:** For each function, with and without PARTITION BY, on
fixtures with ties at the cutoff, the Partial and Final operators report the
same numOutputRows with codegen on as with codegen off.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -91,6 +93,274 @@ case class WindowGroupLimitExec(
}
}
+ // RowNumber, Rank and DenseRank are all wired up for codegen (see
`doConsume`); any future
+ // rank-like function defaults to the interpreted path above
(`WindowGroupLimitEvaluatorFactory`)
+ // by falling through to `false` here.
+ override def supportCodegen: Boolean = rankLikeFunction match {
+ case _: RowNumber | _: Rank | _: DenseRank => true
+ case _ => false
+ }
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
child.asInstanceOf[CodegenSupport].inputRDDs()
+
+ // This operator neither materializes nor reorders columns itself, so let
every column stay
+ // lazy until a downstream operator actually needs it, the same way
`FilterExec` does. Only the
+ // `partitionSpec`/`orderSpec` columns (if any) end up evaluated, by
`genKeyChangeCode`.
+ override def usedInputs: AttributeSet = AttributeSet.empty
+
+ protected override def doProduce(ctx: CodegenContext): String = {
+ child.asInstanceOf[CodegenSupport].produce(ctx, this)
+ }
+
+ override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row:
ExprCode): String = {
+ rankLikeFunction match {
+ case _: RowNumber => doConsumeRowNumber(ctx, input)
+ case _: Rank => doConsumeRank(ctx, input)
+ case _: DenseRank => doConsumeDenseRank(ctx, input)
+ case other =>
+ // Unreachable: `supportCodegen` keeps any other rank-like function
off the codegen path.
+ throw SparkException.internalError(
+ s"Codegen for rank-like function $other is not supported in
WindowGroupLimitExec.")
+ }
+ }
+
+ /**
+ * Projects `keyExprs` (bound against `child.output`) into a fresh
`UnsafeRow`, returning the
+ * code that computes it (to be emitted by the caller) together with the
Java expression that
+ * reads the resulting row. Evaluating a key this way -- rather than through
`genKeyChangeCode`
+ * below, which also does the comparison -- is for cases where the
evaluation must happen before
+ * a `consume()` call but the comparison/branch may happen after it; see the
order-key handling
+ * in `doConsumeRank`/`doConsumeDenseRank`.
+ *
+ * The returned code MUST be emitted, in the generated method, before any
`consume()` call for
+ * the same row. `usedInputs` is empty (columns stay lazy), so these
columns' evaluation code is
+ * still attached to `input` here; `evaluateRequiredVariables` evaluates and
clears it. Skipping
+ * that, or running it after `consume(ctx, input)`, would duplicate the
work: `consume()`
+ * evaluates and clears the columns `input` owes on its own internal copy of
`input` (see its
+ * `outputVars.map(_.copy())`), leaving `input`'s original `ExprCode`s --
the ones this method
Review Comment:
**Nit (P3):** This explanation is the reverse of what `consume()` does. It
calls `prepareRowVar` on the original `outputVars`, whose `evaluateVariables`
clears their code, and then points `ctx.currentVars` at its copies. A
projection generated afterwards would read the copies, or whatever the parent
left there, not `input`'s originals. Emitting before `consume()` is right, but
for that reason, which also matches the comment at lines 241-244. Other
comments in this file have the same kind of problem:
- Line 128 says the projection writes a fresh `UnsafeRow`, but
`GenerateUnsafeProjection.createCode` resets and returns one reused `rowWriter`
row. That reuse is why `genKeyChangeBranch` copies it.
- The `usedInputs` comment (106-108) and the `orderKeyOrdering` scaladoc
(204-208) credit `genKeyChangeCode` with the order-key work. The
`genKeyProjection` calls in `body()` do that work.
- The `doConsumeRank` comment (281-283) contrasts the generated path with
the interpreted one. But `GroupIterator.skipRemainingRows` also fetches every
remaining row and projects its partition key, so after the limit both paths
check the partition key and skip only the order-key work.
**Verification:**
- **Inspection:** The rewritten comments describe consume() as clearing
input's remaining evaluation code and rebinding the current variables, the key
projection as returning a reused row, the order-key work as done by
genKeyProjection, and the interpreted iterator as also checking the partition
key of every skipped row, and no comment in the operator says otherwise.
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameWindowFunctionsSuite.scala:
##########
@@ -1888,6 +1889,276 @@ class DataFrameWindowFunctionsSuite extends
SharedSparkSession
}
}
}
+
+ test("WindowGroupLimitExec supports codegen for row_number, rank and
dense_rank") {
+ // Ties (the repeated 2s) within each `key` group exercise `Rank`'s
skip-across-ties and
+ // `DenseRank`'s no-skip behavior, not just the simpler `RowNumber` count.
+ val df = Seq(
+ ("a", 1), ("a", 1), ("a", 2), ("a", 3),
+ ("b", 1), ("b", 2), ("b", 2), ("b", 3),
+ ("c", 1)).toDF("key", "value")
+
+ def topRows(partitioned: Boolean, rankLikeFunc: Column): DataFrame = {
+ val w = if (partitioned) {
+ Window.partitionBy($"key").orderBy($"value")
+ } else {
+ Window.orderBy($"value")
+ }
+ df.withColumn("rn", rankLikeFunc.over(w)).where($"rn" <= 2)
+ }
+
+ // None when the plan has no `WindowGroupLimitExec` at all: without a
`partitionBy`, Spark may
+ // rewrite `row_number`'s window into a `TakeOrderedAndProjectExec`
instead, which is unrelated
+ // to this change and never goes through `WindowGroupLimitExec`.
+ def windowGroupLimitIsFused(plan: SparkPlan): Option[Boolean] =
plan.collectFirst {
+ case WholeStageCodegenExec(_: WindowGroupLimitExec) => true
+ case _: WindowGroupLimitExec => false
+ }
+
+ // AQE can reshape the plan for such a tiny input (e.g. a local shuffle
reader optimization),
+ // which would make the shape assertions below flaky; disable it, as
SQLMetricsSuite's
+ // "SPARK-37099" WindowGroupLimitExec test also does.
+ Seq(true, false).foreach { partitioned =>
+ Seq(row_number(), rank(), dense_rank()).foreach { rankLikeFunc =>
+ val expectedRows = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key
-> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ topRows(partitioned, rankLikeFunc).collect().toSeq
+ }
+ withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val codegenDf = topRows(partitioned, rankLikeFunc)
+ checkAnswer(codegenDf, expectedRows)
+ val fused =
windowGroupLimitIsFused(codegenDf.queryExecution.executedPlan)
+ if (partitioned) {
+ // Partitioned top-k always goes through `WindowGroupLimitExec`,
so this must be
+ // present and fused.
+ assert(fused == Some(true),
+ s"$rankLikeFunc's WindowGroupLimit should be fused into
WholeStageCodegenExec")
+ } else {
+ fused.foreach { isFused =>
Review Comment:
**Nit (P3):** `fused.foreach` lets the unpartitioned cases pass when the
plan has no `WindowGroupLimitExec` at all. For `row_number` that is always true
here: with the default `spark.sql.execution.topKSortFallbackThreshold`
(Int.MaxValue - 15), `InferWindowGroupLimit` rewrites an unpartitioned
ROW_NUMBER top-k into a `Limit`. Users reach the generated
`partitionSpec.isEmpty` branch of `doConsumeRowNumber` by lowering that public
threshold to the limit or below, but no test runs it. The `limit = 10`
iterations of the multi-column partition-key and order-by tests test nothing
for a similar reason. Both fixtures have 7 rows, and `InferWindowGroupLimit`
only inserts the operator when the child has more rows than the limit.
**Verification:**
- **Behavior:** Unpartitioned ROW_NUMBER top-k queries with
spark.sql.execution.topKSortFallbackThreshold at or below the limit plan a
WindowGroupLimitExec and return the same rows with codegen on as with codegen
off.
- **Inspection:** No comparison case uses a limit at or above its fixture's
row count, and every case checks that its plan contains the operator.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -91,6 +93,274 @@ case class WindowGroupLimitExec(
}
}
+ // RowNumber, Rank and DenseRank are all wired up for codegen (see
`doConsume`); any future
+ // rank-like function defaults to the interpreted path above
(`WindowGroupLimitEvaluatorFactory`)
+ // by falling through to `false` here.
+ override def supportCodegen: Boolean = rankLikeFunction match {
+ case _: RowNumber | _: Rank | _: DenseRank => true
+ case _ => false
+ }
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
child.asInstanceOf[CodegenSupport].inputRDDs()
+
+ // This operator neither materializes nor reorders columns itself, so let
every column stay
+ // lazy until a downstream operator actually needs it, the same way
`FilterExec` does. Only the
+ // `partitionSpec`/`orderSpec` columns (if any) end up evaluated, by
`genKeyChangeCode`.
+ override def usedInputs: AttributeSet = AttributeSet.empty
+
+ protected override def doProduce(ctx: CodegenContext): String = {
+ child.asInstanceOf[CodegenSupport].produce(ctx, this)
Review Comment:
**Blocking (P1):** Without PARTITION BY, the interpreted operator stopped
pulling rows as soon as the rank reached the limit (`BaseLimitIterator.hasNext`
is `rank < limit && input.hasNext`). Here `doProduce` only calls
`child.produce`, and the class doesn't override `limitNotReachedChecks`. After
the limit, each row is rejected inside `consume` without appending anything, so
`shouldStop()` stays false and the producer's loop never sees a stop condition.
From the code, the Partial operator in q44 lets the fused Sort loop (`while
($limitNotReachedCond $sortedIterator.hasNext())`) walk every remaining sorted
row of the map partition. If the sort spilled, every spilled run is read back
in full. Over an already ordered child, such as `spark.range(...)` ranked by
`id`, every row of the partition would be generated, where the base branch
stops after about `limit` rows. This applies by default to RANK and DENSE_RANK
with no PARTITION BY. It also applies to ROW_NUMBER with no PARTITION BY
when `spark.sql.execution.topKSortFallbackThreshold` is at or below the limit.
Results don't change, but the work after the limit now grows with the partition
size. A `limitNotReachedChecks` entry would stop Sort, Range, scan,
ColumnarToRow and InputAdapter loops, but not a sort merge join, because its
loop reads no limit check. The regenerated TopKBenchmark files can't size this:
each compares runs on different machines, and they disagree. The JDK 25 file
shows the unpartitioned RANK and DENSE_RANK cases 2.65x and 2.71x slower, while
the JDK 21 file shows them about 3x faster.
**Recommended change:** Make supportCodegen return false when partitionSpec
is empty, so an operator with no PARTITION BY runs as on the base branch,
interpreted above its child's stage; remove the empty-partitionSpec branches of
the three generated consume paths, which become unreachable; regenerate the q44
and q44.sf100 plan-stability files, whose unpartitioned WindowGroupLimit nodes
move back outside the codegen stages; update the fusion test to expect the
unpartitioned operators to stay interpreted; and add a window-function test
showing that a RANK and DENSE_RANK top-k without PARTITION BY stops reading its
child at the limit.
**Why this works:** With the operator outside the stage, the child stage
hands it rows one at a time through the stage iterator, and
BaseLimitIterator.hasNext (`rank < limit && input.hasNext`) stops pulling once
the rank reaches the limit, so the child's loop, whichever operator produces
it, runs only for the rows the operator admits, about limit rows plus ties per
partition, as on the base branch.
**Scope:** Limit the operator's codegen to windows with PARTITION BY, drop
the generated code that only served the unpartitioned case, and update the plan
golden files and window-function tests that record the unpartitioned plans.
**Compatibility:** Results, the partitioned generated path and the
interpreted iterators stay as they are; only where the unpartitioned operator
runs changes, back to the base branch's plan.
**Risks:** Unpartitioned top-k queries lose the codegen fusion this change
adds for them, so their plans, the q44 golden files and EXPLAIN return to the
base branch's shape. The interpreted per-row cost stays on the rows the
operator admits, about limit rows plus ties per partition, which is small
unless large tie groups at the cutoff make RANK or DENSE_RANK admit far more
rows than the limit; restoring the eligibility condition rolls the change back.
**Constraints:** The partitioned generated paths, their admission rules and
their plan-stability files stay unchanged. The interpreted iterators stay the
base branch's code, since they now also serve the unpartitioned case when
codegen is on.
**Exclusions:**
- Teaching SortMergeJoinExec's generated loop to read limitNotReachedChecks,
which would also help a LocalLimitExec fused onto a join, is outside this
change.
- Regenerating the TopKBenchmark results files is left to the benchmark
workflow.
**Success:** With whole-stage codegen on, a WindowGroupLimitExec with an
empty partitionSpec is not fused into its child's stage, and its partitioned
counterparts still are. A RANK or DENSE_RANK top-k without PARTITION BY reads
only about limit rows plus ties from each partition of its child, whether that
child is a Sort, an already ordered source or a sort merge join. Query results
are unchanged for every function, with and without PARTITION BY.
**Verification:**
- **Regression:** A RANK and a DENSE_RANK top-k without PARTITION BY, with
whole-stage codegen on, over an already ordered child such as spark.range
ranked by id, makes that child produce only about limit rows per partition,
observed through the range's numOutputRows metric, where the current code
produces every row of the partition.
- **Behavior:** With whole-stage codegen on, the unpartitioned ROW_NUMBER,
RANK and DENSE_RANK operators run outside a codegen stage while the partitioned
ones are fused, and all of them return the same answers as with codegen off.
- **Inspection:** The regenerated q44 and q44.sf100 plan-stability files
differ from the current ones only in their WindowGroupLimit nodes moving back
outside the WholeStageCodegen stages.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -91,6 +93,274 @@ case class WindowGroupLimitExec(
}
}
+ // RowNumber, Rank and DenseRank are all wired up for codegen (see
`doConsume`); any future
+ // rank-like function defaults to the interpreted path above
(`WindowGroupLimitEvaluatorFactory`)
+ // by falling through to `false` here.
+ override def supportCodegen: Boolean = rankLikeFunction match {
+ case _: RowNumber | _: Rank | _: DenseRank => true
+ case _ => false
+ }
+
+ override def inputRDDs(): Seq[RDD[InternalRow]] =
child.asInstanceOf[CodegenSupport].inputRDDs()
+
+ // This operator neither materializes nor reorders columns itself, so let
every column stay
+ // lazy until a downstream operator actually needs it, the same way
`FilterExec` does. Only the
+ // `partitionSpec`/`orderSpec` columns (if any) end up evaluated, by
`genKeyChangeCode`.
+ override def usedInputs: AttributeSet = AttributeSet.empty
+
+ protected override def doProduce(ctx: CodegenContext): String = {
+ child.asInstanceOf[CodegenSupport].produce(ctx, this)
+ }
+
+ override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row:
ExprCode): String = {
+ rankLikeFunction match {
+ case _: RowNumber => doConsumeRowNumber(ctx, input)
+ case _: Rank => doConsumeRank(ctx, input)
+ case _: DenseRank => doConsumeDenseRank(ctx, input)
+ case other =>
+ // Unreachable: `supportCodegen` keeps any other rank-like function
off the codegen path.
+ throw SparkException.internalError(
+ s"Codegen for rank-like function $other is not supported in
WindowGroupLimitExec.")
+ }
+ }
+
+ /**
+ * Projects `keyExprs` (bound against `child.output`) into a fresh
`UnsafeRow`, returning the
+ * code that computes it (to be emitted by the caller) together with the
Java expression that
+ * reads the resulting row. Evaluating a key this way -- rather than through
`genKeyChangeCode`
+ * below, which also does the comparison -- is for cases where the
evaluation must happen before
+ * a `consume()` call but the comparison/branch may happen after it; see the
order-key handling
+ * in `doConsumeRank`/`doConsumeDenseRank`.
+ *
+ * The returned code MUST be emitted, in the generated method, before any
`consume()` call for
+ * the same row. `usedInputs` is empty (columns stay lazy), so these
columns' evaluation code is
+ * still attached to `input` here; `evaluateRequiredVariables` evaluates and
clears it. Skipping
+ * that, or running it after `consume(ctx, input)`, would duplicate the
work: `consume()`
+ * evaluates and clears the columns `input` owes on its own internal copy of
`input` (see its
+ * `outputVars.map(_.copy())`), leaving `input`'s original `ExprCode`s --
the ones this method
+ * reads -- still holding their unclaimed evaluation code, which
`GenerateUnsafeProjection` would
+ * then copy as-is (`BoundReference.doGenCode` copies but does not clear a
source `ExprCode`'s
+ * code), re-running the same expression a second time. For a
non-deterministic expression (e.g.
+ * `ORDER BY rand()`) that would let the materialized output row and the
value used for this
+ * projection disagree, not just waste cycles.
+ */
+ private def genKeyProjection(
+ ctx: CodegenContext,
+ input: Seq[ExprCode],
+ keyExprs: Seq[Expression]): (String, String) = {
+ val requiredAttrs = AttributeSet(keyExprs.flatMap(_.references))
+ val evaluateCols = evaluateRequiredVariables(child.output, input,
requiredAttrs)
+ val keyCode = GenerateUnsafeProjection.createCode(ctx,
bindReferences(keyExprs, child.output))
+ (s"$evaluateCols\n${keyCode.code}", keyCode.value.toString)
+ }
+
+ /**
+ * Generates the code that compares an already-projected key (`keyValue`,
from
+ * `genKeyProjection`) against the mutable `UnsafeRow` snapshot of the
previous row's key
+ * (`keyTerm`), and runs `onChange` whenever they differ, per `isDifferent`
(e.g. `!a.equals(b)`,
+ * or an `Ordering.compare(a, b) != 0`). `onChange` does not run for the
very first row seen
+ * (there is nothing to compare against yet, matching `BaseLimitIterator`'s
subclasses, which
+ * only initialize their tracking state then).
+ */
+ private def genKeyChangeBranch(
+ keyTerm: String,
+ keyValue: String,
+ isDifferent: (String, String) => String,
+ onChange: String): String = {
+ s"""
+ |if ($keyTerm == null) {
+ | $keyTerm = ($keyValue).copy();
+ |} else if (${isDifferent(keyTerm, keyValue)}) {
+ | $onChange
+ | $keyTerm = ($keyValue).copy();
+ |}
+ """.stripMargin
+ }
+
+ /**
+ * `genKeyProjection` followed immediately by `genKeyChangeBranch` against
its result -- for
+ * callers that evaluate and react to a key change in one place, with
nothing else that needs to
+ * run before a `consume()` call in between. This is the partition-key
boundary check shared by
+ * `RowNumber`/`Rank`/`DenseRank` alike: see `doConsumeRowNumber` and the
grouped branches of
+ * `doConsumeRank`/`doConsumeDenseRank`. It is not used for the order-key
check in the latter two,
+ * which must evaluate before `consume()` but branch after -- see
`genKeyProjection`.
+ */
+ private def genKeyChangeCode(
+ ctx: CodegenContext,
+ input: Seq[ExprCode],
+ keyExprs: Seq[Expression],
+ keyTerm: String,
+ isDifferent: (String, String) => String,
+ onChange: String): String = {
+ val (evalCode, keyValue) = genKeyProjection(ctx, input, keyExprs)
+ s"""
+ |$evalCode
+ |${genKeyChangeBranch(keyTerm, keyValue, isDifferent, onChange)}
+ """.stripMargin
+ }
+
+ private def notEqualsCheck(a: String, b: String): String = s"!$a.equals($b)"
+
+ /**
+ * An `Ordering` over a row made up of just `orderSpec`'s columns (in order,
at ordinal
+ * positions 0..n-1), rather than the full `child.output`. Preserves each
column's own
+ * direction and null ordering, same as the interpreted
`OrderSpecProvider.ordering`, but is
+ * usable against the narrow projection `genKeyChangeCode` builds for the
order-key check.
+ *
+ * `private[sql]`, not `private`: generated code calls it by reflection-free
reference (see
+ * `genOrderKeyOrderingTerm`), and those generated classes live in
+ * `org.apache.spark.sql.catalyst.expressions`, inside this scope. The
qualifier is enforced
+ * at Scala compile time only -- the bytecode method stays public -- so
runtime-generated code
+ * links to it unchanged.
+ */
+ private[sql] def orderKeyOrdering(): BaseOrdering = {
+ val boundOrders = orderSpec.zipWithIndex.map { case (order, i) =>
+ order.copy(child = BoundReference(i, order.dataType, order.nullable))
+ }
+ GenerateOrdering.generate(boundOrders)
+ }
+
+ /**
+ * The generated `SpecificOrdering` class `orderKeyOrdering()` returns isn't
`Serializable`
+ * (codegen'd classes never are), so it can't be embedded directly as a
task-closure reference
+ * the way the mutable-state terms elsewhere in this file are. Instead,
reference `this` plan
+ * (already `Serializable`, like any other operator in the tree) and have
the generated `init()`
+ * build the ordering once per task by calling back into it -- the same
pattern `SortExec` uses
+ * for its `createSorter()`.
+ */
+ private def genOrderKeyOrderingTerm(ctx: CodegenContext, varName: String):
String = {
+ val planTerm = ctx.addReferenceObj("plan", this)
+ ctx.addMutableState(classOf[BaseOrdering].getName, varName,
+ v => s"$v = $planTerm.orderKeyOrdering();", forceInline = true)
+ }
+
+ private def doConsumeRowNumber(ctx: CodegenContext, input: Seq[ExprCode]):
String = {
+ val numOutput = metricTerm(ctx, "numOutputRows")
+ val rankTerm = ctx.addMutableState(CodeGenerator.JAVA_INT, "rank",
forceInline = true)
+
+ // A `def`, not a `val`: `consume(ctx, input)` has the side effect of
emitting (and marking
+ // consumed) the evaluation code for every column `input` still owes. It
must run after the
+ // grouped branch below has already claimed the partition columns' code via
+ // `genKeyChangeCode`, not before -- otherwise both would emit it,
independently.
+ def checkLimitAndConsume(): String =
+ s"""
+ |if ($rankTerm < $limit) {
+ | $rankTerm++;
+ | $numOutput.add(1);
+ | ${consume(ctx, input)}
+ |}
+ """.stripMargin
+
+ if (partitionSpec.isEmpty) {
+ checkLimitAndConsume()
+ } else {
+ // Rows arrive already clustered by `partitionSpec` (see
`requiredChildDistribution` and
+ // `requiredChildOrdering`), so a change in the projected partition key
marks the start of a
+ // new group: reset the rank counter, mirroring the group-boundary
detection
+ // `SortAggregateExec.doConsumeWithKeys` uses for its sort-based
grouping.
+ val groupKeyTerm = ctx.addMutableState("UnsafeRow", "groupKey",
forceInline = true)
+ genKeyChangeCode(ctx, input, partitionSpec, groupKeyTerm,
notEqualsCheck, s"$rankTerm = 0;") +
+ checkLimitAndConsume()
+ }
+ }
+
+ private def doConsumeRank(ctx: CodegenContext, input: Seq[ExprCode]): String
= {
+ val numOutput = metricTerm(ctx, "numOutputRows")
+ val rankTerm = ctx.addMutableState(CodeGenerator.JAVA_INT, "rank",
forceInline = true)
Review Comment:
**Nit (P3):** `rank`, `count`, `groupKey`, the order-key snapshot and the
ordering are all created in `doConsume` with fresh names. So each `consume()`
call a producer makes gets its own copy of this state. When the join is planned
as a sort merge join, left and right outer `SortMergeJoinExec` codegen calls
`consume()` twice: once for joined rows and once for the streamed-only guard. A
WindowGroupLimitExec whose ascending PARTITION BY and ORDER BY columns are a
prefix of the streamed join keys fuses directly onto that join. Take
`spark.sql.join.splitStreamedSideJoinCondition=true` with a streamed-side-only
conjunct, for example `l LEFT JOIN r ON l.k = r.k AND l.x > 5`. Rows then reach
both sites, and each site ranks only its own subsequence. Up to twice as many
rows pass into the shuffle, and `numOutputRows` no longer matches the
interpreted path. Results stay correct, since a site's rank never exceeds a
row's true rank and the Filter trims the extras. With the default setting the
guard copy's code isn't emitted, but its state still is, and its `init()`
builds a second ordering in every task. `BaseLimitExec` avoids this by
declaring its counter once in `doProduce`.
**Verification:**
- **Regression:** With spark.sql.join.splitStreamedSideJoinCondition=true,
ROW_NUMBER, RANK and DENSE_RANK top-k queries partitioned and ordered by the
two join keys of a left outer sort merge join with a streamed-side-only
condition fuse onto the join and report the same WindowGroupLimitExec
numOutputRows and answers as with codegen off.
- **Inspection:** The generated code of a stage whose producer calls
consume() twice declares each piece of the operator's cross-row state once.
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameWindowFunctionsSuite.scala:
##########
@@ -1888,6 +1889,276 @@ class DataFrameWindowFunctionsSuite extends
SharedSparkSession
}
}
}
+
+ test("WindowGroupLimitExec supports codegen for row_number, rank and
dense_rank") {
+ // Ties (the repeated 2s) within each `key` group exercise `Rank`'s
skip-across-ties and
+ // `DenseRank`'s no-skip behavior, not just the simpler `RowNumber` count.
+ val df = Seq(
+ ("a", 1), ("a", 1), ("a", 2), ("a", 3),
+ ("b", 1), ("b", 2), ("b", 2), ("b", 3),
+ ("c", 1)).toDF("key", "value")
+
+ def topRows(partitioned: Boolean, rankLikeFunc: Column): DataFrame = {
+ val w = if (partitioned) {
+ Window.partitionBy($"key").orderBy($"value")
+ } else {
+ Window.orderBy($"value")
+ }
+ df.withColumn("rn", rankLikeFunc.over(w)).where($"rn" <= 2)
+ }
+
+ // None when the plan has no `WindowGroupLimitExec` at all: without a
`partitionBy`, Spark may
+ // rewrite `row_number`'s window into a `TakeOrderedAndProjectExec`
instead, which is unrelated
+ // to this change and never goes through `WindowGroupLimitExec`.
+ def windowGroupLimitIsFused(plan: SparkPlan): Option[Boolean] =
plan.collectFirst {
+ case WholeStageCodegenExec(_: WindowGroupLimitExec) => true
+ case _: WindowGroupLimitExec => false
+ }
+
+ // AQE can reshape the plan for such a tiny input (e.g. a local shuffle
reader optimization),
+ // which would make the shape assertions below flaky; disable it, as
SQLMetricsSuite's
+ // "SPARK-37099" WindowGroupLimitExec test also does.
+ Seq(true, false).foreach { partitioned =>
+ Seq(row_number(), rank(), dense_rank()).foreach { rankLikeFunc =>
+ val expectedRows = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key
-> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ topRows(partitioned, rankLikeFunc).collect().toSeq
+ }
+ withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val codegenDf = topRows(partitioned, rankLikeFunc)
+ checkAnswer(codegenDf, expectedRows)
+ val fused =
windowGroupLimitIsFused(codegenDf.queryExecution.executedPlan)
+ if (partitioned) {
+ // Partitioned top-k always goes through `WindowGroupLimitExec`,
so this must be
+ // present and fused.
+ assert(fused == Some(true),
+ s"$rankLikeFunc's WindowGroupLimit should be fused into
WholeStageCodegenExec")
+ } else {
+ fused.foreach { isFused =>
+ assert(isFused,
+ s"$rankLikeFunc's WindowGroupLimit should be fused into
WholeStageCodegenExec")
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Verifies `buildQuery()` (a `row_number`/`rank`/`dense_rank` top-k query,
named by `funcName`)
+ * gives the same answer under codegen as under the interpreted path, and --
for `rank`/
+ * `dense_rank` only -- the same answer as a ground truth computed with the
`WindowGroupLimit`
+ * optimizer rule disabled (a structurally different plan, with no
`WindowGroupLimitExec` at
+ * all). Checking against that ground truth, not just
interpreted-vs-codegen, catches a bug
+ * shared by both execution strategies, e.g. a `WindowGroupLimitExec` that
under- or
+ * over-filters in a way that happens to agree between the two.
+ *
+ * The ground-truth check is skipped for `row_number`: every tied row in a
group gets the same
+ * `rank`/`dense_rank`, but ties can get arbitrary distinct `row_number`s,
so a `limit` that
+ * splits a tied group can legitimately see different per-row assignments
(though the same *set*
Review Comment:
**Nit (P3):** A different plan can return a different set of tied rows here,
not just different numbers for the same rows. In the unpartitioned runs the six
value-1 rows have keys a, a, b, null, null and c. With nulls first, limit 3
keeps both null-value rows plus any one of those six. In the overlap test,
every row in a group ties while the keys differ. Other comments in these tests
have similar problems:
- Line 1894: at `rn <= 2`, group b's repeated 2s give the same rows for rank
(1, 2, 2, 4) and dense_rank (1, 2, 2, 3). The difference comes from group a's
repeated 1s and the unpartitioned tie on 1.
- Lines 1918-1920: with AQE on, `executedPlan` is an `AdaptiveSparkPlanExec`
leaf, so `collectFirst` finds nothing and the partitioned assertion fails on
every run, not intermittently.
- Lines 1951-1952: `WINDOW_GROUP_LIMIT_THRESHOLD = -1` disables
`InferWindowGroupLimit`; `WindowGroupLimit` is the logical node.
- Lines 1964-1966: the helper makes no plan-shape checks, and
SQLMetricsSuite's SPARK-37099 test carries no AQE note, since that suite
disables AQE suite-wide.
- Lines 2029-2030: in the unpartitioned runs all 11 rows form one group, so
limit 10 is reached.
**Verification:**
- **Inspection:** The corrected comments attribute the rank versus
dense_rank difference to the ties that cause it, describe AQE's effect as a
deterministic failure of the fusion check, name InferWindowGroupLimit, allow
different tied rows under a different plan, make no claim about plan-shape
checks or a SQLMetricsSuite note, and state the limit coverage of the
unpartitioned runs correctly.
--
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]