comphead commented on code in PR #7722:
URL: https://github.com/apache/datafusion-comet/pull/7722#discussion_r4743958558


##########
spark/src/test/scala/org/apache/comet/CometMapExpressionSuite.scala:
##########
@@ -261,6 +294,44 @@ class CometMapExpressionSuite extends CometTestBase {
     }
   }
 
+  test("float map builders use the settings captured when planning") {
+    assume(isSpark40Plus)
+    val policy = SQLConf.MAP_KEY_DEDUP_POLICY.key
+    val disableNormalization = "spark.sql.legacy.disableMapKeyNormalization"
+    withParquetTable(Seq((Seq(0.0, -0.0), Seq(1, 2))), "zero_keys") {
+      withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        policy -> "LAST_WIN",
+        disableNormalization -> "false") {
+        val df = sql(
+          "SELECT map_values(map_from_arrays(_1, _2)), " +
+            "map_values(map_from_entries(arrays_zip(_1, _2))) FROM zero_keys")
+        assertExpressionImpl(
+          df.queryExecution.executedPlan,
+          Seq("map_from_arrays", "map_from_entries"),
+          Seq.empty)
+        withSQLConf(policy -> "EXCEPTION", disableNormalization -> "true") {
+          assert(df.collect().toSeq == Seq(Row(Seq(2), Seq(2))))

Review Comment:
   This asserts `Row(Seq(2), Seq(2))` after switching to `EXCEPTION` and 
`disableMapKeyNormalization=true` on a plan built under `LAST_WIN`. Spark reads 
both settings when it builds the map on the executor, so I expect it to keep 
`0.0` and `-0.0` as two keys under those settings and return `Seq(1, 2)`. I did 
not run this. The docs call this case unsupported, so the assertion turns a 
known divergence into part of the test contract and will fail if Comet is later 
made to follow Spark. Keeping the `assertExpressionImpl` check on the planned 
query and dropping the final `collect` assertion, or renaming the test so it 
reads as a pin of current behavior, avoids that.



##########
spark/src/main/scala/org/apache/comet/serde/maps.scala:
##########
@@ -133,34 +135,106 @@ object CometMapExtract extends 
CometExpressionSerde[GetMapValue] {
   }
 }
 
-/**
- * Shared gate for the native map builders, `map_from_arrays` and 
`map_from_entries`, which tell
- * keys apart by their bits. A key type that holds a float at any depth is 
`Incompatible` on every
- * Spark version; `floatingPointReason` explains why.
- */
 private object MapBuilderKeySupport {
-  val floatingPointReason: String =
-    "Spark finds duplicate map keys that hold a `FLOAT` or `DOUBLE` by value, 
so NaNs with " +
-      "different bits are one key, and so are `-0.0` and `0.0` inside a struct 
or array key. " +
-      "From Spark 4.0, a `-0.0` key is also normalized to `0.0`, unless " +
-      "`spark.sql.legacy.disableMapKeyNormalization` is set. Comet's native 
map construction " +
-      "compares the keys' bits 
([#6549](https://github.com/apache/datafusion-comet/issues/6549))."
-
-  def hasFloatingPointKey(dataType: MapType): Boolean =
-    SupportLevel.containsType(dataType.keyType, classOf[FloatType], 
classOf[DoubleType])
+  def convertFloatMap(
+      expr: Expression,
+      inputs: Seq[Attribute],
+      binding: Boolean): Option[ExprOuterClass.Expr] = {
+    val normalize = isSpark40Plus &&
+      !SQLConf.get
+        .getConfString("spark.sql.legacy.disableMapKeyNormalization", "false")
+        .trim
+        .toBoolean
+    val args =
+      expr.children ++ Seq(Literal(normalize), 
Literal(MapKeyDedupPolicySupport.isLastWin))
+    val native = scalarFunctionExprToProto(
+      "spark_float_map",
+      args.map(exprToProtoInternal(_, inputs, binding)): _*)
+    withNullShortCircuit(expr, native).orElse {
+      CometScalaUDF.emitJvmCodegenDispatch(expr, inputs, binding)
+    }
+  }
+
+  val nestedFloatingPointReason: String =
+    "Spark compares a `FLOAT` or `DOUBLE` inside a struct or array key using 
SQL ordering, " +
+      "where signed zeros are equal and all NaNs are equal. Comet's native map 
builders " +
+      "compare their bits for these nested keys."
+
+  def isFloatingPoint(keyType: DataType): Boolean =
+    keyType == FloatType || keyType == DoubleType
+
+  private def isColumn(expr: Expression): Boolean = expr match {
+    case _: AttributeReference | _: BoundReference => true
+    case field: GetStructField => isColumn(field.child)
+    case _ => false
+  }
+
+  // Spark codegen emits canonical NaNs for scalar literals. Java 
serialization does the same
+  // for the boxed elements of folded GenericArrayData. Protobuf preserves 
their raw bits.
+  private def sparkPreservesLiteralBits(value: Any): Boolean = value match {
+    case f: Float => java.lang.Float.floatToRawIntBits(f) == 
java.lang.Float.floatToIntBits(f)
+    case d: Double =>
+      java.lang.Double.doubleToRawLongBits(d) == 
java.lang.Double.doubleToLongBits(d)
+    case a: GenericArrayData => a.array.forall(sparkPreservesLiteralBits)
+    case _ => true
+  }
+
+  // Constructors evaluate their children across the batch and can broadcast a 
large value
+  // before LAST_WIN discards it. Only build entries from fixed-width, eagerly 
evaluable fields.
+  private def safeElement(expr: Expression): Boolean = expr match {
+    case Literal(v, _) if !sparkPreservesLiteralBits(v) => false
+    case s: CreateNamedStruct => s.valExprs.nonEmpty && 
s.valExprs.forall(safeElement)
+    case _: UnaryMinus | _: Add | _: Subtract | _: Multiply =>
+      isFloatingPoint(expr.dataType) && expr.children.forall(safeElement)
+    case c: Cast if isFloatingPoint(c.dataType) =>
+      (c.child.dataType == NullType || 
c.child.dataType.isInstanceOf[NumericType]) &&
+      safeElement(c.child)
+    case _ =>
+      (expr.isInstanceOf[Literal] || isColumn(expr)) &&
+      (expr.dataType.isInstanceOf[DecimalType] || 
UnsafeRow.isFixedLength(expr.dataType))
+  }
+
+  private def simpleArray(expr: Expression): Boolean = expr match {
+    case array: CreateArray => array.children.forall(safeElement)
+    case _ => isColumn(expr)
+  }
+
+  // The outer null guard cannot prevent arrays_zip from evaluating an input 
in both its
+  // null check and its body. A stateful input can give different values on 
the second call.
+  private def safeInput(expr: Expression): Boolean = expr match {
+    case Literal(value, ArrayType(element, _)) =>
+      CometLiteral.listLiteralElementSupported(element) && 
sparkPreservesLiteralBits(value)
+    case zip: ArraysZip => zip.children.nonEmpty && 
zip.children.forall(simpleArray)
+    case _ => simpleArray(expr)
+  }

Review Comment:
   The `arrays_zip` case works around a hazard that is not specific to float 
keys. `CometArraysZip.convert` (`arrays.scala` lines 1402-1424) serializes each 
child for the zip body and again inside `IsNotNull(child)` for the guard, so a 
stateful child is evaluated twice for every `arrays_zip`, including 
`map_from_entries(arrays_zip(...))` with string or integer keys, which stay 
native with arbitrary inputs. Evaluating each child once in `CometArraysZip` 
would remove the `ArraysZip` case from this gate and the matching paragraph in 
`floating-point.md`. The `safeElement` restriction above (fixed-width fields 
and the `UnaryMinus`, `Add` and `Cast` allow list) is described as a 
peak-memory trade-off. For other key types `CometMapFromArrays.convert` 
serializes `expr.left` and `expr.right` with no such check, so the same 
`map_from_arrays(array(<wide value>, ...), ...)` shape is native for one key 
type and dispatched for another. The earlier review question about what this 
gate protects beyo
 nd `withNullShortCircuit` has no answer in the thread. Without a measurement 
that shows the expansion matters, I would drop the memory restriction and keep 
only the stateful-child and NaN-bits conditions.



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