andylam-db commented on code in PR #60634:
URL: https://github.com/apache/spark/pull/60634#discussion_r4648453893


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InsertVariantCanonicalization.scala:
##########
@@ -0,0 +1,230 @@
+/*
+ * 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.immutable.VectorMap
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, ArrayTransform, 
Attribute, CreateNamedStruct, Expression, GetStructField, If, IsNull, 
LambdaFunction, Literal, NamedExpression, NamedLambdaVariable, SortOrder, 
TransformValues}
+import 
org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, 
AggregateFunction}
+import org.apache.spark.sql.catalyst.expressions.variant.CanonicalizeVariant
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan, 
Project, RepartitionByExpression}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{AGGREGATE, 
REPARTITION_OPERATION}
+import org.apache.spark.sql.types.{ArrayType, MapType, StructType, VariantType}
+import org.apache.spark.util.ArrayImplicits.SparkArrayOps
+
+/**
+ * Adds [[CanonicalizeVariant]] to grouping expressions and distinct aggregate 
arguments that
+ * contain Variant values, ensuring logically equal Variants have identical 
bytes before
+ * aggregation:
+ *
+ * SELECT variant_column, COUNT(*) FROM TABLE GROUP BY variant_column =>
+ * SELECT _groupingvariantcanonicalization AS variant_column, COUNT(*) FROM (
+ *   SELECT canonicalize_variant(variant_column) AS 
_groupingvariantcanonicalization FROM TABLE
+ * ) GROUP BY _groupingvariantcanonicalization
+ *
+ * SELECT COUNT(DISTINCT variant_column) FROM TABLE =>
+ * SELECT COUNT(DISTINCT _distinctvariantcanonicalization) FROM (
+ *   SELECT canonicalize_variant(variant_column) AS 
_distinctvariantcanonicalization FROM TABLE
+ * )
+ *
+ * This rule runs after [[PullOutGroupingExpressions]], so grouping keys are 
attributes or
+ * literals. Distinct arguments are normalized here instead of in 
[[RewriteDistinctAggregates]]
+ * because a single distinct group without a filter bypasses that rule and is 
handled by the
+ * physical planner.
+ */
+object InsertVariantCanonicalizationInAggregate extends Rule[LogicalPlan] {

Review Comment:
   Consider this query once GROUP BY accepts Variant keys:
   
   ```
   SELECT schema_of_variant_agg(v)
   FROM (
     SELECT CAST(CAST(id AS DECIMAL(10, 1)) AS VARIANT) AS v
     FROM range(1, 3)
   )
   GROUP BY v;
   ```
    The input contains decimal Variants for 1.0 and 2.0. Each gets its own 
group. The existing aggregate would report a DECIMAL schema for each group. But 
CanonicalizeVariant converts these integer-valued decimals to longs, so if the 
aggregate reads the canonicalized values, it reports BIGINT for both groups. 
The grouping is correct and the returned schemas are wrong.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -234,6 +234,11 @@ abstract class Optimizer(catalogManager: CatalogManager)
       ReplaceExceptWithFilter,
       ReplaceExceptWithAntiJoin,
       ReplaceDistinctWithAggregate),
+    // This batch must run after "Replace Operators", as that one turns 
Distinct and Deduplicate
+    // into Aggregate.
+    Batch("Insert Variant Canonicalization", FixedPoint(1),
+      InsertVariantCanonicalizationInAggregate,
+      InsertVariantCanonicalizationInRepartitionExpressions),

Review Comment:
   Another problem with this rewrite;
    
   Consider COUNT(DISTINCT v) FILTER (WHERE false), where v is a constant, 
valid Variant. Some valid Variants share storage internally. Rebuilding one 
into its canonical encoding can expand it past Spark’s
   size limit.
   
   • Base Spark removes the always-false aggregate and returns 0.
   • With the PR, the optimizer puts CanonicalizeVariant(v) in a separate 
projection below the aggregate.  Constant folding evaluates that projection 
before Spark removes the always-false aggregate, so it can  throw 
VARIANT_CONSTRUCTOR_SIZE_LIMIT.



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