spark-test commented on code in PR #60531:
URL: https://github.com/apache/spark/pull/60531#discussion_r4620163607


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala:
##########
@@ -3011,9 +3027,11 @@ object CodeGenerator extends Logging {
       case _ => dataType
     }
 
-    if (sqlDataType.isInstanceOf[StructType]) {
-      // `ColumnVector.getStruct` is different from `InternalRow.getStruct`, 
it only takes an
-      // `ordinal` parameter.
+    // ColumnVector.getStruct takes a single arg (rowId), unlike 
InternalRow.getStruct which
+    // takes two args (ordinal, numFields). Resolve framework types so 
struct-backed types
+    // hit the StructType path.
+    val resolved = 
TypeOps(sqlDataType).flatMap(_.rowRepresentationType).getOrElse(sqlDataType)

Review Comment:
   **Nit (P3):** No test calls `getValueFromVector` for a framework type, so 
removing this lookup would leave the suite green. Without it, a struct-backed 
framework column, or a UDT over one, would get `getValue`'s two-argument 
`getStruct(rowId, numFields)`, which `ColumnVector` does not declare, so the 
code generated for columnar-to-row conversion (`Columnar.scala:111`) and for 
the vectorized hash map (`VectorizedHashMapGenerator.scala:110`) would fail to 
compile and fall back. The PR's other row-representation lookups now have tests 
that fail without them; this one was not among the sites the earlier review 
named.
   
   Suggested fix: a string check like the `addBufferedState` test, asserting 
that `CodeGenerator.getValueFromVector` returns the one-argument `getStruct` 
call for the test type and for a UDT over it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60531#discussion_r4582037865).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/InterpretedSafeProjection.scala:
##########
@@ -56,9 +57,21 @@ class InterpretedSafeProjection(expressions: 
Seq[Expression]) extends Projection
     (exprs(i), f)
   }
 
