You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by co...@apache.org on 2026/09/08 21:32:19 UTC
(datafusion-comet) branch main updated: feat: address remaining issues for `CreateArray` (#5766)
This is an automated email from the ASF dual-hosted git repository.
comphead pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
The following commit(s) were added to refs/heads/main by this push:
new 0d1348f353 feat: address remaining issues for `CreateArray` (#5766)
0d1348f353 is described below
commit 0d1348f353ac54897bc523fe3a9c5b5b14afc1a3
Author: Oleks V <co...@users.noreply.github.com>
AuthorDate: Tue Sep 8 14:32:14 2026 -0700
feat: address remaining issues for `CreateArray` (#5766)
---
.github/workflows/pr_build_linux.yml | 1 +
.github/workflows/pr_build_macos.yml | 1 +
.../comet/codegen/CometBatchKernelCodegen.scala | 12 +-
.../main/scala/org/apache/comet/serde/arrays.scala | 124 +++++++------
.../scala/org/apache/comet/serde/literals.scala | 203 +++++++++++++++------
.../org/apache/comet/shims/CometTypeShim.scala | 23 +++
.../org/apache/comet/shims/CometTypeShim.scala | 3 +
.../sql-tests/expressions/array/array_append.sql | 7 +
.../expressions/array/element_at_ansi.sql | 41 +++++
.../sql-tests/expressions/array/slice.sql | 18 ++
.../sql-tests/expressions/map/create_map.sql | 11 ++
.../apache/comet/CometArrayExpressionSuite.scala | 126 ++++++++++++-
.../org/apache/comet/serde/CometLiteralSuite.scala | 126 +++++++++++++
13 files changed, 578 insertions(+), 118 deletions(-)
diff --git a/.github/workflows/pr_build_linux.yml b/.github/workflows/pr_build_linux.yml
index 79fea7fb88..a911893467 100644
--- a/.github/workflows/pr_build_linux.yml
+++ b/.github/workflows/pr_build_linux.yml
@@ -476,6 +476,7 @@ jobs:
org.apache.comet.CometWidthBucketSuite
org.apache.comet.CometUuidExpressionSuite
org.apache.comet.serde.CometScalarFunctionSuite
+ org.apache.comet.serde.CometLiteralSuite
org.apache.comet.CometFallbackInvarianceSuite
fail-fast: false
name: ${{ matrix.profile.name }} [${{ matrix.suite.name }}]
diff --git a/.github/workflows/pr_build_macos.yml b/.github/workflows/pr_build_macos.yml
index 5473d3988a..334e4592ea 100644
--- a/.github/workflows/pr_build_macos.yml
+++ b/.github/workflows/pr_build_macos.yml
@@ -249,6 +249,7 @@ jobs:
org.apache.comet.CometWidthBucketSuite
org.apache.comet.CometUuidExpressionSuite
org.apache.comet.serde.CometScalarFunctionSuite
+ org.apache.comet.serde.CometLiteralSuite
org.apache.comet.CometFallbackInvarianceSuite
fail-fast: false
diff --git a/spark/src/main/scala/org/apache/comet/codegen/CometBatchKernelCodegen.scala b/spark/src/main/scala/org/apache/comet/codegen/CometBatchKernelCodegen.scala
index 3e2456234e..83fbca6b63 100644
--- a/spark/src/main/scala/org/apache/comet/codegen/CometBatchKernelCodegen.scala
+++ b/spark/src/main/scala/org/apache/comet/codegen/CometBatchKernelCodegen.scala
@@ -81,6 +81,12 @@ object CometBatchKernelCodegen extends Logging with CometExprTraitShim with Come
/**
* Type surface the kernel covers on both input and output sides. Recursive: complex types are
* supported when their children are.
+ *
+ * Duplicate struct field names are excluded, an output-side rule: Arrow addresses a
+ * `StructVector`'s children by name, so `named_struct('x', 10, 'x', 20)` collapses into a
+ * single child and the generated writer NPEs on the missing ordinal-1 vector.
+ * `CometCreateNamedStruct` declines them on the native path for the same reason, but a struct
+ * nested inside a dispatcher-built value (a `CreateMap` value) never reaches that check.
*/
def isSupportedDataType(dt: DataType): Boolean = dt match {
case BooleanType | ByteType | ShortType | IntegerType | LongType => true
@@ -91,7 +97,11 @@ object CometBatchKernelCodegen extends Logging with CometExprTraitShim with Come
case dt if isTimeType(dt) => true
case _: YearMonthIntervalType | _: DayTimeIntervalType | CalendarIntervalType => true
case ArrayType(inner, _) => isSupportedDataType(inner)
- case st: StructType => st.fields.forall(f => isSupportedDataType(f.dataType))
+ case st: StructType =>
+ // `fieldNames` rebuilds an array on each call, so read it once.
+ val names = st.fieldNames
+ names.distinct.length == names.length &&
+ st.fields.forall(f => isSupportedDataType(f.dataType))
case mt: MapType => isSupportedDataType(mt.keyType) && isSupportedDataType(mt.valueType)
case _ => false
}
diff --git a/spark/src/main/scala/org/apache/comet/serde/arrays.scala b/spark/src/main/scala/org/apache/comet/serde/arrays.scala
index 27a742ce58..32f8d08e10 100644
--- a/spark/src/main/scala/org/apache/comet/serde/arrays.scala
+++ b/spark/src/main/scala/org/apache/comet/serde/arrays.scala
@@ -51,17 +51,17 @@ object CometArrayRemove
}
}
-object CometArrayAppend extends CometExpressionSerde[ArrayAppend] {
+object CometArrayAppend extends CometExpressionSerde[ArrayAppend] with ArraysBase {
override def convert(
expr: ArrayAppend,
inputs: Seq[Attribute],
binding: Boolean): Option[ExprOuterClass.Expr] = {
- val child = expr.children.head
- val elementType = child.dataType.asInstanceOf[ArrayType].elementType
+ val (srcChild, itemChild) = widenElementInLockstep(expr.children.head, expr.children(1))
+ val elementType = srcChild.dataType.asInstanceOf[ArrayType].elementType
- val arrayExprProto = exprToProto(expr.children.head, inputs, binding)
- val keyExprProto = exprToProto(expr.children(1), inputs, binding)
+ val arrayExprProto = exprToProto(srcChild, inputs, binding)
+ val keyExprProto = exprToProto(itemChild, inputs, binding)
// DataFusion's array_append always returns a list with nullable elements,
// so we must promise ArrayType(elementType, containsNull = true) here even if
@@ -74,6 +74,8 @@ object CometArrayAppend extends CometExpressionSerde[ArrayAppend] {
arrayExprProto,
keyExprProto)
+ // IS NOT NULL does not care about element nullability, so use the un-widened source and skip
+ // serializing a redundant cast.
val isNotNullExpr = createUnaryExpr(
expr,
expr.children.head,
@@ -444,28 +446,7 @@ object CometArrayInsert extends CometExpressionSerde[ArrayInsert] with ArraysBas
expr: ArrayInsert,
inputs: Seq[Attribute],
binding: Boolean): Option[ExprOuterClass.Expr] = {
- val srcArray = expr.children.head
- val item = expr.children(2)
- val srcElementType = srcArray.dataType.asInstanceOf[ArrayType].elementType
-
- // Native ArrayInsert requires the item's Arrow type to equal the source array's element type
- // exactly, including nested nullability. For complex element types the two sides can disagree:
- // a `CreateArray` source is widened to a deeply-nullable element type (see CometCreateArray),
- // while a standalone item (e.g. `map(2, coalesce(id, 0))`) keeps Spark's Catalyst nullability.
- // Cast BOTH sides in lockstep to the same deeply-nullable element type so their Arrow types
- // match; Spark's `ArrayInsert.dataType` is `first.dataType.asNullable`, so this also
- // matches the declared output element type. Casting only widens metadata and never
- // changes values. Primitive element types are byte-identical on both sides, so the gate
- // leaves them untouched.
- val (srcChild, itemChild) = if (isComplexType(srcElementType)) {
- val elementType = deepNullable(srcElementType)
- val arrayType = ArrayType(elementType, containsNull = true)
- val widenedSrc = if (srcArray.dataType == arrayType) srcArray else Cast(srcArray, arrayType)
- val widenedItem = if (item.dataType == elementType) item else Cast(item, elementType)
- (widenedSrc, widenedItem)
- } else {
- (srcArray, item)
- }
+ val (srcChild, itemChild) = widenElementInLockstep(expr.children.head, expr.children(2))
val srcExprProto = exprToProtoInternal(srcChild, inputs, binding)
val posExprProto = exprToProtoInternal(expr.children(1), inputs, binding)
@@ -497,22 +478,18 @@ object CometSlice extends CometExpressionSerde[Slice] {
expr: Slice,
inputs: Seq[Attribute],
binding: Boolean): Option[ExprOuterClass.Expr] = {
- val elementType = expr.x.dataType.asInstanceOf[ArrayType].elementType
val arrayExprProto = exprToProto(expr.x, inputs, binding)
val startExprProto = exprToProto(Cast(expr.start, LongType), inputs, binding)
val lengthExprProto = exprToProto(Cast(expr.length, LongType), inputs, binding)
- // DataFusion list types always have nullable inner elements, so promise
- // ArrayType(elementType, containsNull = true) here even if Spark's
- // expr.dataType reports containsNull = false (e.g. for array(1, 2, 3)).
- val sliceScalarExpr =
- scalarFunctionExprToProtoWithReturnType(
- "spark_array_slice",
- ArrayType(elementType, containsNull = true),
- false,
- arrayExprProto,
- startExprProto,
- lengthExprProto)
- sliceScalarExpr
+ // No serialized return type: native `spark_array_slice` reuses its input's list field for the
+ // output, so only `return_field_from_args` is guaranteed to match. Spark's `expr.dataType` is
+ // not: `CometCreateArray` may have widened the input to a deeply-nullable element type, and
+ // DataFusion list elements are nullable where Spark's `containsNull` says otherwise.
+ scalarFunctionExprToProto(
+ "spark_array_slice",
+ arrayExprProto,
+ startExprProto,
+ lengthExprProto)
}
}
@@ -638,11 +615,34 @@ object CometArrayReverse extends CometExpressionSerde[Reverse] with ArraysBase {
object CometElementAt extends CometExpressionSerde[ElementAt] {
+ /**
+ * Under ANSI, neither native shape reproduces Spark for a nullable nondeterministic operand.
+ * Spark's `ElementAt` is a `BinaryExpression`: for a NULL map/array it returns NULL without
+ * evaluating the key/index child at all. A native lookup evaluates every argument over the
+ * whole batch first, so a throwing index fires on rows whose operand is NULL. `convert`
+ * reproduces the short-circuit with a `CASE WHEN <operand> IS NOT NULL` guard, but that guard
+ * serializes the operand twice, which a stateful operand cannot survive: the two copies advance
+ * its state independently and silently move values and NULLs. Declining leaves the lookup on
+ * Spark. Lifting this needs a native lookup that evaluates the operand once and masks the index
+ * evaluation with the result, at which point the guard becomes unnecessary for every operand.
+ */
+ private val eagerIndexReason: String =
+ "ANSI mode with a nullable nondeterministic array or map operand: a native lookup evaluates " +
+ "the index over the whole batch, where Spark skips it on the rows whose operand is NULL"
+
+ /** True when `convert` has to wrap the lookup to reproduce Spark's NULL short-circuit. */
+ private def needsNullGuard(expr: ElementAt): Boolean =
+ expr.failOnError && expr.left.nullable
+
override def getSupportLevel(expr: ElementAt): SupportLevel = {
- expr.left.dataType match {
- case _: ArrayType => Compatible()
- case MapType(keyType, _, _) => MapKeySupport.keySupport(keyType)
- case _ => Unsupported(Some("Input must be an array or map"))
+ if (needsNullGuard(expr) && !expr.left.deterministic) {
+ Unsupported(Some(eagerIndexReason))
+ } else {
+ expr.left.dataType match {
+ case _: ArrayType => Compatible()
+ case MapType(keyType, _, _) => MapKeySupport.keySupport(keyType)
+ case _ => Unsupported(Some("Input must be an array or map"))
+ }
}
}
@@ -682,15 +682,12 @@ object CometElementAt extends CometExpressionSerde[ElementAt] {
}
}
- // Spark's ElementAt is a BinaryExpression: for a NULL map/array it returns NULL WITHOUT
- // evaluating the key/index child. Native scalar functions evaluate the key eagerly over the
- // whole batch, so under ANSI (failOnError) a throwing key (e.g. a divide-by-zero) fires even on
- // rows whose map/array is NULL, where Spark short-circuits. When the left can actually be NULL,
- // guard the lookup with CASE WHEN left IS NOT NULL THEN <lookup> ELSE null so the key is only
- // evaluated on the selected rows (DataFusion's CaseExpr filters the batch before the THEN
- // branch), reproducing the short-circuit. Mirrors the CASE-WHEN idiom in CometArrayAppend /
- // CometSize; the ELSE null literal carries the result type, as in CometArraysZip.
- if (expr.failOnError && expr.left.nullable) {
+ // Evaluate the key only on the rows the guard selects (DataFusion's CaseExpr filters the batch
+ // before the THEN branch), reproducing Spark's short-circuit. See `eagerIndexReason` for why
+ // this shape is restricted to deterministic operands. Mirrors the CASE-WHEN idiom in
+ // CometArrayAppend / CometSize; the ELSE null literal carries the result type, as in
+ // CometArraysZip.
+ if (needsNullGuard(expr)) {
val isNotNullExpr = createUnaryExpr(
expr,
expr.left,
@@ -940,6 +937,27 @@ trait ArraysBase {
.collectFirst { case dt if !isTypeSupported(dt) => dt }
.map(dt => Unsupported(Some(s"data type not supported: $dt")))
.getOrElse(Compatible())
+
+ /**
+ * Cast `srcArray` and `item` to one deeply-nullable element type, for the native kernels that
+ * require the two Arrow types to be equal (`array_append`, `array_insert`). A `CreateArray`
+ * source is already deeply-nullable (see `CometCreateArray`) while a standalone item keeps
+ * Spark's Catalyst nullability, so for a complex element type the two disagree. Casting only
+ * widens metadata, and lands on both expressions' declared `asNullable` output element type.
+ * Primitive element types already agree, so the gate leaves them untouched.
+ */
+ def widenElementInLockstep(srcArray: Expression, item: Expression): (Expression, Expression) = {
+ val srcType = srcArray.dataType.asInstanceOf[ArrayType]
+ if (isComplexType(srcType.elementType)) {
+ val elementType = deepNullable(srcType.elementType)
+ val arrayType = ArrayType(elementType, containsNull = true)
+ val widenedSrc = if (srcType == arrayType) srcArray else Cast(srcArray, arrayType)
+ val widenedItem = if (item.dataType == elementType) item else Cast(item, elementType)
+ (widenedSrc, widenedItem)
+ } else {
+ (srcArray, item)
+ }
+ }
}
object CometArrayTransform extends CometCodegenDispatch[ArrayTransform]
diff --git a/spark/src/main/scala/org/apache/comet/serde/literals.scala b/spark/src/main/scala/org/apache/comet/serde/literals.scala
index a951ae2857..b368f80320 100644
--- a/spark/src/main/scala/org/apache/comet/serde/literals.scala
+++ b/spark/src/main/scala/org/apache/comet/serde/literals.scala
@@ -22,46 +22,44 @@ package org.apache.comet.serde.literals
import java.lang
import org.apache.spark.internal.Logging
-import org.apache.spark.sql.catalyst.expressions.{Attribute, CreateArray, CreateMap, Expression, KnownNullable, Literal}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Cast, CreateArray, CreateMap, Expression, KnownNullable, Literal, MapFromArrays}
import org.apache.spark.sql.catalyst.util.{ArrayData, MapData, TypeUtils}
import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType, ByteType, CalendarIntervalType, DataType, DateType, DayTimeIntervalType, Decimal, DecimalType, DoubleType, FloatType, IntegerType, LongType, MapType, NullType, ShortType, StringType, StructType, TimestampNTZType, TimestampType}
-import org.apache.spark.unsafe.types.UTF8String
+import org.apache.spark.unsafe.types.{CalendarInterval, UTF8String}
import com.google.protobuf.ByteString
import org.apache.comet.CometSparkSessionExtensions.withFallbackReason
-import org.apache.comet.DataTypeSupport.isComplexType
import org.apache.comet.serde.{CometExpressionSerde, Compatible, ExprOuterClass, LiteralOuterClass, MapKeySupport, SupportLevel, Unsupported}
-import org.apache.comet.serde.QueryPlanSerde.{exprToProtoInternal, isTimeType, serializeDataType, supportedDataType}
+import org.apache.comet.serde.QueryPlanSerde.{exprToProtoInternal, serializeDataType, supportedDataType}
import org.apache.comet.serde.Types.ListLiteral
+import org.apache.comet.shims.CometTypeShim
-object CometLiteral extends CometExpressionSerde[Literal] with Logging {
+object CometLiteral extends CometExpressionSerde[Literal] with CometTypeShim with Logging {
override def getUnsupportedReasons(): Seq[String] = Seq(
"Not all data types are supported for literal values")
override def getSupportLevel(expr: Literal): SupportLevel = {
+ val serializable = expr.dataType match {
+ // A null literal carries only its type on the wire, so any type serializeDataType handles.
+ case _ if expr.value == null => supportedDataType(expr.dataType, allowComplex = true)
+ case ArrayType(elementType, _) => listLiteralElementSupported(elementType)
+ case dt => supportedDataType(dt)
+ }
- if (supportedDataType(
- expr.dataType,
- allowComplex = expr.value == null ||
-
- // Nested literal support for native reader
- // can be tracked https://github.com/apache/datafusion-comet/issues/1937
- (expr.dataType
- .isInstanceOf[ArrayType] && (!isComplexType(
- expr.dataType.asInstanceOf[ArrayType].elementType) || expr.dataType
- .asInstanceOf[ArrayType]
- .elementType
- .isInstanceOf[ArrayType])))) {
- Compatible(None)
- } else if (canExpandComplexLiteral(expr)) {
- // Rebuilt as a `CreateArray` / `CreateMap` tree in `convert`.
+ // A shape `canExpandComplexLiteral` admits is rebuilt as a `CreateArray` / `CreateMap` tree.
+ if ((serializable && !hasUnwritableValue(expr.value, expr.dataType)) ||
+ canExpandComplexLiteral(expr)) {
Compatible(None)
+ } else if (serializable) {
+ // The type is fine, so this is a value `convert` could only serialize by changing it.
+ Unsupported(Some(s"Unsupported literal value for data type ${expr.dataType}"))
} else {
expr.dataType match {
case _: DayTimeIntervalType => Compatible(None)
- case _ => Unsupported(Some(s"Unsupported data type ${expr.dataType}"))
+ case dt => Unsupported(Some(s"Unsupported data type $dt"))
}
}
}
@@ -136,8 +134,12 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
}
- private def makeListLiteral(array: Array[Any], arrayType: ArrayType): ListLiteral.Builder = {
+ /** Package-private only so `CometLiteralSuite` can pin it against the gate below. */
+ private[serde] def makeListLiteral(
+ array: Array[Any],
+ arrayType: ArrayType): ListLiteral.Builder = {
val listLiteralBuilder = ListLiteral.newBuilder()
+ // Keep these arms in sync with [[listLiteralElementSupported]].
arrayType.elementType match {
case NullType =>
array.foreach(_ => listLiteralBuilder.addNullMask(true))
@@ -226,6 +228,22 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
listLiteralBuilder
}
+ /**
+ * Element types [[makeListLiteral]] has a branch for. Anything else has to be expanded or
+ * declined before `convert` reaches it, or the missing branch raises a `MatchError` mid-plan.
+ * `StringType` is matched as a stable identifier, so a non-default collation (whose `equals`
+ * compares `collationId`) is declined here rather than falling into the missing branch.
+ * `CometLiteralSuite` pins the two together.
+ */
+ private[serde] def listLiteralElementSupported(dataType: DataType): Boolean = dataType match {
+ case NullType | BooleanType | ByteType | ShortType | IntegerType | DateType | LongType |
+ TimestampType | TimestampNTZType | FloatType | DoubleType | StringType | BinaryType =>
+ true
+ case _: DecimalType => true
+ case ArrayType(elementType, _) => listLiteralElementSupported(elementType)
+ case _ => false
+ }
+
/**
* Rebuild a folded complex Literal as an equivalent tree of `CreateArray` / `CreateMap` over
* primitive-typed Literals, or `None` when [[canExpandComplexLiteral]] rejects the shape.
@@ -247,9 +265,7 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
* every native map consumer gates on [[MapKeySupport]]; see [[mapKeyTypesExpandable]] for why.
*
* Declined shapes:
- * - Null values and empty top-level containers: a synthesized `Create*` with no children
- * cannot recover the original element type. Empty `ArrayType` literals still serialize via
- * `makeListLiteral`, which keeps the type.
+ * - Null values, which `convert` serializes as a typed `is_null` literal instead.
* - Any map key type native map kernels cannot reproduce Spark equality for (floating-point,
* collated string, complex), or whose interpreted ordering is undefined
* (`CalendarIntervalType`), at any nesting level. See [[mapKeyTypesExpandable]].
@@ -261,49 +277,125 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
* `CometCreateMap` hands the whole rebuilt `CreateMap` to the JVM codegen dispatcher, so
* Spark's own code builds the struct.
* - Folded maps with duplicate keys, see [[hasDuplicateMapKeys]].
+ * - Values no Arrow encoding of the rebuilt tree can carry, see [[hasUnwritableValue]].
*/
private def expandComplexLiteral(expr: Literal): Option[Expression] = {
if (!canExpandComplexLiteral(expr)) return None
expr.dataType match {
case ArrayType(et, containsNull) =>
val arr = expr.value.asInstanceOf[ArrayData]
- val elements = (0 until arr.numElements())
- .map(i => withNullability(literalAt(arr, i, et), containsNull))
- Some(CreateArray(elements, useStringTypeWhenEmpty = false))
+ if (arr.numElements() == 0) {
+ Some(emptyTypedArray(et, containsNull))
+ } else {
+ val elements = (0 until arr.numElements())
+ .map(i => withNullability(literalAt(arr, i, et), containsNull))
+ Some(CreateArray(elements, useStringTypeWhenEmpty = false))
+ }
case MapType(kt, vt, valueContainsNull) =>
val mapData = expr.value.asInstanceOf[MapData]
- val keys = mapData.keyArray()
- val values = mapData.valueArray()
- val children = (0 until keys.numElements()).flatMap(i =>
- Seq(
- literalAt(keys, i, kt),
- withNullability(literalAt(values, i, vt), valueContainsNull)))
- Some(CreateMap(children, useStringTypeWhenEmpty = false))
+ if (mapData.numElements() == 0) {
+ // `MapFromArrays` recovers the declared key/value types from its two array children;
+ // a childless `CreateMap` would report `MapType(NullType, NullType)`. Arrow map keys
+ // are never null, so the key array is non-nullable.
+ Some(
+ MapFromArrays(
+ emptyTypedArray(kt, containsNull = false),
+ emptyTypedArray(vt, valueContainsNull)))
+ } else {
+ val keys = mapData.keyArray()
+ val values = mapData.valueArray()
+ val children = (0 until keys.numElements()).flatMap(i =>
+ Seq(
+ literalAt(keys, i, kt),
+ withNullability(literalAt(values, i, vt), valueContainsNull)))
+ Some(CreateMap(children, useStringTypeWhenEmpty = false))
+ }
case _ => None
}
}
/**
- * Cheap admission test that mirrors [[expandComplexLiteral]] without materializing the rebuilt
- * `Create*` tree, so `getSupportLevel` can probe a large folded literal without allocating the
- * N `Literal`s `convert` would immediately rebuild. Declines a null value or empty top-level
- * container (no children to recover the element type), a folded map with duplicate keys (see
- * [[hasDuplicateMapKeys]]), any unsupported or non-orderable map key type at any nesting level
- * (see [[mapKeyTypesExpandable]]), and an array of structs ([[needsExpansion]] stops at a
- * `StructType`). [[expandComplexLiteral]] gates on this, so the two cannot diverge.
+ * An empty `ArrayType(elementType, containsNull)` value. `CometCreateArray` turns a childless
+ * `CreateArray` into an empty `ArrayType(NullType)` list literal (its documented workaround for
+ * DataFusion's zero-argument `make_array`), and the cast stamps the declared element type back
+ * onto it.
+ */
+ private def emptyTypedArray(elementType: DataType, containsNull: Boolean): Expression =
+ Cast(CreateArray(Nil, useStringTypeWhenEmpty = false), ArrayType(elementType, containsNull))
+
+ /**
+ * Admission test for [[expandComplexLiteral]], which gates on this so the two cannot diverge.
+ * Split out so `getSupportLevel` can decide without allocating the N `Literal`s `convert` would
+ * immediately rebuild. See [[expandComplexLiteral]] for the shapes this declines.
*/
private def canExpandComplexLiteral(expr: Literal): Boolean = {
if (expr.value == null || !mapKeyTypesExpandable(expr.dataType)) return false
- expr.dataType match {
- case ArrayType(et, _) if needsExpansion(et) =>
- expr.value.asInstanceOf[ArrayData].numElements() > 0
+ val expandableShape = expr.dataType match {
+ case ArrayType(et, _) => needsExpansion(et)
case MapType(kt, _, _) =>
- val mapData = expr.value.asInstanceOf[MapData]
- mapData.numElements() > 0 && !hasDuplicateMapKeys(mapData.keyArray(), kt)
+ !hasDuplicateMapKeys(expr.value.asInstanceOf[MapData].keyArray(), kt)
case _ => false
}
+ // Last, because it is the only check here that walks the whole folded value.
+ expandableShape && !hasUnwritableValue(expr.value, expr.dataType)
+ }
+
+ /**
+ * True when some scalar inside `value` has no faithful Arrow encoding, in which case the
+ * literal has to stay on Spark. Two of the copies a Literal takes towards the native side are
+ * not total:
+ * - a `UTF8String` holding malformed UTF-8 (`CAST(X'FF' AS STRING)`). A rebuilt `CreateMap`
+ * reaches the JVM codegen dispatcher, whose generated writer copies the bytes verbatim into
+ * a `VarCharVector`; native string kernels then read them through unchecked Arrow FFI and
+ * abort the JVM on a `hint::unreachable_unchecked`, or silently mis-count characters. The
+ * direct paths (`convert`'s `StringType` arm and [[makeListLiteral]]'s) instead go through
+ * `UTF8String.toString`, which substitutes U+FFFD. Neither is fixable on the wire, because
+ * `string_val` and `string_values` are proto `string` fields.
+ * - a `CalendarInterval` beyond about 292 years of elapsed time overflows
+ * `Math.multiplyExact(microseconds, 1000L)` on the way into `IntervalMonthDayNanoVector`,
+ * whose nanosecond field cannot represent it (#5279). Spark itself accepts the value.
+ *
+ * The same hazards exist for a non-folded `map(...)` / a scanned string column, which never
+ * reach this serde; this only keeps a Literal from newly admitting them.
+ */
+ private def hasUnwritableValue(value: Any, dataType: DataType): Boolean =
+ mayHoldUnwritableValue(dataType) && unwritableValueIn(value, dataType)
+
+ /**
+ * Type-level precondition for [[hasUnwritableValue]]: only a string or a calendar interval
+ * reaches one of its hazardous arms, so a large all-numeric literal is never walked element by
+ * element. Applied once per collection rather than once per element.
+ */
+ private def mayHoldUnwritableValue(dataType: DataType): Boolean =
+ SupportLevel.containsType(dataType, classOf[StringType], classOf[CalendarIntervalType])
+
+ private def unwritableValueIn(value: Any, dataType: DataType): Boolean = dataType match {
+ case _ if value == null => false
+ case _: StringType => !isValidUtf8(value.asInstanceOf[UTF8String])
+ case CalendarIntervalType =>
+ val micros = value.asInstanceOf[CalendarInterval].microseconds
+ micros > MaxArrowIntervalMicros || micros < -MaxArrowIntervalMicros
+ case ArrayType(et, _) => unwritableElementIn(value.asInstanceOf[ArrayData], et)
+ case MapType(kt, vt, _) =>
+ val mapData = value.asInstanceOf[MapData]
+ (mayHoldUnwritableValue(kt) && unwritableElementIn(mapData.keyArray(), kt)) ||
+ (mayHoldUnwritableValue(vt) && unwritableElementIn(mapData.valueArray(), vt))
+ case StructType(fields) =>
+ val row = value.asInstanceOf[InternalRow]
+ fields.indices.exists { i =>
+ val fieldType = fields(i).dataType
+ mayHoldUnwritableValue(fieldType) && unwritableValueIn(row.get(i, fieldType), fieldType)
+ }
+ case _ => false
}
+ private def unwritableElementIn(arr: ArrayData, elementType: DataType): Boolean =
+ (0 until arr.numElements()).exists(i =>
+ unwritableValueIn(arr.get(i, elementType), elementType))
+
+ /** Largest `CalendarInterval.microseconds` that survives conversion to Arrow nanoseconds. */
+ private final val MaxArrowIntervalMicros: Long = Long.MaxValue / 1000
+
/**
* True when every map key type reachable inside `dataType` can be rebuilt and consumed
* natively. A folded map is rebuilt as a `CreateMap`; once native it may reach a map consumer
@@ -365,16 +457,13 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
* instead of asking the ordering to compare it.
*/
private def hasDuplicateMapKeys(keys: ArrayData, keyType: DataType): Boolean = {
- val n = keys.numElements()
- if (n < 2) {
- false
- } else if ((0 until n).exists(keys.isNullAt)) {
- true
- } else {
- val ordering = TypeUtils.getInterpretedOrdering(keyType)
- val sorted = (0 until n).map(i => keys.get(i, keyType)).sorted(ordering)
- (1 until sorted.length).exists(i => ordering.compare(sorted(i - 1), sorted(i)) == 0)
- }
+ if (keys.numElements() < 2) return false
+ // Single pass out of the ArrayData; a null slot comes back as null.
+ val sorted = keys.toObjectArray(keyType)
+ if (sorted.contains(null)) return true
+ val ordering = TypeUtils.getInterpretedOrdering(keyType)
+ java.util.Arrays.sort(sorted, ordering.asInstanceOf[Ordering[Object]])
+ (1 until sorted.length).exists(i => ordering.compare(sorted(i - 1), sorted(i)) == 0)
}
/**
diff --git a/spark/src/main/spark-3.x/org/apache/comet/shims/CometTypeShim.scala b/spark/src/main/spark-3.x/org/apache/comet/shims/CometTypeShim.scala
index 3fd97509fc..7280fdc9dc 100644
--- a/spark/src/main/spark-3.x/org/apache/comet/shims/CometTypeShim.scala
+++ b/spark/src/main/spark-3.x/org/apache/comet/shims/CometTypeShim.scala
@@ -19,9 +19,13 @@
package org.apache.comet.shims
+import java.nio.ByteBuffer
+import java.nio.charset.{CharacterCodingException, CodingErrorAction, StandardCharsets}
+
import scala.annotation.nowarn
import org.apache.spark.sql.types.{DataType, StructType}
+import org.apache.spark.unsafe.types.UTF8String
trait CometTypeShim {
@nowarn // Spark 4 feature; stubbed to false in Spark 3.x for compatibility.
@@ -47,4 +51,23 @@ trait CometTypeShim {
@nowarn // Spark 4.1 feature; TimeType doesn't exist in Spark 3.x.
def isTimeType(dt: DataType): Boolean = false
+
+ /**
+ * `UTF8String.isValid` (which memoizes on the instance) only exists from Spark 4.0, so decode
+ * here instead. Rejects the same sequences as Rust's `str::from_utf8`: overlong forms,
+ * surrogates, and code points past U+10FFFF. Unlike `Charset.decode`, a `CharsetDecoder` set to
+ * REPORT raises rather than silently substituting U+FFFD.
+ */
+ def isValidUtf8(s: UTF8String): Boolean = {
+ val decoder = StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ try {
+ decoder.decode(ByteBuffer.wrap(s.getBytes))
+ true
+ } catch {
+ case _: CharacterCodingException => false
+ }
+ }
}
diff --git a/spark/src/main/spark-4.x/org/apache/comet/shims/CometTypeShim.scala b/spark/src/main/spark-4.x/org/apache/comet/shims/CometTypeShim.scala
index 0fcdf2255d..1270eebfe0 100644
--- a/spark/src/main/spark-4.x/org/apache/comet/shims/CometTypeShim.scala
+++ b/spark/src/main/spark-4.x/org/apache/comet/shims/CometTypeShim.scala
@@ -21,6 +21,7 @@ package org.apache.comet.shims
import org.apache.spark.sql.execution.datasources.VariantMetadata
import org.apache.spark.sql.types.{ArrayType, DataType, MapType, StringType, StructType, VariantType}
+import org.apache.spark.unsafe.types.UTF8String
trait CometTypeShim {
// A `StringType` carries collation metadata in Spark 4.0. Only non-default (non-UTF8_BINARY)
@@ -74,5 +75,7 @@ trait CometTypeShim {
def isTimeType(dt: DataType): Boolean =
dt.getClass.getSimpleName.startsWith("TimeType")
+ def isValidUtf8(s: UTF8String): Boolean = s.isValid
+
def hasCollationSupport: Boolean = true
}
diff --git a/spark/src/test/resources/sql-tests/expressions/array/array_append.sql b/spark/src/test/resources/sql-tests/expressions/array/array_append.sql
index 4453ab663e..b88c7c15c6 100644
--- a/spark/src/test/resources/sql-tests/expressions/array/array_append.sql
+++ b/spark/src/test/resources/sql-tests/expressions/array/array_append.sql
@@ -39,3 +39,10 @@ SELECT array_append(array(1, 2, 3), val) FROM test_array_append
-- literal + literal
query
SELECT array_append(array(1, 2, 3), 4), array_append(array(), 1), array_append(cast(NULL as array<int>), 1)
+
+-- Arrays of maps. `CometCreateArray` widens every child to a deeply-nullable element type while
+-- the appended item keeps Spark's own, so the kernel's declared result type and its two operand
+-- types all have to agree with what the batch carries.
+query
+SELECT array_append(array(map(1, 2), map(3, 4)), map(5, 6)),
+ array_append(array(map(1, array(2))), map(3, array(4)))
diff --git a/spark/src/test/resources/sql-tests/expressions/array/element_at_ansi.sql b/spark/src/test/resources/sql-tests/expressions/array/element_at_ansi.sql
index 0a3f418907..30ab1bba58 100644
--- a/spark/src/test/resources/sql-tests/expressions/array/element_at_ansi.sql
+++ b/spark/src/test/resources/sql-tests/expressions/array/element_at_ansi.sql
@@ -72,3 +72,44 @@ SELECT element_at(arr, -10) FROM ansi_element_at_oob
-- literal with negative out of bounds
query ignore(https://github.com/apache/datafusion-comet/issues/3375)
SELECT element_at(array(1, 2, 3), -5)
+
+-- ============================================================================
+-- ANSI short-circuit over a NULL array
+-- ============================================================================
+
+statement
+CREATE TABLE ansi_element_at_null(id int) USING parquet
+
+statement
+INSERT INTO ansi_element_at_null VALUES (1), (2), (3)
+
+-- Spark's ElementAt is a BinaryExpression that returns NULL for a NULL array WITHOUT evaluating the
+-- index, so the ANSI remainder-by-zero at id = 2 must not fire. CometElementAt reproduces that with
+-- a `CASE WHEN <array> IS NOT NULL` guard, which runs the index only on the selected rows, so this
+-- executes natively and returns 1, NULL, 1. The map counterpart lives in
+-- map/element_at_map_ansi.sql.
+query
+SELECT id, element_at(IF(id <> 2, array(1), CAST(NULL AS ARRAY<INT>)), 1 + (id % (id - 2))) AS v
+FROM ansi_element_at_null
+
+-- Same guard over a `CASE WHEN` operand with no ELSE, which reaches the serde with an implicit NULL
+-- branch. The index is a plain literal on purpose: with a throwing index, plain Spark 3.5 and 4.0
+-- raise DIVIDE_BY_ZERO from this spelling on the very row whose array is NULL, contradicting their
+-- own `BinaryExpression.eval` and Spark 4.1, so no single expected result covers every supported
+-- version. The throwing-index case is covered by the `IF(...)` spelling above. Returns 1, NULL, 1.
+query
+SELECT id, element_at(CASE WHEN id <> 2 THEN array(1) END, 1) AS v
+FROM ansi_element_at_null
+
+-- A nondeterministic operand is declined outright. Neither native shape reproduces Spark: the
+-- `CASE WHEN <array> IS NOT NULL` guard serializes the operand twice, so a stateful operand's two
+-- copies drift, and the unguarded lookup evaluates the index over the whole batch, raising
+-- DIVIDE_BY_ZERO at id = 2 on the very row whose array is NULL. `rand(7L) < 2` is always true, so
+-- both operands are NULL on every row and Spark returns NULL without evaluating either index.
+-- The non-ANSI spelling stays native and is covered in element_at.sql.
+-- https://github.com/apache/datafusion-comet/issues/5544
+query expect_fallback(nullable nondeterministic array or map operand)
+SELECT id,
+ element_at(IF(monotonically_increasing_id() % 2 = 0, CAST(NULL AS ARRAY<INT>), array(1)), 1) AS v1,
+ element_at(IF(rand(7L) < 2, CAST(NULL AS ARRAY<INT>), array(1)), 1 + (id % (id - 2))) AS v2
+FROM ansi_element_at_null
diff --git a/spark/src/test/resources/sql-tests/expressions/array/slice.sql b/spark/src/test/resources/sql-tests/expressions/array/slice.sql
index fcb2bb254b..03a4bec048 100644
--- a/spark/src/test/resources/sql-tests/expressions/array/slice.sql
+++ b/spark/src/test/resources/sql-tests/expressions/array/slice.sql
@@ -259,3 +259,21 @@ INSERT INTO test_slice_nested_str VALUES
query
SELECT slice(arr, -2, 2) FROM test_slice_nested_str
+
+-- Arrays of maps and structs. `CometCreateArray` widens every child to a deeply-nullable element
+-- type, so the declared result type must come from the native input field, not `Slice.dataType`.
+query
+SELECT slice(array(map(1, 2), map(3, 4), map(5, 6)), 2, 2),
+ slice(array(map('x', 1), map('y', 2)), -1, 1),
+ slice(array(map(1, array(2)), map(3, array(4))), 1, 1),
+ slice(array(named_struct('a', 1, 'b', 'x'), named_struct('a', 2, 'b', 'y')), 2, 1)
+
+-- Column-based array of maps.
+statement
+CREATE TABLE test_slice_map(k int, v int) USING parquet
+
+statement
+INSERT INTO test_slice_map VALUES (1, 10), (2, NULL), (3, 30)
+
+query
+SELECT slice(array(map(k, v), map(k + 1, v)), 1, 1) FROM test_slice_map
diff --git a/spark/src/test/resources/sql-tests/expressions/map/create_map.sql b/spark/src/test/resources/sql-tests/expressions/map/create_map.sql
index 2dcfad3f6f..8e47941245 100644
--- a/spark/src/test/resources/sql-tests/expressions/map/create_map.sql
+++ b/spark/src/test/resources/sql-tests/expressions/map/create_map.sql
@@ -28,3 +28,14 @@ SELECT map(k, v) FROM test_create_map
query
SELECT map(1, 'a', 2, 'b'), map('x', array(1, 2), 'y', array(3))
+
+-- Arrow addresses a struct vector's children by name, so the two `x` fields collapse into one
+-- child and the dispatcher's generated writer NPEs on the missing ordinal-1 vector. Spark keeps
+-- both values. A struct that is only a map value never reaches `CometCreateNamedStruct`'s check.
+-- https://github.com/apache/datafusion-comet/issues/5544
+query expect_fallback(codegen dispatch: unsupported output type)
+SELECT map(1, named_struct('x', 10, 'x', 20))
+
+-- Distinct field names are unaffected.
+query
+SELECT map(1, named_struct('x', 10, 'y', 20))
diff --git a/spark/src/test/scala/org/apache/comet/CometArrayExpressionSuite.scala b/spark/src/test/scala/org/apache/comet/CometArrayExpressionSuite.scala
index 247de1bb1e..5f769dab9c 100644
--- a/spark/src/test/scala/org/apache/comet/CometArrayExpressionSuite.scala
+++ b/spark/src/test/scala/org/apache/comet/CometArrayExpressionSuite.scala
@@ -1280,19 +1280,131 @@ class CometArrayExpressionSuite extends CometTestBase with AdaptiveSparkPlanHelp
}
}
- // An empty container has no children to recover the element type from, and a NULL literal
- // serializes as a typed null without expansion, so only the empty cases fall back.
+ // An empty container has no children to recover its element type from, so expansion rebuilds it
+ // from a childless `CreateArray` cast to the declared type (and `map_from_arrays` over two such
+ // arrays for a map). A NULL literal serializes as a typed null without expansion.
test("folded empty and NULL complex literals") {
withParquetTable((0 until 3).map(i => (i, i.toLong)), "tbl") {
+ checkSparkAnswerAndOperator("SELECT _1 AS id, CAST(map() AS MAP<INT,INT>) AS m FROM tbl")
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, CAST(array() AS ARRAY<MAP<INT,INT>>) AS a FROM tbl")
+ checkSparkAnswerAndOperator("SELECT _1 AS id, CAST(NULL AS MAP<INT,INT>) AS m FROM tbl")
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, CAST(NULL AS ARRAY<MAP<INT,INT>>) AS a FROM tbl")
+ // A complex value type has to survive the rebuild too: `typedLit(Map.empty[Int, List[Int]])`
+ // is already a Literal, and `map_extract` only type-checks if the rebuilt empty map keeps
+ // `MapType(IntegerType, ArrayType(IntegerType, false), true)`.
+ val emptyMapping = typedLit(Map.empty[Int, List[Int]])
+ checkSparkAnswerAndOperator(spark.table("tbl").select(emptyMapping(col("_1")).as("v")))
+ }
+ }
+
+ // https://github.com/apache/datafusion-comet/issues/5544: Arrow's IntervalMonthDayNano holds
+ // elapsed time in nanoseconds, so the dispatcher's `Math.multiplyExact(microseconds, 1000L)`
+ // overflows past about 292 years, where Spark accepts the value (#5279). Expansion has to
+ // decline the value, not just the type: the calendar-interval restriction in
+ // `mapKeyTypesExpandable` only covers map keys. The `array(map(...))` spelling also covers the
+ // outer `ArrayType` recursion of the value walk.
+ test("folded map value with an out-of-range calendar interval falls back (multirow)") {
+ withParquetTable((0 until 3).map(i => (i, i.toLong)), "tbl") {
+ Seq(
+ "array(map(1, make_interval(0, 0, 0, 0, 3000000, 0, 0)))" -> "ArrayType",
+ "map(1, make_interval(0, 0, 0, 0, 3000000, 0, 0))" -> "MapType",
+ "map(1, make_interval(0, 0, 0, 0, -3000000, 0, 0))" -> "MapType").foreach {
+ case (value, declaredType) =>
+ checkSparkAnswerAndFallbackReason(
+ s"SELECT _1 AS id, $value AS v FROM tbl",
+ s"Unsupported data type $declaredType")
+ }
+ // An interval inside the nanosecond range still runs natively.
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, array(map(1, make_interval(0, 0, 0, 0, 24, 0, 0))) AS a FROM tbl")
+ }
+ }
+
+ // https://github.com/apache/datafusion-comet/issues/5544: the dispatcher copies a UTF8String's
+ // raw bytes into a VarCharVector and the native bridge imports them through unchecked Arrow FFI,
+ // so malformed UTF-8 aborts the JVM on `hint::unreachable_unchecked` (X'FF') or silently
+ // mis-counts characters (the overlong X'C080'). Spark preserves the raw bytes, so normalizing
+ // them would not be equivalent either; expansion declines and Spark evaluates the projection.
+ test("folded map value with malformed UTF-8 falls back (multirow)") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
+ withParquetTable((1 until 4).map(i => (i, i.toLong)), "tbl") {
+ Seq(
+ "length(element_at(map(1, CAST(X'FF' AS STRING)), _1))" -> "MapType",
+ // Exercises the struct arm of the value walk.
+ "element_at(map(1, named_struct('s', CAST(X'FF' AS STRING))), _1)" -> "MapType")
+ .foreach { case (value, declaredType) =>
+ checkSparkAnswerAndFallbackReason(
+ s"SELECT _1 AS id, $value AS v FROM tbl",
+ s"Unsupported data type $declaredType")
+ }
+ // Well-formed multi-byte text is unaffected.
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, length(element_at(map(1, CAST(X'C3A9' AS STRING)), _1)) AS v FROM tbl")
+ }
+ }
+ }
+
+ // https://github.com/apache/datafusion-comet/issues/5544: the two paths that serialize a
+ // string literal directly, `convert`'s scalar `StringType` arm and `makeListLiteral`'s, both
+ // go through `UTF8String.toString`, which substitutes U+FFFD for malformed input where Spark
+ // keeps the raw bytes. Declining is the only option, because `string_val` and `string_values`
+ // are proto `string` fields that cannot carry those bytes at all. Comparing the answers calls
+ // the two sides equal, since both render as the replacement character, so the failing cases
+ // go through `hex`. Every expression here keeps a column child to stay out of ConstantFolding,
+ // which would otherwise fold the projection into one literal the encoder never sees.
+ test("string literal holding malformed UTF-8 falls back (multirow)") {
+ withParquetTable((1 until 4).map(i => (i, i.toLong)), "tbl") {
+ // The list-literal encoder: `array(...)` is all-literal, so it folds.
checkSparkAnswerAndFallbackReason(
- "SELECT _1 AS id, CAST(map() AS MAP<INT,INT>) AS m FROM tbl",
- "Unsupported data type MapType")
+ "SELECT _1 AS id, hex(element_at(array(CAST(X'FF' AS STRING), 'b', 'c'), _1)) AS v " +
+ "FROM tbl",
+ "Unsupported literal value for data type ArrayType")
+ // The scalar arm, which has nothing to do with complex literals. The overlong form of
+ // U+0000 is the same hazard: Spark accepts it, Rust's `str::from_utf8` does not.
+ Seq("X'FF'", "X'C080'").foreach { bytes =>
+ checkSparkAnswerAndFallbackReason(
+ s"SELECT _1 AS id, hex(concat(CAST($bytes AS STRING), CAST(_1 AS STRING))) AS v " +
+ "FROM tbl",
+ "Unsupported literal value for data type StringType")
+ }
+ // Well-formed multi-byte text still serializes, on both paths.
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, length(concat(CAST(X'C3A9' AS STRING), CAST(_1 AS STRING))) AS v " +
+ "FROM tbl")
+ checkSparkAnswerAndOperator(
+ "SELECT _1 AS id, length(element_at(array(CAST(X'C3A9' AS STRING), 'b', 'c'), _1)) " +
+ "AS v FROM tbl")
+ }
+ }
+
+ // `CometLiteralSuite` pins the element-type gate against `makeListLiteral`'s arms exhaustively.
+ // This is the end-to-end half: an element type with no arm produces a fallback rather than the
+ // `MatchError` it used to raise mid-planning.
+ test("folded array literal whose element type the list encoder cannot carry falls back") {
+ withParquetTable((0 until 3).map(i => (i, i.toLong)), "tbl") {
checkSparkAnswerAndFallbackReason(
- "SELECT _1 AS id, CAST(array() AS ARRAY<MAP<INT,INT>>) AS a FROM tbl",
+ "SELECT _1 AS id, array(make_interval(1)) AS a FROM tbl",
"Unsupported data type ArrayType")
- checkSparkAnswerAndOperator("SELECT _1 AS id, CAST(NULL AS MAP<INT,INT>) AS m FROM tbl")
+ }
+ }
+
+ // https://github.com/apache/datafusion-comet/issues/5544: Arrow addresses a `StructVector`'s
+ // children by name, so the two `x` fields collapse into one child and the dispatcher's
+ // generated writer NPEs on the missing ordinal. `CometCreateNamedStruct` declines duplicates
+ // on the native path, but a struct that is only a map value is handed to the dispatcher whole
+ // and never reaches that check. The SQL fixture covers the unfolded spelling, and the harness
+ // excludes `ConstantFolding`, so the folded spelling the issue reports only runs here.
+ test("folded map value with duplicate struct field names falls back (multirow)") {
+ withParquetTable((0 until 3).map(i => (i, i.toLong)), "tbl") {
+ checkSparkAnswerAndFallbackReason(
+ "SELECT _1 AS id, map(1, named_struct('x', 10, 'x', 20)) AS v FROM tbl",
+ "Unsupported data type MapType")
+ // Names differing only in case are distinct children in Arrow, so the exact-name check
+ // leaves these on the native path.
checkSparkAnswerAndOperator(
- "SELECT _1 AS id, CAST(NULL AS ARRAY<MAP<INT,INT>>) AS a FROM tbl")
+ "SELECT _1 AS id, map(1, named_struct('x', 10, 'X', 20)) AS v FROM tbl")
}
}
diff --git a/spark/src/test/scala/org/apache/comet/serde/CometLiteralSuite.scala b/spark/src/test/scala/org/apache/comet/serde/CometLiteralSuite.scala
new file mode 100644
index 0000000000..746cc8e4b8
--- /dev/null
+++ b/spark/src/test/scala/org/apache/comet/serde/CometLiteralSuite.scala
@@ -0,0 +1,126 @@
+/*
+ * 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.comet.serde
+
+import scala.util.Try
+
+import org.apache.arrow.vector.types.TimeUnit
+import org.apache.arrow.vector.types.pojo.{ArrowType, Field, FieldType}
+import org.apache.spark.sql.CometTestBase
+import org.apache.spark.sql.catalyst.util.GenericArrayData
+import org.apache.spark.sql.comet.util.Utils
+import org.apache.spark.sql.types._
+
+import org.apache.comet.CometSparkSessionExtensions.{isSpark40Plus, isSpark41Plus}
+import org.apache.comet.serde.literals.CometLiteral
+import org.apache.comet.shims.CometTypeShim
+
+/**
+ * Pins `CometLiteral.listLiteralElementSupported` against the arms of
+ * `CometLiteral.makeListLiteral`. The gate exists only to keep an element type the encoder has no
+ * arm for from reaching it, so a disagreement between the two is not a fallback: the missing arm
+ * raises a `MatchError` in the middle of planning, which Spark surfaces as `[INTERNAL_ERROR] The
+ * Spark SQL phase planning failed with an internal error`.
+ */
+class CometLiteralSuite extends CometTestBase with CometTypeShim {
+
+ /**
+ * Element types the two sides are compared over. Both halves of the list matter. A type the
+ * encoder handles today that drops out of the gate silently costs a native projection; a type
+ * the gate admits that the encoder has no arm for is the planning failure above. Add an entry
+ * whenever `makeListLiteral` gains an arm, or when a new Spark release adds a type that a
+ * folded array literal can carry.
+ */
+ private val probeElementTypes: Seq[DataType] = Seq(
+ NullType,
+ BooleanType,
+ ByteType,
+ ShortType,
+ IntegerType,
+ LongType,
+ FloatType,
+ DoubleType,
+ DateType,
+ TimestampType,
+ TimestampNTZType,
+ StringType,
+ BinaryType,
+ DecimalType(10, 2),
+ CalendarIntervalType,
+ DayTimeIntervalType(),
+ YearMonthIntervalType(),
+ StructType(Seq(StructField("a", IntegerType))),
+ MapType(IntegerType, IntegerType)) ++ variantType.toSeq ++ probeTimeType.toSeq
+
+ /**
+ * Spark `DataType` for Arrow `Time(NANOSECOND, 64)`, resolved without a 4.1 compile dep, the
+ * way `CometSpecializedGettersDispatchSuite` does it. `convert` has an `isTimeType` arm while
+ * `makeListLiteral` has none, so this is exactly the asymmetry the pin exists to catch.
+ */
+ private def probeTimeType: Option[DataType] =
+ if (!isSpark41Plus) None
+ else
+ Some(
+ Utils.fromArrowField(
+ new Field(
+ "t",
+ FieldType.nullable(new ArrowType.Time(TimeUnit.NANOSECOND, 64)),
+ java.util.Collections.emptyList[Field]())))
+
+ /**
+ * Whether `makeListLiteral` has an arm for `arrayType`'s element type. The probe arrays are
+ * empty, so every arm's per-element conversion is skipped and the only thing under test is
+ * whether the match falls through to a `MatchError`.
+ */
+ private def encoderAcceptsElement(array: Array[Any], arrayType: ArrayType): Boolean =
+ Try(CometLiteral.makeListLiteral(array, arrayType)).isSuccess
+
+ test("listLiteralElementSupported mirrors makeListLiteral's arms, flat and nested") {
+ probeElementTypes.foreach { dt =>
+ withClue(s"element type $dt: ") {
+ assert(
+ CometLiteral.listLiteralElementSupported(dt) ===
+ encoderAcceptsElement(Array.empty, ArrayType(dt)))
+ }
+ // `makeListLiteral` recurses per element rather than on the type, so an empty outer array
+ // would never reach the inner type. One empty inner array forces the recursion.
+ withClue(s"element type ARRAY<$dt>: ") {
+ assert(
+ CometLiteral.listLiteralElementSupported(ArrayType(dt)) ===
+ encoderAcceptsElement(
+ Array[Any](new GenericArrayData(Array.empty[Any])),
+ ArrayType(ArrayType(dt))))
+ }
+ }
+ }
+
+ // `makeListLiteral` matches `StringType` as a stable identifier, whose `equals` compares
+ // `collationId`, so a collated string has no arm and the gate has to decline it. Loosening
+ // either side alone to `_: StringType` would reintroduce the planning failure (gate) or encode
+ // the value under the wrong collation (encoder). Built through SQL because `StringType(id)` does
+ // not compile against Spark 3.x.
+ test("a non-default collation is declined on both sides") {
+ assume(isSpark40Plus, "COLLATE requires Spark 4.0")
+ val collated = spark.sql("SELECT 'a' COLLATE UTF8_LCASE").schema.head.dataType
+ assert(collated !== StringType)
+ assert(!CometLiteral.listLiteralElementSupported(collated))
+ assert(!encoderAcceptsElement(Array.empty, ArrayType(collated)))
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org