|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.sql.catalyst.optimizer |
| 19 | + |
| 20 | +import org.apache.spark.sql.catalyst.expressions.{Alias, And, ArrayTransform, CreateArray, CreateMap, CreateNamedStruct, CreateNamedStructUnsafe, CreateStruct, EqualTo, ExpectsInputTypes, Expression, GetStructField, LambdaFunction, NamedLambdaVariable, UnaryExpression} |
| 21 | +import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, ExprCode} |
| 22 | +import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys |
| 23 | +import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Subquery, Window} |
| 24 | +import org.apache.spark.sql.catalyst.rules.Rule |
| 25 | +import org.apache.spark.sql.types._ |
| 26 | + |
| 27 | +/** |
| 28 | + * We need to take care of special floating numbers (NaN and -0.0) in several places: |
| 29 | + * 1. When compare values, different NaNs should be treated as same, `-0.0` and `0.0` should be |
| 30 | + * treated as same. |
| 31 | + * 2. In aggregate grouping keys, different NaNs should belong to the same group, -0.0 and 0.0 |
| 32 | + * should belong to the same group. |
| 33 | + * 3. In join keys, different NaNs should be treated as same, `-0.0` and `0.0` should be |
| 34 | + * treated as same. |
| 35 | + * 4. In window partition keys, different NaNs should belong to the same partition, -0.0 and 0.0 |
| 36 | + * should belong to the same partition. |
| 37 | + * |
| 38 | + * Case 1 is fine, as we handle NaN and -0.0 well during comparison. For complex types, we |
| 39 | + * recursively compare the fields/elements, so it's also fine. |
| 40 | + * |
| 41 | + * Case 2, 3 and 4 are problematic, as Spark SQL turns grouping/join/window partition keys into |
| 42 | + * binary `UnsafeRow` and compare the binary data directly. Different NaNs have different binary |
| 43 | + * representation, and the same thing happens for -0.0 and 0.0. |
| 44 | + * |
| 45 | + * This rule normalizes NaN and -0.0 in window partition keys, join keys and aggregate grouping |
| 46 | + * keys. |
| 47 | + * |
| 48 | + * Ideally we should do the normalization in the physical operators that compare the |
| 49 | + * binary `UnsafeRow` directly. We don't need this normalization if the Spark SQL execution engine |
| 50 | + * is not optimized to run on binary data. This rule is created to simplify the implementation, so |
| 51 | + * that we have a single place to do normalization, which is more maintainable. |
| 52 | + * |
| 53 | + * Note that, this rule must be executed at the end of optimizer, because the optimizer may create |
| 54 | + * new joins(the subquery rewrite) and new join conditions(the join reorder). |
| 55 | + */ |
| 56 | +object NormalizeFloatingNumbers extends Rule[LogicalPlan] { |
| 57 | + |
| 58 | + def apply(plan: LogicalPlan): LogicalPlan = plan match { |
| 59 | + // A subquery will be rewritten into join later, and will go through this rule |
| 60 | + // eventually. Here we skip subquery, as we only need to run this rule once. |
| 61 | + case _: Subquery => plan |
| 62 | + |
| 63 | + case _ => plan transform { |
| 64 | + case w: Window if w.partitionSpec.exists(p => needNormalize(p.dataType)) => |
| 65 | + // Although the `windowExpressions` may refer to `partitionSpec` expressions, we don't need |
| 66 | + // to normalize the `windowExpressions`, as they are executed per input row and should take |
| 67 | + // the input row as it is. |
| 68 | + w.copy(partitionSpec = w.partitionSpec.map(normalize)) |
| 69 | + |
| 70 | + // Only hash join and sort merge join need the normalization. Here we catch all Joins with |
| 71 | + // join keys, assuming Joins with join keys are always planned as hash join or sort merge |
| 72 | + // join. It's very unlikely that we will break this assumption in the near future. |
| 73 | + case j @ ExtractEquiJoinKeys(_, leftKeys, rightKeys, condition, _, _, _) |
| 74 | + // The analyzer guarantees left and right joins keys are of the same data type. Here we |
| 75 | + // only need to check join keys of one side. |
| 76 | + if leftKeys.exists(k => needNormalize(k.dataType)) => |
| 77 | + val newLeftJoinKeys = leftKeys.map(normalize) |
| 78 | + val newRightJoinKeys = rightKeys.map(normalize) |
| 79 | + val newConditions = newLeftJoinKeys.zip(newRightJoinKeys).map { |
| 80 | + case (l, r) => EqualTo(l, r) |
| 81 | + } ++ condition |
| 82 | + j.copy(condition = Some(newConditions.reduce(And))) |
| 83 | + |
| 84 | + // TODO: ideally Aggregate should also be handled here, but its grouping expressions are |
| 85 | + // mixed in its aggregate expressions. It's unreliable to change the grouping expressions |
| 86 | + // here. For now we normalize grouping expressions in `AggUtils` during planning. |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + private def needNormalize(dt: DataType): Boolean = dt match { |
| 91 | + case FloatType | DoubleType => true |
| 92 | + case StructType(fields) => fields.exists(f => needNormalize(f.dataType)) |
| 93 | + case ArrayType(et, _) => needNormalize(et) |
| 94 | + // Currently MapType is not comparable and analyzer should fail earlier if this case happens. |
| 95 | + case _: MapType => |
| 96 | + throw new IllegalStateException("grouping/join/window partition keys cannot be map type.") |
| 97 | + case _ => false |
| 98 | + } |
| 99 | + |
| 100 | + private[sql] def normalize(expr: Expression): Expression = expr match { |
| 101 | + case _ if expr.dataType == FloatType || expr.dataType == DoubleType => |
| 102 | + NormalizeNaNAndZero(expr) |
| 103 | + |
| 104 | + case CreateNamedStruct(children) => |
| 105 | + CreateNamedStruct(children.map(normalize)) |
| 106 | + |
| 107 | + case CreateNamedStructUnsafe(children) => |
| 108 | + CreateNamedStructUnsafe(children.map(normalize)) |
| 109 | + |
| 110 | + case CreateArray(children) => |
| 111 | + CreateArray(children.map(normalize)) |
| 112 | + |
| 113 | + case CreateMap(children) => |
| 114 | + CreateMap(children.map(normalize)) |
| 115 | + |
| 116 | + case a: Alias if needNormalize(a.dataType) => |
| 117 | + a.withNewChildren(Seq(normalize(a.child))) |
| 118 | + |
| 119 | + case _ if expr.dataType.isInstanceOf[StructType] && needNormalize(expr.dataType) => |
| 120 | + val fields = expr.dataType.asInstanceOf[StructType].fields.indices.map { i => |
| 121 | + normalize(GetStructField(expr, i)) |
| 122 | + } |
| 123 | + CreateStruct(fields) |
| 124 | + |
| 125 | + case _ if expr.dataType.isInstanceOf[ArrayType] && needNormalize(expr.dataType) => |
| 126 | + val ArrayType(et, containsNull) = expr.dataType |
| 127 | + val lv = NamedLambdaVariable("arg", et, containsNull) |
| 128 | + val function = normalize(lv) |
| 129 | + ArrayTransform(expr, LambdaFunction(function, Seq(lv))) |
| 130 | + |
| 131 | + case _ => expr |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +case class NormalizeNaNAndZero(child: Expression) extends UnaryExpression with ExpectsInputTypes { |
| 136 | + |
| 137 | + override def dataType: DataType = child.dataType |
| 138 | + |
| 139 | + override def inputTypes: Seq[AbstractDataType] = Seq(TypeCollection(FloatType, DoubleType)) |
| 140 | + |
| 141 | + private lazy val normalizer: Any => Any = child.dataType match { |
| 142 | + case FloatType => (input: Any) => { |
| 143 | + val f = input.asInstanceOf[Float] |
| 144 | + if (f.isNaN) { |
| 145 | + Float.NaN |
| 146 | + } else if (f == -0.0f) { |
| 147 | + 0.0f |
| 148 | + } else { |
| 149 | + f |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + case DoubleType => (input: Any) => { |
| 154 | + val d = input.asInstanceOf[Double] |
| 155 | + if (d.isNaN) { |
| 156 | + Double.NaN |
| 157 | + } else if (d == -0.0d) { |
| 158 | + 0.0d |
| 159 | + } else { |
| 160 | + d |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + override def nullSafeEval(input: Any): Any = { |
| 166 | + normalizer(input) |
| 167 | + } |
| 168 | + |
| 169 | + override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { |
| 170 | + val codeToNormalize = child.dataType match { |
| 171 | + case FloatType => (f: String) => { |
| 172 | + s""" |
| 173 | + |if (Float.isNaN($f)) { |
| 174 | + | ${ev.value} = Float.NaN; |
| 175 | + |} else if ($f == -0.0f) { |
| 176 | + | ${ev.value} = 0.0f; |
| 177 | + |} else { |
| 178 | + | ${ev.value} = $f; |
| 179 | + |} |
| 180 | + """.stripMargin |
| 181 | + } |
| 182 | + |
| 183 | + case DoubleType => (d: String) => { |
| 184 | + s""" |
| 185 | + |if (Double.isNaN($d)) { |
| 186 | + | ${ev.value} = Double.NaN; |
| 187 | + |} else if ($d == -0.0d) { |
| 188 | + | ${ev.value} = 0.0d; |
| 189 | + |} else { |
| 190 | + | ${ev.value} = $d; |
| 191 | + |} |
| 192 | + """.stripMargin |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + nullSafeCodeGen(ctx, ev, codeToNormalize) |
| 197 | + } |
| 198 | +} |
0 commit comments