-  private def generateSafeValueConverter(dt: DataType): Any => Any = dt match {
+  // A framework type with a row representation is converted as that 
representation.
+  private def generateSafeValueConverter(dt: DataType): Any => Any =
+    
TypeOps(dt).flatMap(_.rowRepresentationType).map(generateSafeValueConverter)
+      .getOrElse(generateSafeValueConverterDefault(dt))
+
+  // A nested value (an array element, a struct field, a map key or value) may 
be null, which the
+  // array, struct and map converters cannot convert.
+  private def generateNullSafeValueConverter(dt: DataType): Any => Any = {
+    val converter = generateSafeValueConverter(dt)
+    v => if (v == null) null else converter(v)

Review Comment:
   **Nit (P3):** `generateNullSafeValueConverter` wraps every nested converter, 
including the `identity` that `generateSafeValueConverterDefault` returns for 
atomic types (`InterpretedSafeProjection.scala:113`), which also serves TIME 
and UDTs over atomic types. `identity` already returns null for null, and the 
nested reads already pass a null element or field through as null 
(`ArrayData.foreach` and `toArray` read through `InternalRow.getAccessor`'s 
null check, and `row.get` returns null for a null field). So, reading the code, 
an `array<int>` of n elements now costs n extra function calls and null checks 
over the base branch and converts to the same `GenericArrayData`; struct fields 
and map keys and values pay the same. Only the struct, array and map converters 
dereference their input and need the guard. The interpreted safe projection 
runs when `SafeProjection` falls back from a failed compile or the internal 
`spark.sql.codegen.factoryMode` setting selects it, so the cost is small
 , but the null fix does not need it.
   
   Suggested fix: return one shared identity converter from the default arm, 
kept in the companion object because the converters are built while the 
projection is being constructed, and have `generateNullSafeValueConverter` 
return that converter unwrapped while wrapping every other converter as it does 
now.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60531#discussion_r4612082651).
   
   **Verification:**
   - **Behavior:** With the interpreted safe projection, a null struct, array 
or map value nested in an array, a struct and a map is kept as null, a null 
atomic element stays null, and non-null nested values of atomic, struct, array, 
map and struct-backed framework types convert to the same values as before.
   - **Inspection:** The converter the interpreted safe projection builds for a 
nested atomic type is the shared identity converter, not a null-check wrapper 
around it, while the converters for nested struct, array and map types remain 
wrapped.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/vectorized/ColumnarRow.java:
##########
@@ -40,10 +43,18 @@ public final class ColumnarRow extends InternalRow {
   private final int numFields;
 
   public ColumnarRow(ColumnVector data, int rowId) {
-    assert (data.dataType() instanceof StructType);
     this.data = data;
     this.rowId = rowId;
-    this.numFields = ((StructType) data.dataType()).size();
+    DataType dt = data.dataType();
+    if (dt instanceof StructType) {
+      this.numFields = ((StructType) dt).size();
+    } else {
+      // Struct-backed framework types map to PhysicalStructType but are not 
StructType.
+      PhysicalDataType pdt = PhysicalDataType.apply(dt);

Review Comment:
   **Nit (P3):** This branch has no test, and neither has the struct route of 
the generic `get` in `ColumnarRow` and `ColumnarBatchRow`, which reaches it 
through `SpecializedGettersReader` and `ColumnVector.getStruct`: 
`StructBackedFrameworkTypeSuite` reads the test type only from row, array and 
map inputs, and the new `ColumnarBatchSuite` test reads TIME and interval 
values from `StructType` vectors. Reverting the branch to the base branch's 
`StructType` assertion and cast, or taking `numFields` from somewhere else, 
would leave the suite green. Column vectors don't build children for such a 
type yet, so until that work lands a test is the only thing that would catch it.
   
   Suggested fix: add a test-only `ColumnVector` that reports a given type and 
returns given child vectors, modeled on `NoCloseColumnVector` in 
`SparkSessionExtensionSuite`, since a writable vector cannot hold a framework 
type. Use it once with the test type over ordinary vectors for its two fields 
and once as a struct vector whose only field is that vector, so that 
`ColumnarBatchRow.get`, `ColumnVector.getStruct` and `ColumnarRow.get` each 
build and read a `ColumnarRow` over the framework-typed vector.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TypeOps.scala:
##########
@@ -108,13 +134,69 @@ trait TypeOps extends TypeApiOps {
   /**
    * Returns a writer function for setting values in an InternalRow.
    *
+   * Not used by InternalRow.getWriter for a type with a 
[[rowRepresentationType]], which is
+   * written as that representation.
+   *
    * @param ordinal
    *   the column index to write to
    * @return
    *   writer function (InternalRow, Any) => Unit
    */
   def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit
 
+  /**
+   * Returns the number of bytes this type occupies in the fixed-size region 
of an
+   * [[org.apache.spark.sql.catalyst.expressions.UnsafeArrayData 
UnsafeArrayData]].
+   *
+   * Variable-length types (struct, array, map, binary, string) use 8 bytes 
because
+   * the fixed region stores an offset+size pointer into the variable-length 
region.
+   * Fixed-size primitive types use their natural size (1 for byte/boolean, 2 
for short,
+   * 4 for int/float, 8 for long/double).
+   *
+   * Consumed by 
[[org.apache.spark.sql.catalyst.expressions.InterpretedUnsafeProjection]]
+   * when writing arrays or maps that contain framework type elements. Derived 
from
+   * [[getPhysicalType]], matching the slot size that code generation uses.
+   *
+   * @return
+   *   element size in bytes
+   */
+  def getElementSize: Int = getPhysicalType match {
+    case PhysicalBooleanType | PhysicalByteType => 1
+    case PhysicalShortType => 2
+    case PhysicalIntegerType | PhysicalFloatType => 4
+    case _ => 8
+  }
+
+  /**
+   * Returns an equivalent built-in DataType for infrastructure dispatch.
+   *
+   * Framework types backed by complex physical storage (struct, array, map) 
return
+   * the corresponding built-in DataType so that row infrastructure code 
(codegen,
+   * projection, comparison, etc.) can handle them through existing code paths 
via
+   * self-recursion - no per-physical-type matching needed at call sites.
+   *
+   * Primitive-backed types (e.g., TimeType backed by Long) return None because
+   * existing infrastructure default paths already handle primitives correctly.
+   *
+   * This is NOT a type alias - the framework type retains its identity in 
schemas,
+   * expressions, proto serialization, and error messages. This is solely a 
dispatch
+   * hint for row infrastructure internals.
+   *
+   * Derived from [[getPhysicalType]]: PhysicalStructType(fields) is 
StructType(fields), and
+   * PhysicalArrayType and PhysicalMapType are the matching ArrayType and 
MapType. The result is
+   * always a built-in DataType, never another framework type, as some sites 
look the
+   * representation up only once.
+   *
+   * @return Some(DataType) for complex-backed types, None for 
primitive-backed types

Review Comment:
   **Nit (P3):** `case _ => None` also covers physical types that are neither 
primitive nor complex, such as those of the registered nanosecond timestamp 
types, but this `@return` and the paragraph about primitive-backed types 
describe only those two kinds, with the reason that the default paths already 
handle primitives. A type that gets `None` reaches the logical-type sites as 
itself: the nanosecond types work because those sites match them by name (for 
example `setColumnDefault`, `CodeGenerator.scala:2901-2902`), whereas a 
string-backed framework type would, reading the code, get no `clone()` in 
`addBufferedState` (`CodeGenerator.scala:747`) and no `copy()` in 
`setColumnDefault` (`CodeGenerator.scala:2908-2910`), and keep a view into a 
reused buffer. No registered type is affected today.
   
   Suggested fix: have the `@return` give `None` for every physical type other 
than a struct, an array or a map, and have the paragraph say that the 
logical-type sites then see the type itself, so a primitive-backed type such as 
TIME goes through their existing primitive handling and any other type needs 
handling of its own there.
   
   **Verification:**
   - **Inspection:** The rowRepresentationType documentation and its @return 
describe the result for struct, array and map physical types and for every 
other physical type, give a non-primitive example of the latter such as the 
nanosecond timestamp types, and say that the logical-type sites see such a type 
as itself, so that a type that is not primitive-backed needs handling of its 
own there.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala:
##########
@@ -0,0 +1,603 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.types.ops
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, 
CodeGenerator, GenerateMutableProjection, GenerateOrdering, GeneratePredicate, 
GenerateSafeProjection, GenerateUnsafeProjection}
+import 
org.apache.spark.sql.catalyst.expressions.objects.{CatalystToExternalMap, 
MapObjects, UnresolvedCatalystToExternalMap}
+import org.apache.spark.sql.catalyst.types.{PhysicalDataType, 
PhysicalStructType}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Test-only DataType backed by a struct: its physical type is a 
PhysicalStructType and its row
+ * representation is the matching StructType.
+ *
+ * This type has 2 fields: name (String, nullable) and value (Long, non-null).
+ * The internal representation is InternalRow (same as StructType).
+ */
+case class TestStructBackedType() extends TestableFrameworkType {
+  override def defaultSize: Int = 20
+  override def asNullable: TestStructBackedType = this
+  override def typeName: String = "test_struct_backed"
+  override def createTypeOps(): TypeOps = TestStructBackedTypeOps(this)
+}
+
+object TestStructBackedType {
+  val FIELDS: Array[StructField] = Array(
+    StructField("name", StringType, nullable = true),
+    StructField("value", LongType, nullable = false)
+  )
+}
+
+/**
+ * Test-only TypeOps for TestStructBackedType.
+ *
+ * The sites that dispatch on the physical type (SpecializedGettersReader,
+ * InternalRow.getAccessor, InterpretedUnsafeProjection's field writers) 
handle the type through
+ * PhysicalStructType(fields). The sites that dispatch on the logical type 
(the code generation
+ * helpers, InternalRow.getWriter and InterpretedSafeProjection) handle it 
through its row
+ * representation, StructType(fields).
+ */
+case class TestStructBackedTypeOps(override val dataType: TestStructBackedType)
+    extends TypeOps {
+
+  override def getPhysicalType: PhysicalDataType =
+    PhysicalStructType(TestStructBackedType.FIELDS)
+
+  override def getJavaClass: Class[_] = classOf[InternalRow]
+
+  override def getMutableValue: MutableValue = new MutableAny
+
+  override def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit =
+    (row, v) => row.update(ordinal, v)
+
+  override def getDefaultLiteral: Literal =
+    Literal.create(
+      new GenericInternalRow(Array[Any](UTF8String.fromString(""), 0L)),
+      new TestStructBackedType())
+
+  override def getJavaLiteral(v: Any): String = v.toString
+
+  override def toCatalystImpl(scalaValue: Any): Any = scalaValue
+
+  override def toScala(catalystValue: Any): Any = catalystValue
+
+  override def toScalaImpl(row: InternalRow, column: Int): Any =
+    row.getStruct(column, 2)
+
+  // Test type does not exercise client-side ops; stub TypeApiOps members so 
the trait contract
+  // is satisfied without pulling in encoder / SQL-literal infrastructure.
+  override def format(v: Any): String = v.toString
+  override def toSQLValue(v: Any): String = v.toString
+  override def getEncoder: AgnosticEncoder[_] =
+    throw new UnsupportedOperationException("Test type does not provide an 
encoder")
+}
+
+/**
+ * A user-defined type stored as TestStructBackedType, to check that the 
dispatch sites look a
+ * framework type up again after unwrapping a UDT.
+ */
+class TestStructBackedUDT extends UserDefinedType[InternalRow] {
+  override def sqlType: DataType = TestStructBackedType()
+  override def serialize(obj: InternalRow): Any = obj
+  override def deserialize(datum: Any): InternalRow = 
datum.asInstanceOf[InternalRow]
+  override def userClass: Class[InternalRow] = classOf[InternalRow]
+}
+
+/**
+ * Suite for a framework type with a struct-backed physical representation, on 
the interpreted
+ * and the code generation paths.
+ *
+ * The readers and the interpreted unsafe writer reach the type through its 
physical type
+ * (PhysicalStructType). The code generation helpers, InternalRow.getWriter and
+ * InterpretedSafeProjection reach it through its row representation 
(StructType).
+ */
+class StructBackedFrameworkTypeSuite extends SparkFunSuite {
+
+  private val testType = TestStructBackedType()
+
+  private def makeStructRow(name: String, value: Long): GenericInternalRow = {
+    new GenericInternalRow(Array[Any](
+      if (name != null) UTF8String.fromString(name) else null,
+      value
+    ))
+  }
+
+  // ==================== Physical Type Resolution ====================
+
+  test("PhysicalDataType resolves to PhysicalStructType for struct-backed 
framework type") {
+    val physType = PhysicalDataType(testType)
+    assert(physType.isInstanceOf[PhysicalStructType])
+    val st = physType.asInstanceOf[PhysicalStructType]
+    assert(st.fields.length === 2)
+    assert(st.fields(0).dataType === StringType)
+    assert(st.fields(1).dataType === LongType)
+  }
+
+  // ==================== Interpreted Path ====================
+
+  test("interpreted read: SpecializedGettersReader reads struct for framework 
type") {
+    val struct = makeStructRow("hello", 42L)
+    val row: SpecializedGetters = new GenericInternalRow(Array[Any](struct))
+
+    val handleNull = true
+    val handleUserDefinedType = false
+    val result = SpecializedGettersReader.read(row, 0, testType, handleNull, 
handleUserDefinedType)
+    assert(result.isInstanceOf[InternalRow])
+    val resultRow = result.asInstanceOf[InternalRow]
+    assert(resultRow.getUTF8String(0).toString === "hello")
+    assert(resultRow.getLong(1) === 42L)
+  }
+
+  test("interpreted read: SpecializedGettersReader returns null for null 
column") {
+    val row: SpecializedGetters = new GenericInternalRow(Array[Any](null))
+
+    val handleNull = true
+    val handleUserDefinedType = false
+    val result = SpecializedGettersReader.read(row, 0, testType, handleNull, 
handleUserDefinedType)
+    assert(result === null)
+  }
+
+  test("interpreted read: InternalRow.getAccessor dispatches through 
PhysicalStructType") {
+    val struct = makeStructRow("accessor", 7L)
+    val row = new GenericInternalRow(Array[Any](struct))
+
+    val accessor = InternalRow.getAccessor(testType)
+    val result = accessor(row, 0)
+    assert(result.isInstanceOf[InternalRow])
+    val resultRow = result.asInstanceOf[InternalRow]
+    assert(resultRow.getUTF8String(0).toString === "accessor")
+    assert(resultRow.getLong(1) === 7L)
+  }
+
+  test("interpreted write: InterpretedUnsafeProjection round-trips struct") {
+    val struct = makeStructRow("test", 123L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, testType, nullable = true): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.getUTF8String(0).toString === "test")
+    assert(result.getLong(1) === 123L)
+  }
+
+  test("interpreted write: InterpretedUnsafeProjection handles null column") {
+    val inputRow = new GenericInternalRow(Array[Any](null))
+
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, testType, nullable = true): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow)
+
+    assert(unsafeRow.isNullAt(0))
+  }
+
+  // ==================== Codegen Path ====================
+
+  test("codegen write: GenerateUnsafeProjection round-trips struct") {
+    val struct = makeStructRow("codegen", 456L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.getUTF8String(0).toString === "codegen")
+    assert(result.getLong(1) === 456L)
+  }
+
+  test("codegen write: GenerateUnsafeProjection handles null column") {
+    val inputRow = new GenericInternalRow(Array[Any](null))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow)
+
+    assert(unsafeRow.isNullAt(0))
+  }
+
+  test("codegen write: GenerateUnsafeProjection round-trips null struct 
field") {
+    val struct = makeStructRow(null, 789L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.isNullAt(0))
+    assert(result.getLong(1) === 789L)
+  }
+
+  // ==================== Literal Validation ====================
+
+  test("literal validation accepts InternalRow for struct-backed framework 
type") {
+    val struct = makeStructRow("lit", 10L)
+    // Should not throw - PhysicalStructType validation checks InternalRow + 
fields
+    Literal.create(struct, testType)
+  }
+
+  test("literal validation rejects non-InternalRow for struct-backed framework 
type") {
+    intercept[IllegalArgumentException] {
+      Literal.create("not a row", testType)
+    }
+  }
+
+  // ==================== Array Containing Framework Type ====================
+
+  test("interpreted write: array of framework type round-trips") {
+    val elem1 = makeStructRow("a", 1L)
+    val elem2 = makeStructRow("b", 2L)
+    val arrayData = new GenericArrayData(Array[Any](elem1, elem2))
+    val inputRow = new GenericInternalRow(Array[Any](arrayData))
+
+    val arrayType = ArrayType(testType, containsNull = false)
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, arrayType, nullable = false): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultArray = unsafeRow.getArray(0)
+    assert(resultArray.numElements() === 2)
+    val s0 = resultArray.getStruct(0, 2)
+    assert(s0.getUTF8String(0).toString === "a")
+    assert(s0.getLong(1) === 1L)
+    val s1 = resultArray.getStruct(1, 2)
+    assert(s1.getUTF8String(0).toString === "b")
+    assert(s1.getLong(1) === 2L)
+  }
+
+  test("codegen write: array of framework type round-trips") {
+    val elem1 = makeStructRow("x", 10L)
+    val elem2 = makeStructRow("y", 20L)
+    val arrayData = new GenericArrayData(Array[Any](elem1, elem2))
+    val inputRow = new GenericInternalRow(Array[Any](arrayData))
+
+    val arrayType = ArrayType(testType, containsNull = false)
+    val exprs = Seq(BoundReference(0, arrayType, nullable = false))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultArray = unsafeRow.getArray(0)
+    assert(resultArray.numElements() === 2)
+    val s0 = resultArray.getStruct(0, 2)
+    assert(s0.getUTF8String(0).toString === "x")
+    assert(s0.getLong(1) === 10L)
+    val s1 = resultArray.getStruct(1, 2)
+    assert(s1.getUTF8String(0).toString === "y")
+    assert(s1.getLong(1) === 20L)
+  }
+
+  // ==================== Map Containing Framework Type ====================
+
+  test("interpreted write: map with framework type values round-trips") {
+    val key1 = UTF8String.fromString("k1")
+    val key2 = UTF8String.fromString("k2")
+    val val1 = makeStructRow("m1", 100L)
+    val val2 = makeStructRow("m2", 200L)
+    val mapData = new ArrayBasedMapData(
+      new GenericArrayData(Array[Any](key1, key2)),
+      new GenericArrayData(Array[Any](val1, val2)))
+    val inputRow = new GenericInternalRow(Array[Any](mapData))
+
+    val mapType = MapType(StringType, testType, valueContainsNull = false)
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, mapType, nullable = false): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultMap = unsafeRow.getMap(0)
+    assert(resultMap.numElements() === 2)
+    val keys = resultMap.keyArray()
+    val values = resultMap.valueArray()
+    assert(keys.getUTF8String(0).toString === "k1")
+    assert(keys.getUTF8String(1).toString === "k2")
+    val v0 = values.getStruct(0, 2)
+    assert(v0.getUTF8String(0).toString === "m1")
+    assert(v0.getLong(1) === 100L)
+    val v1 = values.getStruct(1, 2)
+    assert(v1.getUTF8String(0).toString === "m2")
+    assert(v1.getLong(1) === 200L)
+  }
+
+  test("codegen write: map with framework type values round-trips") {
+    val key1 = UTF8String.fromString("k1")
+    val key2 = UTF8String.fromString("k2")
+    val val1 = makeStructRow("m1", 100L)
+    val val2 = makeStructRow("m2", 200L)
+    val mapData = new ArrayBasedMapData(
+      new GenericArrayData(Array[Any](key1, key2)),
+      new GenericArrayData(Array[Any](val1, val2)))
+    val inputRow = new GenericInternalRow(Array[Any](mapData))
+
+    val mapType = MapType(StringType, testType, valueContainsNull = false)
+    val exprs = Seq(BoundReference(0, mapType, nullable = false))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultMap = unsafeRow.getMap(0)
+    assert(resultMap.numElements() === 2)
+    val keys = resultMap.keyArray()
+    val values = resultMap.valueArray()
+    assert(keys.getUTF8String(0).toString === "k1")
+    assert(keys.getUTF8String(1).toString === "k2")
+    val v0 = values.getStruct(0, 2)
+    assert(v0.getUTF8String(0).toString === "m1")
+    assert(v0.getLong(1) === 100L)
+    val v1 = values.getStruct(1, 2)
+    assert(v1.getUTF8String(0).toString === "m2")
+    assert(v1.getLong(1) === 200L)
+  }
+
+  // ==================== Safe Projection ====================
+
+  test("codegen: GenerateSafeProjection round-trips framework type") {
+    val struct = makeStructRow("safe", 42L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    // Create an UnsafeRow first via GenerateUnsafeProjection
+    val unsafeExprs = Seq(BoundReference(0, testType, nullable = true))
+    val unsafeProjection = GenerateUnsafeProjection.generate(unsafeExprs)
+    val unsafeRow = unsafeProjection.apply(inputRow)
+
+    // Now convert back to safe via GenerateSafeProjection
+    val safeExprs = Seq(BoundReference(0, testType, nullable = true))
+    val safeProjection = GenerateSafeProjection.generate(safeExprs)
+    val safeRow = safeProjection.apply(unsafeRow)
+
+    // The result should be a safe (non-unsafe) InternalRow with correct values
+    val result = safeRow.getStruct(0, 2)
+    assert(!result.isInstanceOf[UnsafeRow])
+    assert(result.getUTF8String(0).toString === "safe")
+    assert(result.getLong(1) === 42L)
+  }
+
+  test("codegen: GenerateOrdering compares framework type values like 
structs") {
+    val ordering = GenerateOrdering.generate(
+      Seq(SortOrder(BoundReference(0, testType, nullable = true), Ascending)))
+    def row(name: String, value: Long): InternalRow =
+      new GenericInternalRow(Array[Any](makeStructRow(name, value)))
+    assert(ordering.compare(row("a", 1L), row("a", 1L)) === 0)
+    assert(ordering.compare(row("a", 1L), row("b", 1L)) < 0)
+    assert(ordering.compare(row("a", 2L), row("a", 1L)) > 0)
+  }
+
+  test("codegen: GenerateMutableProjection sets framework type values") {
+    val projection = GenerateMutableProjection.generate(
+      Seq(BoundReference(0, testType, nullable = true)))
+    val target = new GenericInternalRow(1)
+    projection.target(target)
+    projection(new GenericInternalRow(Array[Any](makeStructRow("mutable", 
7L))))
+    val result = target.getStruct(0, 2)
+    assert(result.getUTF8String(0).toString === "mutable")
+    assert(result.getLong(1) === 7L)
+  }
+
+  // ==================== Derived Layout ====================
+
+  test("the row representation and the element size are derived from the 
physical type") {
+    assert(TypeOps(testType).get.rowRepresentationType ===
+      Some(StructType(TestStructBackedType.FIELDS)))
+    assert(TypeOps(TimeType(6)).get.rowRepresentationType.isEmpty)
+    val types = Seq(TimeType(6), TimestampNTZNanosType(9), 
TimestampLTZNanosType(9), testType)

Review Comment:
   **Non-blocking (P2):** This list, like the rest of the suite, has no array- 
or map-backed framework type, so the `PhysicalArrayType` and `PhysicalMapType` 
arms of `rowRepresentationType` never run and no test sends such a type through 
a logical-type site, although arrays and maps are two of the three layouts the 
description says now work. Reading the code, if either arm returned `None` or 
dropped `containsNull` or `valueContainsNull`, the suite would stay green, 
while an array-backed type would reach `setColumn` and `addBufferedState` 
without the `copy()` they emit for `ArrayType`, keeping a view into a reused 
buffer, and `writeElement` would emit `writer.write(index, value)` for an 
`ArrayData`, which no `UnsafeWriter` overload accepts. No production type uses 
these layouts yet, so tests are the only signal until one does.
   
   Suggested fix: add array- and map-backed test types whose `containsNull` or 
`valueContainsNull` is a parameter, with different key and value types for the 
map, and assert that their row representations equal the matching `ArrayType` 
and `MapType` for both flag values; the constructors default the flag to true, 
so only a false flag shows one that was dropped. Then run the reused-input safe 
and mutable projection tests and an unsafe projection round trip for each type 
in both modes.
   
   **Verification:**
   - **Regression:** If rowRepresentationType returns None for an array- or 
map-backed physical type, drops or inverts containsNull or valueContainsNull, 
or swaps a map's key and value types, a test fails.
   - **Behavior:** Values of an array-backed and of a map-backed framework type 
keep their contents after the reused unsafe input buffer is overwritten, 
through the safe and mutable projections on the interpreted and the generated 
path, and round-trip through the unsafe projection on both paths.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala:
##########
@@ -0,0 +1,603 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.types.ops
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, 
CodeGenerator, GenerateMutableProjection, GenerateOrdering, GeneratePredicate, 
GenerateSafeProjection, GenerateUnsafeProjection}
+import 
org.apache.spark.sql.catalyst.expressions.objects.{CatalystToExternalMap, 
MapObjects, UnresolvedCatalystToExternalMap}
+import org.apache.spark.sql.catalyst.types.{PhysicalDataType, 
PhysicalStructType}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Test-only DataType backed by a struct: its physical type is a 
PhysicalStructType and its row
+ * representation is the matching StructType.
+ *
+ * This type has 2 fields: name (String, nullable) and value (Long, non-null).
+ * The internal representation is InternalRow (same as StructType).
+ */
+case class TestStructBackedType() extends TestableFrameworkType {
+  override def defaultSize: Int = 20
+  override def asNullable: TestStructBackedType = this
+  override def typeName: String = "test_struct_backed"
+  override def createTypeOps(): TypeOps = TestStructBackedTypeOps(this)
+}
+
+object TestStructBackedType {
+  val FIELDS: Array[StructField] = Array(
+    StructField("name", StringType, nullable = true),
+    StructField("value", LongType, nullable = false)
+  )
+}
+
+/**
+ * Test-only TypeOps for TestStructBackedType.
+ *
+ * The sites that dispatch on the physical type (SpecializedGettersReader,
+ * InternalRow.getAccessor, InterpretedUnsafeProjection's field writers) 
handle the type through
+ * PhysicalStructType(fields). The sites that dispatch on the logical type 
(the code generation
+ * helpers, InternalRow.getWriter and InterpretedSafeProjection) handle it 
through its row
+ * representation, StructType(fields).
+ */
+case class TestStructBackedTypeOps(override val dataType: TestStructBackedType)
+    extends TypeOps {
+
+  override def getPhysicalType: PhysicalDataType =
+    PhysicalStructType(TestStructBackedType.FIELDS)
+
+  override def getJavaClass: Class[_] = classOf[InternalRow]
+
+  override def getMutableValue: MutableValue = new MutableAny
+
+  override def getRowWriter(ordinal: Int): (InternalRow, Any) => Unit =
+    (row, v) => row.update(ordinal, v)
+
+  override def getDefaultLiteral: Literal =
+    Literal.create(
+      new GenericInternalRow(Array[Any](UTF8String.fromString(""), 0L)),
+      new TestStructBackedType())
+
+  override def getJavaLiteral(v: Any): String = v.toString
+
+  override def toCatalystImpl(scalaValue: Any): Any = scalaValue
+
+  override def toScala(catalystValue: Any): Any = catalystValue
+
+  override def toScalaImpl(row: InternalRow, column: Int): Any =
+    row.getStruct(column, 2)
+
+  // Test type does not exercise client-side ops; stub TypeApiOps members so 
the trait contract
+  // is satisfied without pulling in encoder / SQL-literal infrastructure.
+  override def format(v: Any): String = v.toString
+  override def toSQLValue(v: Any): String = v.toString
+  override def getEncoder: AgnosticEncoder[_] =
+    throw new UnsupportedOperationException("Test type does not provide an 
encoder")
+}
+
+/**
+ * A user-defined type stored as TestStructBackedType, to check that the 
dispatch sites look a
+ * framework type up again after unwrapping a UDT.
+ */
+class TestStructBackedUDT extends UserDefinedType[InternalRow] {
+  override def sqlType: DataType = TestStructBackedType()
+  override def serialize(obj: InternalRow): Any = obj
+  override def deserialize(datum: Any): InternalRow = 
datum.asInstanceOf[InternalRow]
+  override def userClass: Class[InternalRow] = classOf[InternalRow]
+}
+
+/**
+ * Suite for a framework type with a struct-backed physical representation, on 
the interpreted
+ * and the code generation paths.
+ *
+ * The readers and the interpreted unsafe writer reach the type through its 
physical type
+ * (PhysicalStructType). The code generation helpers, InternalRow.getWriter and
+ * InterpretedSafeProjection reach it through its row representation 
(StructType).
+ */
+class StructBackedFrameworkTypeSuite extends SparkFunSuite {
+
+  private val testType = TestStructBackedType()
+
+  private def makeStructRow(name: String, value: Long): GenericInternalRow = {
+    new GenericInternalRow(Array[Any](
+      if (name != null) UTF8String.fromString(name) else null,
+      value
+    ))
+  }
+
+  // ==================== Physical Type Resolution ====================
+
+  test("PhysicalDataType resolves to PhysicalStructType for struct-backed 
framework type") {
+    val physType = PhysicalDataType(testType)
+    assert(physType.isInstanceOf[PhysicalStructType])
+    val st = physType.asInstanceOf[PhysicalStructType]
+    assert(st.fields.length === 2)
+    assert(st.fields(0).dataType === StringType)
+    assert(st.fields(1).dataType === LongType)
+  }
+
+  // ==================== Interpreted Path ====================
+
+  test("interpreted read: SpecializedGettersReader reads struct for framework 
type") {
+    val struct = makeStructRow("hello", 42L)
+    val row: SpecializedGetters = new GenericInternalRow(Array[Any](struct))
+
+    val handleNull = true
+    val handleUserDefinedType = false
+    val result = SpecializedGettersReader.read(row, 0, testType, handleNull, 
handleUserDefinedType)
+    assert(result.isInstanceOf[InternalRow])
+    val resultRow = result.asInstanceOf[InternalRow]
+    assert(resultRow.getUTF8String(0).toString === "hello")
+    assert(resultRow.getLong(1) === 42L)
+  }
+
+  test("interpreted read: SpecializedGettersReader returns null for null 
column") {
+    val row: SpecializedGetters = new GenericInternalRow(Array[Any](null))
+
+    val handleNull = true
+    val handleUserDefinedType = false
+    val result = SpecializedGettersReader.read(row, 0, testType, handleNull, 
handleUserDefinedType)
+    assert(result === null)
+  }
+
+  test("interpreted read: InternalRow.getAccessor dispatches through 
PhysicalStructType") {
+    val struct = makeStructRow("accessor", 7L)
+    val row = new GenericInternalRow(Array[Any](struct))
+
+    val accessor = InternalRow.getAccessor(testType)
+    val result = accessor(row, 0)
+    assert(result.isInstanceOf[InternalRow])
+    val resultRow = result.asInstanceOf[InternalRow]
+    assert(resultRow.getUTF8String(0).toString === "accessor")
+    assert(resultRow.getLong(1) === 7L)
+  }
+
+  test("interpreted write: InterpretedUnsafeProjection round-trips struct") {
+    val struct = makeStructRow("test", 123L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, testType, nullable = true): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.getUTF8String(0).toString === "test")
+    assert(result.getLong(1) === 123L)
+  }
+
+  test("interpreted write: InterpretedUnsafeProjection handles null column") {
+    val inputRow = new GenericInternalRow(Array[Any](null))
+
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, testType, nullable = true): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow)
+
+    assert(unsafeRow.isNullAt(0))
+  }
+
+  // ==================== Codegen Path ====================
+
+  test("codegen write: GenerateUnsafeProjection round-trips struct") {
+    val struct = makeStructRow("codegen", 456L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.getUTF8String(0).toString === "codegen")
+    assert(result.getLong(1) === 456L)
+  }
+
+  test("codegen write: GenerateUnsafeProjection handles null column") {
+    val inputRow = new GenericInternalRow(Array[Any](null))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow)
+
+    assert(unsafeRow.isNullAt(0))
+  }
+
+  test("codegen write: GenerateUnsafeProjection round-trips null struct 
field") {
+    val struct = makeStructRow(null, 789L)
+    val inputRow = new GenericInternalRow(Array[Any](struct))
+
+    val exprs = Seq(BoundReference(0, testType, nullable = true))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val result = unsafeRow.getStruct(0, 2)
+    assert(result.isNullAt(0))
+    assert(result.getLong(1) === 789L)
+  }
+
+  // ==================== Literal Validation ====================
+
+  test("literal validation accepts InternalRow for struct-backed framework 
type") {
+    val struct = makeStructRow("lit", 10L)
+    // Should not throw - PhysicalStructType validation checks InternalRow + 
fields
+    Literal.create(struct, testType)
+  }
+
+  test("literal validation rejects non-InternalRow for struct-backed framework 
type") {
+    intercept[IllegalArgumentException] {
+      Literal.create("not a row", testType)
+    }
+  }
+
+  // ==================== Array Containing Framework Type ====================
+
+  test("interpreted write: array of framework type round-trips") {
+    val elem1 = makeStructRow("a", 1L)
+    val elem2 = makeStructRow("b", 2L)
+    val arrayData = new GenericArrayData(Array[Any](elem1, elem2))
+    val inputRow = new GenericInternalRow(Array[Any](arrayData))
+
+    val arrayType = ArrayType(testType, containsNull = false)
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, arrayType, nullable = false): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultArray = unsafeRow.getArray(0)
+    assert(resultArray.numElements() === 2)
+    val s0 = resultArray.getStruct(0, 2)
+    assert(s0.getUTF8String(0).toString === "a")
+    assert(s0.getLong(1) === 1L)
+    val s1 = resultArray.getStruct(1, 2)
+    assert(s1.getUTF8String(0).toString === "b")
+    assert(s1.getLong(1) === 2L)
+  }
+
+  test("codegen write: array of framework type round-trips") {
+    val elem1 = makeStructRow("x", 10L)
+    val elem2 = makeStructRow("y", 20L)
+    val arrayData = new GenericArrayData(Array[Any](elem1, elem2))
+    val inputRow = new GenericInternalRow(Array[Any](arrayData))
+
+    val arrayType = ArrayType(testType, containsNull = false)
+    val exprs = Seq(BoundReference(0, arrayType, nullable = false))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultArray = unsafeRow.getArray(0)
+    assert(resultArray.numElements() === 2)
+    val s0 = resultArray.getStruct(0, 2)
+    assert(s0.getUTF8String(0).toString === "x")
+    assert(s0.getLong(1) === 10L)
+    val s1 = resultArray.getStruct(1, 2)
+    assert(s1.getUTF8String(0).toString === "y")
+    assert(s1.getLong(1) === 20L)
+  }
+
+  // ==================== Map Containing Framework Type ====================
+
+  test("interpreted write: map with framework type values round-trips") {
+    val key1 = UTF8String.fromString("k1")
+    val key2 = UTF8String.fromString("k2")
+    val val1 = makeStructRow("m1", 100L)
+    val val2 = makeStructRow("m2", 200L)
+    val mapData = new ArrayBasedMapData(
+      new GenericArrayData(Array[Any](key1, key2)),
+      new GenericArrayData(Array[Any](val1, val2)))
+    val inputRow = new GenericInternalRow(Array[Any](mapData))
+
+    val mapType = MapType(StringType, testType, valueContainsNull = false)
+    val exprs: Array[Expression] = Array(
+      BoundReference(0, mapType, nullable = false): Expression)
+    val projection = new InterpretedUnsafeProjection(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultMap = unsafeRow.getMap(0)
+    assert(resultMap.numElements() === 2)
+    val keys = resultMap.keyArray()
+    val values = resultMap.valueArray()
+    assert(keys.getUTF8String(0).toString === "k1")
+    assert(keys.getUTF8String(1).toString === "k2")
+    val v0 = values.getStruct(0, 2)
+    assert(v0.getUTF8String(0).toString === "m1")
+    assert(v0.getLong(1) === 100L)
+    val v1 = values.getStruct(1, 2)
+    assert(v1.getUTF8String(0).toString === "m2")
+    assert(v1.getLong(1) === 200L)
+  }
+
+  test("codegen write: map with framework type values round-trips") {
+    val key1 = UTF8String.fromString("k1")
+    val key2 = UTF8String.fromString("k2")
+    val val1 = makeStructRow("m1", 100L)
+    val val2 = makeStructRow("m2", 200L)
+    val mapData = new ArrayBasedMapData(
+      new GenericArrayData(Array[Any](key1, key2)),
+      new GenericArrayData(Array[Any](val1, val2)))
+    val inputRow = new GenericInternalRow(Array[Any](mapData))
+
+    val mapType = MapType(StringType, testType, valueContainsNull = false)
+    val exprs = Seq(BoundReference(0, mapType, nullable = false))
+    val projection = GenerateUnsafeProjection.generate(exprs)
+    val unsafeRow = projection.apply(inputRow).copy()
+
+    val resultMap = unsafeRow.getMap(0)
+    assert(resultMap.numElements() === 2)
+    val keys = resultMap.keyArray()
+    val values = resultMap.valueArray()
+    assert(keys.getUTF8String(0).toString === "k1")
+    assert(keys.getUTF8String(1).toString === "k2")
+    val v0 = values.getStruct(0, 2)
+    assert(v0.getUTF8String(0).toString === "m1")
+    assert(v0.getLong(1) === 100L)
+    val v1 = values.getStruct(1, 2)
+    assert(v1.getUTF8String(0).toString === "m2")
+    assert(v1.getLong(1) === 200L)
+  }
+
+  // ==================== Safe Projection ====================

Review Comment:
   **Nit (P3):** Besides the `GenerateSafeProjection` test, this section holds 
"codegen: GenerateOrdering compares framework type values like structs" and 
"codegen: GenerateMutableProjection sets framework type values", neither of 
which is a safe projection test. Likewise the "Reused UnsafeRow Input" section 
(line 422) holds the column and array unsafe round trips (lines 475 and 486) 
and the nested-null safe projection test (line 540), none of which uses 
`withReusedUnsafeInput` or a reused buffer. The repository's guidance asks a 
long class to group its members into sections whose headers describe them; as 
it stands, these tests are hard to find and the next test is likely to land in 
the wrong section.
   
   Suggested fix: move the ordering and mutable-projection tests under "Other 
Code Generation Helpers", and move the round-trip and nested-null tests into 
their own loop under a header that names them, with no change to any test body.
   
   **Verification:**
   - **Inspection:** Each section header in the struct-backed framework type 
suite names the kind of test under it, and every test registered before the 
move is still registered afterwards with the same name and assertions.



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