peter-toth commented on code in PR #57576: URL: https://github.com/apache/spark/pull/57576#discussion_r3668891619
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CombineApproximatePercentiles.scala: ########## @@ -0,0 +1,139 @@ +/* + * 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.catalyst.optimizer + +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{CreateArray, Expression, ExprId, GetArrayItem, Literal, NamedExpression} +import org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, AggregateMode, ApproximatePercentile} +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.AGGREGATE +import org.apache.spark.sql.types.DoubleType + +/** + * Combines scalar approximate percentiles that can share the same percentile digest. + * + * An approximate percentile digest depends on its input, accuracy, filter, distinctness, and + * aggregate mode, but not on the percentile requested from the completed digest. Consequently, + * compatible scalar percentiles can be calculated by one array-valued aggregate and projected + * back to their original scalar outputs. + * + * Inputs and filters must retain their original expression structure so that floating-point + * evaluation and ANSI overflow behavior are preserved. Streaming aggregates are left unchanged + * to preserve the value schemas of existing checkpoints. + */ +object CombineApproximatePercentiles extends Rule[LogicalPlan] { + + private case class CompatibilityKey( + child: Expression, + accuracy: Long, + mode: AggregateMode, + isDistinct: Boolean, + filter: Option[Expression]) + + private case class PhysicalCompatibilityKey( + child: Expression, + accuracy: Expression, + mode: AggregateMode, + isDistinct: Boolean, + filter: Option[Expression]) + + private def physicalCompatibilityKey( + key: CompatibilityKey, + accuracy: Expression): PhysicalCompatibilityKey = PhysicalCompatibilityKey( + key.child.canonicalized, + accuracy.canonicalized, + key.mode, + key.isDistinct, + key.filter.map(_.canonicalized)) + + override def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning( + _.containsPattern(AGGREGATE), ruleId) { + case aggregate: Aggregate if aggregate.resolved && !aggregate.isStreaming => + combine(aggregate) + } + + private def combine(aggregate: Aggregate): Aggregate = { + val compatible = mutable.LinkedHashMap.empty[ + CompatibilityKey, mutable.ArrayBuffer[AggregateExpression]] + val physicalCompatibilityKeys = mutable.HashMap.empty[ + PhysicalCompatibilityKey, mutable.HashSet[CompatibilityKey]] + val arrayPercentiles = mutable.ArrayBuffer.empty[AggregateExpression] + + aggregate.aggregateExpressions.foreach(_.foreach { + case expression @ AggregateExpression( + percentile: ApproximatePercentile, mode, isDistinct, filter, _) + if percentile.child.deterministic && + filter.forall(_.deterministic) => + val key = CompatibilityKey( + percentile.child, + percentile.accuracyExpression.eval().asInstanceOf[Number].longValue, + mode, + isDistinct, + filter) + physicalCompatibilityKeys.getOrElseUpdate( + physicalCompatibilityKey(key, percentile.accuracyExpression), + mutable.HashSet.empty) += key + if (percentile.percentageExpression.dataType == DoubleType) { + compatible.getOrElseUpdate(key, mutable.ArrayBuffer.empty) += expression + } else { + arrayPercentiles += expression + } + case _ => + }) + + val replacements = mutable.HashMap.empty[ExprId, (AggregateExpression, Int)] + compatible.iterator.filter { case (key, expressions) => + expressions.sizeCompare(1) > 0 && expressions.forall { expression => + val percentile = expression.aggregateFunction.asInstanceOf[ApproximatePercentile] + physicalCompatibilityKeys( + physicalCompatibilityKey(key, percentile.accuracyExpression)).sizeCompare(1) == 0 + } + }.foreach { case (_, expressions) => + val first = expressions.head + val percentile = first.aggregateFunction.asInstanceOf[ApproximatePercentile] + val percentages = expressions.map { expression => + expression.aggregateFunction + .asInstanceOf[ApproximatePercentile] + .percentageExpression + } + val combined = first.copy( + aggregateFunction = percentile.copy( + percentageExpression = CreateArray(percentages.toSeq))) + if (!arrayPercentiles.exists(_.semanticEquals(combined))) { + expressions.zipWithIndex.foreach { case (expression, index) => + replacements.put(expression.resultId, (combined, index)) Review Comment: **Finding 2.** `replacements` is keyed by `resultId`, so if the *same* `AggregateExpression` instance is collected twice into one group, the second `put` overwrites the first and both references resolve to the last ordinal. This happens whenever a `Column` is reused, e.g. `df.agg(p50.as("a"), p50.as("b"), p90.as("c"))` — `aggregate.aggregateExpressions.foreach(_.foreach ...)` walks each occurrence, so the buffer is `[p50, p50, p90]` while `replacements` maps that one `resultId` to ordinal 1 only: ``` Aggregate [percentile_approx(col, [0.5,0.5,0.9], ...)[1] AS a, percentile_approx(col, [0.5,0.5,0.9], ...)[1] AS b, percentile_approx(col, [0.5,0.5,0.9], ...)[2] AS c] ``` Results are correct today, and I could not construct a wrong answer: a repeated `resultId` implies the identical instance, hence the identical percentage, so every ordinal it could have pointed at holds the same value. But that is an unstated invariant that the positional `expressions`/`percentages` alignment depends on, and it would break quietly if a future change ever derived the array from anything other than one-slot-per-occurrence. Deduping the group by `resultId` before building the array makes the intent explicit and drops the dead slot: ```scala }.foreach { case (_, allExpressions) => val expressions = allExpressions.distinctBy(_.resultId) ``` (If finding 1 lands, this dedup should happen before the distinct-percentage check so the reused instance doesn't count twice toward "2+ compatible aggregates".) ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CombineApproximatePercentiles.scala: ########## @@ -0,0 +1,139 @@ +/* + * 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.catalyst.optimizer + +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{CreateArray, Expression, ExprId, GetArrayItem, Literal, NamedExpression} +import org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, AggregateMode, ApproximatePercentile} +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.AGGREGATE +import org.apache.spark.sql.types.DoubleType + +/** + * Combines scalar approximate percentiles that can share the same percentile digest. + * + * An approximate percentile digest depends on its input, accuracy, filter, distinctness, and + * aggregate mode, but not on the percentile requested from the completed digest. Consequently, + * compatible scalar percentiles can be calculated by one array-valued aggregate and projected + * back to their original scalar outputs. + * + * Inputs and filters must retain their original expression structure so that floating-point + * evaluation and ANSI overflow behavior are preserved. Streaming aggregates are left unchanged + * to preserve the value schemas of existing checkpoints. + */ +object CombineApproximatePercentiles extends Rule[LogicalPlan] { + + private case class CompatibilityKey( + child: Expression, + accuracy: Long, + mode: AggregateMode, + isDistinct: Boolean, + filter: Option[Expression]) + + private case class PhysicalCompatibilityKey( + child: Expression, + accuracy: Expression, + mode: AggregateMode, + isDistinct: Boolean, + filter: Option[Expression]) + + private def physicalCompatibilityKey( + key: CompatibilityKey, + accuracy: Expression): PhysicalCompatibilityKey = PhysicalCompatibilityKey( + key.child.canonicalized, + accuracy.canonicalized, + key.mode, + key.isDistinct, + key.filter.map(_.canonicalized)) + + override def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning( + _.containsPattern(AGGREGATE), ruleId) { + case aggregate: Aggregate if aggregate.resolved && !aggregate.isStreaming => + combine(aggregate) + } + + private def combine(aggregate: Aggregate): Aggregate = { + val compatible = mutable.LinkedHashMap.empty[ + CompatibilityKey, mutable.ArrayBuffer[AggregateExpression]] + val physicalCompatibilityKeys = mutable.HashMap.empty[ + PhysicalCompatibilityKey, mutable.HashSet[CompatibilityKey]] + val arrayPercentiles = mutable.ArrayBuffer.empty[AggregateExpression] + + aggregate.aggregateExpressions.foreach(_.foreach { + case expression @ AggregateExpression( + percentile: ApproximatePercentile, mode, isDistinct, filter, _) + if percentile.child.deterministic && + filter.forall(_.deterministic) => + val key = CompatibilityKey( + percentile.child, + percentile.accuracyExpression.eval().asInstanceOf[Number].longValue, + mode, + isDistinct, + filter) + physicalCompatibilityKeys.getOrElseUpdate( + physicalCompatibilityKey(key, percentile.accuracyExpression), + mutable.HashSet.empty) += key + if (percentile.percentageExpression.dataType == DoubleType) { + compatible.getOrElseUpdate(key, mutable.ArrayBuffer.empty) += expression + } else { + arrayPercentiles += expression + } + case _ => + }) + + val replacements = mutable.HashMap.empty[ExprId, (AggregateExpression, Int)] + compatible.iterator.filter { case (key, expressions) => + expressions.sizeCompare(1) > 0 && expressions.forall { expression => Review Comment: **Finding 1.** `expressions.sizeCompare(1) > 0` fires on 2+ compatible aggregates regardless of whether their percentages differ, so a query repeating one percentage gets *more* work than on base, not less. `PhysicalAggregation` already dedups semantically-equal aggregates via `EquivalentExpressions` (`sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:300`), so two identical scalar percentiles share one digest and query it once today. After fusion they become one digest queried N times. Measured on the PR head, counting `ApproximatePercentile` buffers and percentages per `ObjectHashAggregateExec`: ``` SELECT percentile_approx(col, 0.5D) a, percentile_approx(col, 0.5D) b FROM t base : digests=1 percentagesQueried=1 fused: digests=1 percentagesQueried=2 <- pure loss SELECT percentile_approx(col, 0.5D) a, percentile_approx(col, 0.5D) b, percentile_approx(col, 0.5D) c FROM t base : digests=1 percentagesQueried=1 fused: digests=1 percentagesQueried=3 <- pure loss ``` The extra `getPercentiles` work is small, but the plan also gets wider (`array(0.5, 0.5, 0.5)` plus three `GetArrayItem`) for zero gain, and this is a default-on rule. The mixed case is still a win and should keep firing: ``` SELECT percentile_approx(col, 0.5D) a, percentile_approx(col, 0.5D) b, percentile_approx(col, 0.9D) c FROM t base : digests=2 percentagesQueried=2 fused: digests=1 percentagesQueried=3 <- still worth it ``` So the condition wants distinct *evaluated* percentages, not distinct expressions — `array(0.5, 0.5)` and the `0.25 + 0.25` / `0.5` pair are both no-gain. Since `checkInputDataTypes` has already validated that every percentage is foldable and non-null, evaluating is safe here: ```scala expressions.sizeCompare(1) > 0 && expressions.map { expression => expression.aggregateFunction .asInstanceOf[ApproximatePercentile] .percentageExpression.eval() }.distinct.sizeCompare(1) > 0 && expressions.forall { expression => ``` Note this must stay a gate on *whether to fuse*, not a dedup of the array contents: `preserve duplicate and non-monotonic percentile order` depends on the fused array keeping one slot per original aggregate. Worth a test for the all-duplicates case — the suite covers repeated percentages only in `preserve duplicate and non-monotonic percentile order`, where a third distinct percentage makes fusion profitable anyway. -- 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]
