cboumalh commented on code in PR #52883:
URL: https://github.com/apache/spark/pull/52883#discussion_r2713395351


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/TupleSketchUtils.scala:
##########
@@ -0,0 +1,331 @@
+/*
+ * 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.util
+
+import java.util.Locale
+
+import org.apache.datasketches.memory.{Memory, MemoryBoundsException}
+import org.apache.datasketches.tuple.{Sketch, Sketches, Summary, 
TupleSketchIterator}
+import org.apache.datasketches.tuple.adouble.{DoubleSummary, 
DoubleSummaryDeserializer}
+import org.apache.datasketches.tuple.aninteger.{IntegerSummary, 
IntegerSummaryDeserializer}
+
+import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
+import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateFunction
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Sealed trait representing valid summary modes for tuple sketches. This 
provides type-safe
+ * mode handling with compile-time exhaustiveness checking and prevents 
invalid modes from
+ * being created.
+ */
+sealed trait TupleSummaryMode {
+  def toDoubleSummaryMode: DoubleSummary.Mode
+
+  def toIntegerSummaryMode: IntegerSummary.Mode
+
+  def toString: String
+}
+
+object TupleSummaryMode {
+  case object Sum extends TupleSummaryMode {
+    def toDoubleSummaryMode: DoubleSummary.Mode = DoubleSummary.Mode.Sum
+    def toIntegerSummaryMode: IntegerSummary.Mode = IntegerSummary.Mode.Sum
+    override def toString: String = "sum"
+  }
+
+  case object Min extends TupleSummaryMode {
+    def toDoubleSummaryMode: DoubleSummary.Mode = DoubleSummary.Mode.Min
+    def toIntegerSummaryMode: IntegerSummary.Mode = IntegerSummary.Mode.Min
+    override def toString: String = "min"
+  }
+
+  case object Max extends TupleSummaryMode {
+    def toDoubleSummaryMode: DoubleSummary.Mode = DoubleSummary.Mode.Max
+    def toIntegerSummaryMode: IntegerSummary.Mode = IntegerSummary.Mode.Max
+    override def toString: String = "max"
+  }
+
+  case object AlwaysOne extends TupleSummaryMode {
+    def toDoubleSummaryMode: DoubleSummary.Mode = DoubleSummary.Mode.AlwaysOne
+    def toIntegerSummaryMode: IntegerSummary.Mode = 
IntegerSummary.Mode.AlwaysOne
+    override def toString: String = "alwaysone"
+  }
+
+  /** All valid modes */
+  val validModes: Seq[TupleSummaryMode] = Seq(Sum, Min, Max, AlwaysOne)
+
+  /** String representations of valid modes for error messages */
+  val validModeStrings: Seq[String] = validModes.map(_.toString)
+
+  /**
+   * Parses a string into a TupleSummaryMode. This is the single entry point 
for string-to-mode
+   * conversion, ensuring validation happens once.
+   *
+   * @param s The mode string to parse
+   * @param functionName The display name of the function/expression for error 
messages
+   * @return The corresponding TupleSummaryMode
+   * @throws QueryExecutionErrors.tupleInvalidMode if the mode string is 
invalid
+   */
+  def fromString(s: String, functionName: String): TupleSummaryMode = {
+    s.toLowerCase(Locale.ROOT) match {
+      case "sum" => Sum
+      case "min" => Min
+      case "max" => Max
+      case "alwaysone" => AlwaysOne
+      case _ => throw QueryExecutionErrors.tupleInvalidMode(functionName, s, 
validModeStrings)
+    }
+  }
+}
+
+/**
+ * Trait for TupleSketch aggregation functions that use the lgNomEntries 
parameter. Provides
+ * validation and extraction functionality for the log-base-2 of nominal 
entries.
+ */
+trait SketchSize extends AggregateFunction {
+
+  /** log-base-2 of nominal entries (determines sketch size). */
+  def lgNomEntries: Expression
+
+  /** Returns the pretty name of the aggregation function for error messages. 
*/
+  protected def prettyName: String
+
+  /**
+   * Validates that lgNomEntries parameter is a constant and within valid 
range (4-26).
+   */
+  protected def checkLgNomEntriesParameter(): TypeCheckResult = {
+    if (!lgNomEntries.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> "lgNomEntries",
+          "inputType" -> "int",
+          "inputExpr" -> lgNomEntries.sql))
+    } else if (lgNomEntries.eval() == null) {
+      DataTypeMismatch(
+        errorSubClass = "UNEXPECTED_NULL",
+        messageParameters = Map("exprName" -> "lgNomEntries"))
+    } else {
+      try {
+        ThetaSketchUtils.checkLgNomLongs(lgNomEntriesInput, prettyName)
+        TypeCheckResult.TypeCheckSuccess
+      } catch {
+        case e: Exception =>
+          TypeCheckResult.TypeCheckFailure(e.getMessage)

Review Comment:
   Since this code runs during query analysis/type-checking (before any data is 
processed), so it only validates user values, no sensitive internal state or 
memory offsets are accessible at this point. The null check at line 184 already 
prevents NPE, and `ClassCastException` should never occur because Spark 
validates inputTypes during analysis. If it does happen, it indicates an 
internal framework bug rather than a user error. The only expected exception is 
from `TupleSummaryMode.fromString()` which already provides a user-friendly 
error message.



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