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


##########
spark/src/main/scala/org/apache/spark/sql/comet/MapCodegenStage.scala:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.comet
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+import scala.util.control.NonFatal
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.expressions.codegen.CodeGenerator
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.HashAggregateExec
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+import org.apache.comet.serde.{ExprOuterClass, ProtoMessageVisitor}
+import org.apache.comet.serde.OperatorOuterClass.Operator
+
+/** The original Spark stage that determines when a map builder reads its 
settings. */
+private[apache] final class MapCodegenStage private (stage: 
WholeStageCodegenExec) {
+  def fits(limit: Int): Boolean = {
+    // CodegenSupport.produce mutates the plan. Give each RDD construction its 
own copy.
+    val copy = 
stage.session.withActive(stage.clone().asInstanceOf[WholeStageCodegenExec])
+    val source = copy.doCodeGen()._2
+    try {
+      CodeGenerator.compile(source)._2.maxMethodCodeSize <= limit
+    } catch {
+      case NonFatal(_) if !Utils.isTesting && copy.conf.codegenFallback => 
false

Review Comment:
   Under `Utils.isTesting`, a compile failure here fails the query, while in 
production it falls back. So tests and production take different paths through 
this code.



##########
spark/src/main/scala/org/apache/comet/serde/maps.scala:
##########
@@ -133,34 +144,197 @@ 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])
+private[comet] object MapBuilderKeySupport {
+  private val taskPolicy = CometScalarFunction[Expression](Policy.Task)
+  private val driverPolicy = CometScalarFunction[Expression](Policy.Driver)
+
+  private type Policies = IdentityHashMap[Expression, Option[Policy]]
+  private class Context(plan: SparkPlan) {
+    var used: Option[Policy] = None
+    lazy val policies: Policies = builderPolicies(plan)
+  }
+  private val context = new DynamicVariable[Option[Context]](None)
+
+  // AQE forms codegen stages after query stage preparation, possibly with 
different settings.
+  def withPlan(plan: SparkPlan, queryStagePrep: Boolean)(f: => SparkPlan): 
SparkPlan =

Review Comment:
   When this runs as the AQE query-stage-prep rule, the context is `None`, so 
`select` returns `None` and the builder reports `Incompatible(policyReason)`. 
With AQE on (the default), any plan with an exchange dispatches, as the test at 
`CometMapExpressionSuite.scala:454` pins. So `map_from_arrays(collect_list(k), 
collect_list(v))`, probably the most common use, never reaches the native 
kernel.



##########
native/spark-expr/src/map_funcs/float_map.rs:
##########
@@ -0,0 +1,433 @@
+// 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.
+
+use std::{hash::Hash, sync::Arc};
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, Int32Array, ListArray, MapArray, 
NullBufferBuilder, PrimitiveArray,
+    StructArray,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer};
+use arrow::compute::{cast, take};
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, 
Float32Type, Float64Type};
+use datafusion::common::cast::{as_list_array, as_struct_array};
+use datafusion::common::config::MapKeyDedupPolicy;
+use datafusion::common::{exec_err, internal_err, HashMap, Result};
+use datafusion::logical_expr::function::Hint;
+use datafusion::logical_expr::{
+    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, 
Signature, TypeSignature,
+    Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use datafusion_spark::function::map::{
+    map_from_arrays::MapFromArrays, map_from_entries::MapFromEntries,
+};
+
+use crate::conversion_funcs::{java_float_string, JavaFloatString};
+use crate::float_semantics::{canonicalize_nan, normalize_float};
+use crate::SparkError;
+
+/// Spark map construction for a top-level FLOAT or DOUBLE key.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkFloatMap {
+    name: &'static str,
+    signature: Signature,
+    normalize: bool,
+    last_win: bool,
+}
+
+impl SparkFloatMap {
+    pub fn new(name: &'static str, normalize: bool, policy: MapKeyDedupPolicy) 
-> Self {
+        Self {
+            name,
+            signature: Signature::one_of(
+                vec![TypeSignature::Any(1), TypeSignature::Any(2)],
+                Volatility::Immutable,
+            ),
+            normalize,
+            last_win: policy == MapKeyDedupPolicy::LastWin,
+        }
+    }
+
+    fn build(&self, args: &[ArrayRef]) -> Result<ArrayRef> {
+        let lists = args.iter().map(to_list).collect::<Result<Vec<_>>>()?;
+        let input = match lists.as_slice() {
+            [keys, values] => MapInput {
+                key_rows: keys,
+                value_rows: values,
+                keys: keys.values(),
+                values: values.values(),
+                entry_nulls: None,
+                from_arrays: true,
+            },
+            [rows] => {
+                let entries = as_struct_array(rows.values())?;
+                let [keys, values] = entries.columns() else {
+                    return exec_err!("{}: expected key-value pairs", 
self.name());
+                };
+                MapInput {
+                    key_rows: rows,
+                    value_rows: rows,
+                    keys,
+                    values,
+                    entry_nulls: entries.nulls(),
+                    from_arrays: false,
+                }
+            }
+            _ => return exec_err!("{}: expected one or two arguments", 
self.name()),
+        };
+        match input.keys.data_type() {
+            DataType::Float32 => self.build_typed::<Float32Type, _>(input, 
f32::to_bits),
+            DataType::Float64 => self.build_typed::<Float64Type, _>(input, 
f64::to_bits),
+            dt => exec_err!("{}: expected floating-point keys, got {dt}", 
self.name()),
+        }
+    }
+
+    fn build_typed<T, Bits>(
+        &self,
+        input: MapInput,
+        bits: impl Fn(T::Native) -> Bits,
+    ) -> Result<ArrayRef>
+    where
+        T: ArrowPrimitiveType,
+        T::Native: JavaFloatString,
+        Bits: Eq + Hash,
+    {
+        let keys = input.keys.as_primitive::<T>();
+        let key_offsets = input.key_rows.value_offsets();
+        let value_offsets = input.value_rows.value_offsets();
+        let first_key = key_offsets[0] as usize;
+        let first_value = value_offsets[0];
+        let raw_keys = &keys.values()[first_key..];
+        let num_rows = match input.key_rows.len() {
+            1 => input.value_rows.len(),
+            n => n,
+        };
+
+        // Both outputs start as slices of the input. Materialize each 
independently once
+        // a changed key or a non-contiguous value breaks that invariant.
+        let mut output_keys = None;
+        let mut value_indices = None;
+        let mut len = 0;
+        let mut offsets = Vec::with_capacity(num_rows + 1);
+        let mut nulls = NullBufferBuilder::new(num_rows);
+        let mut positions = HashMap::new();
+        for row in 0..num_rows {
+            let key_row = if input.key_rows.len() == 1 { 0 } else { row };
+            let value_row = if input.value_rows.len() == 1 { 0 } else { row };
+            let start = len;
+            offsets.push(start as i32);
+            let key_range = key_offsets[key_row] as usize..key_offsets[key_row 
+ 1] as usize;
+            let value_range = 
value_offsets[value_row]..value_offsets[value_row + 1];
+            let count = key_range.len();
+            if input.key_rows.is_null(key_row)
+                || input.value_rows.is_null(value_row)
+                || input
+                    .entry_nulls
+                    .is_some_and(|nulls| nulls.slice(key_range.start, 
count).null_count() != 0)
+            {
+                nulls.append_null();
+                continue;
+            }
+            nulls.append_non_null();
+            if count != value_range.len() {
+                return Err(SparkError::MapKeyValueDiffSizes.into());
+            }
+
+            positions.clear();
+            // Bound the cost of clearing the table on subsequent rows after a 
large map.
+            positions.shrink_to(count);

Review Comment:
   If row sizes alternate, `shrink_to(count)` reallocates on almost every row. 
Shrinking only when the capacity is far above `count` would avoid that.



##########
spark/src/main/scala/org/apache/comet/serde/maps.scala:
##########
@@ -133,34 +144,197 @@ 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])
+private[comet] object MapBuilderKeySupport {
+  private val taskPolicy = CometScalarFunction[Expression](Policy.Task)
+  private val driverPolicy = CometScalarFunction[Expression](Policy.Driver)
+
+  private type Policies = IdentityHashMap[Expression, Option[Policy]]
+  private class Context(plan: SparkPlan) {
+    var used: Option[Policy] = None
+    lazy val policies: Policies = builderPolicies(plan)
+  }
+  private val context = new DynamicVariable[Option[Context]](None)
+
+  // AQE forms codegen stages after query stage preparation, possibly with 
different settings.
+  def withPlan(plan: SparkPlan, queryStagePrep: Boolean)(f: => SparkPlan): 
SparkPlan =
+    context.withValue(if (queryStagePrep) None else Some(new Context(plan)))(f)
+
+  private def select(expr: Expression): Option[Policy] =
+    context.value.flatMap(_.policies.getOrDefault(expr, None))
+
+  // Every admitted builder belonging to one operator has the same stage and 
consumers.
+  def record(f: => Option[CometNativeExec]): Option[CometNativeExec] = 
context.value match {
+    case None => f
+    case Some(ctx) =>
+      val outer = ctx.used
+      ctx.used = None
+      try {
+        val result = f
+        result.foreach(exec => ctx.used.foreach(_.record(exec)))
+        result
+      } finally {
+        ctx.used = outer
+      }
+  }
+
+  private def builderPolicies(plan: SparkPlan): Policies = {
+    val policies = new Policies
+    // Converted inputs and materialized stages can hide Spark's original 
columnar transitions.
+    if (plan.exists(p => p.isInstanceOf[CometPlan] || 
p.isInstanceOf[QueryStageExec])) {
+      return policies
+    }
+    val conf = SQLConf.get
+    if (conf.getConf(SQLConf.CODEGEN_FACTORY_MODE).toString == "NO_CODEGEN") 
return policies
+
+    // Walk the stages Spark would form before Comet replaces scans or fuses 
operators.
+    // None for consumers means the first insertion can happen in an unknown 
scope.
+    def visit(
+        node: SparkPlan,
+        stage: Option[MapCodegenStage],
+        consumers: Option[List[MapCodegenStage]]): Unit = node match {
+      case generated: WholeStageCodegenExec =>
+        val probe = MapCodegenStage.probe(generated)
+        visit(generated.child, probe, consumers.filter(_ => probe.isDefined))
+      case adapter: InputAdapter => visit(adapter.child, None, consumers)
+      case _ =>
+        val inputConsumers = node match {
+          case _: Exchange => Some(Nil)
+          case _: ProjectExec | _: FilterExec | _: DeserializeToObjectExec | 
_: LocalLimitExec |
+              _: GlobalLimitExec | _: CollectLimitExec | _: ExpandExec | _: 
ColumnarToRowExec |
+              _: RowToColumnarExec =>
+            consumers
+          case _: HashAggregateExec | _: SortExec =>
+            for (outer <- consumers; current <- stage) yield current :: outer
+          case _ => None
+        }
+        val policy = node match {
+          case _: ProjectExec | _: FilterExec => consumers.map(Policy(stage, 
_))
+          case _: ExpandExec if stage.isDefined => consumers.map(Policy(stage, 
_))
+          case _: HashAggregateExec => inputConsumers.map(Policy(stage, _))
+          case _ => None
+        }
+        def recordExpression(expr: Expression, interpreted: Boolean): Unit = {
+          expr match {
+            case _: MapFromArrays | _: MapFromEntries =>
+              val selected = if (interpreted) None else policy
+              val previous = policies.getOrDefault(expr, selected)
+              val _ = policies.put(expr, if (previous == selected) selected 
else None)
+            case _ =>
+          }
+          expr.children.foreach(
+            recordExpression(_, interpreted || 
expr.isInstanceOf[CodegenFallback]))
+        }
+        node.expressions.foreach(recordExpression(_, interpreted = false))
+        node match {
+          case agg: HashAggregateExec =>
+            // A fallback aggregate evaluates result expressions eagerly only 
for empty input.
+            agg.resultExpressions.foreach(recordExpression(_, interpreted = 
true))
+          case _ =>
+        }
+        node.children.foreach(visit(_, stage, inputConsumers))
+    }
+    visit(MapCodegenStage.prepare(plan), None, Some(Nil))
+    policies
+  }
+
+  def convertFloatMap(
+      expr: Expression,
+      inputs: Seq[Attribute],
+      binding: Boolean): Option[ExprOuterClass.Expr] = {
+    val policy = select(expr)
+    val native = if (policy.exists(_.stage.isDefined)) driverPolicy else 
taskPolicy
+    val result = withNullShortCircuit(expr, native.convert(expr, inputs, 
binding))
+    if (result.isDefined && policy.isDefined) context.value.foreach(_.used = 
policy)
+    result.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)
+  }
+
+  private def safeInput(expr: Expression): Boolean = expr match {

Review Comment:
   These input rules apply only to float keys, so which inputs the same 
expression accepts now depends on its key type. `convertFloatMap` already 
applies `withNullShortCircuit`. What does this gate protect against beyond 
that? The protection against expanding wide values looks like a performance 
trade-off, not a correctness one.



##########
docs/source/user-guide/latest/compatibility/floating-point.md:
##########
@@ -179,8 +179,24 @@ array whose elements cannot be null in ascending order, 
Spark's generated code p
 
 ## Map construction
 
-`map_from_arrays` and `map_from_entries` don't build a map natively when its 
key type holds a
-`FLOAT` or `DOUBLE` at any depth. They run Spark's code through the codegen 
dispatcher instead, so
-duplicate keys, including NaNs and zeros of either sign, behave as in Spark. 
`FLOAT` and `DOUBLE`
-values don't affect either function. The expressions' entries in the
-[expression compatibility guide](expressions/map.md) give the reason.
+`map_from_arrays` and `map_from_entries` support `FLOAT` and `DOUBLE` keys in 
Rust under both
+`spark.sql.mapKeyDedupPolicy` settings. All NaNs represent the same key. On 
Spark 4.0 and later,
+the builders also treat `-0.0` and `0.0` as the same key unless
+`spark.sql.legacy.disableMapKeyNormalization=true`.
+
+With normalization enabled, `map_from_entries` stores `0.0` for a `-0.0` key 
and the canonical
+NaN for any NaN key. Like Spark, `map_from_arrays` preserves the original keys 
when they are
+distinct. When `LAST_WIN` removes a duplicate, it stores normalized keys 
throughout that map.
+
+Comet selects Rust for projections, filters, generated hash aggregate inputs 
and expands when

Review Comment:
   This paragraph describes planner internals ("generated hash aggregate inputs 
and expands with known consumers") that users can't act on. It would be enough 
to say when the builders fall back to dispatch, for example under AQE with an 
exchange.



##########
native/spark-expr/src/map_funcs/float_map.rs:
##########
@@ -0,0 +1,433 @@
+// 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.
+
+use std::{hash::Hash, sync::Arc};
+
+use arrow::array::{
+    Array, ArrayRef, AsArray, Int32Array, ListArray, MapArray, 
NullBufferBuilder, PrimitiveArray,
+    StructArray,
+};
+use arrow::buffer::{NullBuffer, OffsetBuffer};
+use arrow::compute::{cast, take};
+use arrow::datatypes::{ArrowPrimitiveType, DataType, Field, FieldRef, 
Float32Type, Float64Type};
+use datafusion::common::cast::{as_list_array, as_struct_array};
+use datafusion::common::config::MapKeyDedupPolicy;
+use datafusion::common::{exec_err, internal_err, HashMap, Result};
+use datafusion::logical_expr::function::Hint;
+use datafusion::logical_expr::{
+    ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, 
Signature, TypeSignature,
+    Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use datafusion_spark::function::map::{
+    map_from_arrays::MapFromArrays, map_from_entries::MapFromEntries,
+};
+
+use crate::conversion_funcs::{java_float_string, JavaFloatString};
+use crate::float_semantics::{canonicalize_nan, normalize_float};
+use crate::SparkError;
+
+/// Spark map construction for a top-level FLOAT or DOUBLE key.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkFloatMap {
+    name: &'static str,
+    signature: Signature,
+    normalize: bool,
+    last_win: bool,
+}
+
+impl SparkFloatMap {
+    pub fn new(name: &'static str, normalize: bool, policy: MapKeyDedupPolicy) 
-> Self {
+        Self {
+            name,
+            signature: Signature::one_of(
+                vec![TypeSignature::Any(1), TypeSignature::Any(2)],
+                Volatility::Immutable,
+            ),
+            normalize,
+            last_win: policy == MapKeyDedupPolicy::LastWin,
+        }
+    }
+
+    fn build(&self, args: &[ArrayRef]) -> Result<ArrayRef> {
+        let lists = args.iter().map(to_list).collect::<Result<Vec<_>>>()?;
+        let input = match lists.as_slice() {
+            [keys, values] => MapInput {
+                key_rows: keys,
+                value_rows: values,
+                keys: keys.values(),
+                values: values.values(),
+                entry_nulls: None,
+                from_arrays: true,
+            },
+            [rows] => {
+                let entries = as_struct_array(rows.values())?;
+                let [keys, values] = entries.columns() else {
+                    return exec_err!("{}: expected key-value pairs", 
self.name());
+                };
+                MapInput {
+                    key_rows: rows,
+                    value_rows: rows,
+                    keys,
+                    values,
+                    entry_nulls: entries.nulls(),
+                    from_arrays: false,
+                }
+            }
+            _ => return exec_err!("{}: expected one or two arguments", 
self.name()),
+        };
+        match input.keys.data_type() {
+            DataType::Float32 => self.build_typed::<Float32Type, _>(input, 
f32::to_bits),
+            DataType::Float64 => self.build_typed::<Float64Type, _>(input, 
f64::to_bits),
+            dt => exec_err!("{}: expected floating-point keys, got {dt}", 
self.name()),
+        }
+    }
+
+    fn build_typed<T, Bits>(
+        &self,
+        input: MapInput,
+        bits: impl Fn(T::Native) -> Bits,
+    ) -> Result<ArrayRef>
+    where
+        T: ArrowPrimitiveType,
+        T::Native: JavaFloatString,
+        Bits: Eq + Hash,
+    {
+        let keys = input.keys.as_primitive::<T>();
+        let key_offsets = input.key_rows.value_offsets();
+        let value_offsets = input.value_rows.value_offsets();
+        let first_key = key_offsets[0] as usize;
+        let first_value = value_offsets[0];
+        let raw_keys = &keys.values()[first_key..];
+        let num_rows = match input.key_rows.len() {
+            1 => input.value_rows.len(),
+            n => n,
+        };
+
+        // Both outputs start as slices of the input. Materialize each 
independently once
+        // a changed key or a non-contiguous value breaks that invariant.
+        let mut output_keys = None;
+        let mut value_indices = None;
+        let mut len = 0;
+        let mut offsets = Vec::with_capacity(num_rows + 1);
+        let mut nulls = NullBufferBuilder::new(num_rows);
+        let mut positions = HashMap::new();
+        for row in 0..num_rows {
+            let key_row = if input.key_rows.len() == 1 { 0 } else { row };
+            let value_row = if input.value_rows.len() == 1 { 0 } else { row };
+            let start = len;
+            offsets.push(start as i32);
+            let key_range = key_offsets[key_row] as usize..key_offsets[key_row 
+ 1] as usize;
+            let value_range = 
value_offsets[value_row]..value_offsets[value_row + 1];
+            let count = key_range.len();
+            if input.key_rows.is_null(key_row)
+                || input.value_rows.is_null(value_row)
+                || input
+                    .entry_nulls
+                    .is_some_and(|nulls| nulls.slice(key_range.start, 
count).null_count() != 0)
+            {
+                nulls.append_null();
+                continue;
+            }
+            nulls.append_non_null();
+            if count != value_range.len() {
+                return Err(SparkError::MapKeyValueDiffSizes.into());
+            }
+
+            positions.clear();
+            // Bound the cost of clearing the table on subsequent rows after a 
large map.
+            positions.shrink_to(count);
+            for (i, value_index) in key_range.zip(value_range) {
+                if keys.is_null(i) {
+                    return Err(SparkError::NullMapKey.into());
+                }
+                let key = keys.value(i);
+                let compared = if self.normalize {
+                    normalize_float(key)
+                } else {
+                    canonicalize_nan(key)
+                };
+                let slot = *positions.entry(bits(compared)).or_insert(len);
+                let prefix_len = len;
+                if slot == len {
+                    let stored = if self.normalize && !input.from_arrays {
+                        compared
+                    } else {
+                        key
+                    };
+                    if i != first_key + len || bits(stored) != bits(key) {
+                        output_keys.get_or_insert_with(|| 
raw_keys[..len].to_vec());
+                    }
+                    if let Some(keys) = &mut output_keys {
+                        keys.push(stored);
+                    }
+                    len += 1;
+                } else if !self.last_win {
+                    return Err(SparkError::DuplicatedMapKey {
+                        key: java_float_string(key),
+                        key_type: T::DATA_TYPE.to_string(),
+                    }
+                    .into());
+                }
+
+                if value_indices.is_some() || (value_index - first_value) as 
usize != slot {
+                    let indices = value_indices.get_or_insert_with(|| {
+                        (first_value..first_value + prefix_len as 
i32).collect::<Vec<_>>()
+                    });
+                    indices.resize(len, value_index);
+                    indices[slot] = value_index;
+                }
+            }
+            // ArrayBasedMapBuilder.from returns the original arrays if all 
keys are unique.
+            // Once LAST_WIN collapses a duplicate, it builds the entire row 
with normalized keys.
+            if input.from_arrays && self.normalize && len - start < count {
+                let out = output_keys.get_or_insert_with(|| 
raw_keys[..len].to_vec());
+                for key in &mut out[start..] {
+                    *key = normalize_float(*key);
+                }
+            }
+        }
+        offsets.push(len as i32);
+        let keys = match output_keys {
+            Some(keys) => PrimitiveArray::<T>::new(keys.into(), None),
+            None => keys.slice(first_key, len),
+        };
+        let values = match value_indices {
+            Some(indices) => take(input.values, &Int32Array::from(indices), 
None)?,
+            None => input.values.slice(first_value as usize, len),
+        };
+        let fields = vec![
+            Field::new("key", keys.data_type().clone(), false),
+            Field::new("value", values.data_type().clone(), true),
+        ];
+        let entries = StructArray::try_new(fields.into(), vec![Arc::new(keys), 
values], None)?;
+        Ok(Arc::new(MapArray::try_new(
+            Arc::new(Field::new("entries", entries.data_type().clone(), 
false)),
+            OffsetBuffer::new(offsets.into()),
+            entries,
+            nulls.finish(),
+            false,
+        )?))
+    }
+}
+
+struct MapInput<'a> {
+    from_arrays: bool,
+    key_rows: &'a ListArray,
+    value_rows: &'a ListArray,
+    keys: &'a ArrayRef,
+    values: &'a ArrayRef,
+    entry_nulls: Option<&'a NullBuffer>,
+}
+
+fn to_list(array: &ArrayRef) -> Result<ListArray> {

Review Comment:
   Comet doesn't produce `LargeList` or `FixedSizeList` inputs for these 
builders, so these branches look unreachable.



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