spark-test commented on code in PR #60531:
URL: https://github.com/apache/spark/pull/60531#discussion_r4582037849
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TypeOps.scala:
##########
@@ -246,6 +301,21 @@ object TypeOps {
case t: TimestampNTZNanosType => Some(TimestampNTZNanosTypeOps(t))
case t: TimestampLTZNanosType => Some(TimestampLTZNanosTypeOps(t))
// Add new types here - single registration point
+ case ft: TestableFrameworkType => Some(ft.createTypeOps())
Review Comment:
**Non-blocking (P2):** This arm tests a trait, so every type that misses the
three case-class arms above, such as `StructType` or `IntegerType`, now fails
an interface `instanceof` on each call. `PhysicalDataType.apply` calls
`TypeOps.apply` every time, and `SpecializedGettersReader.read` calls
`PhysicalDataType.apply` once per value; that reader backs `UnsafeRow.get`,
`UnsafeArrayData.get` and `ColumnarArray.get`. Existing queries therefore pay
the extra check per element in the `CodegenFallback` higher-order functions
(`transform_keys`, `transform_values`, `zip_with`, `map_zip_with`; for example
`transform_values(m, (k, v) -> v)` over a `map<string, struct<a: int>>` column)
and in interpreted `GetStructField` and `GetArrayItem`, all for a hook that
only test types use. Generated code and `InternalRow.getAccessor` resolve the
type once, so typed reads there are not affected.
The cost hasn't been measured and depends on the JIT. Where the call site
sees many types and the JVM doesn't hash secondary supertypes, a failing
interface check can scan the receiver class's whole supertype list on every
call. That list is long for `StructType`, which mixes in `Seq[StructField]`,
while the arms above are constant-time class checks.
Declaring the marker as a package-private abstract class keeps the per-type
factory and the no-global-state design, and turns this arm into a class check
like the others:
```scala
private[ops] abstract class TestableFrameworkType extends DataType {
def createTypeOps(): TypeOps
}
```
`TestStructBackedType` would then extend it instead of `DataType with
TestableFrameworkType`. A short note in the marker's doc would explain why it
is a class.
**Verification:**
- **Inspection:** Every arm of TypeOps.apply, including the one that admits
test-registered types, matches on a class rather than a trait, and the marker's
documentation explains that choice.
- **Behavior:** A test type that extends the marker still gets the ops its
factory creates from TypeOps.apply and the physical type those ops declare from
PhysicalDataType.
##########
sql/catalyst/src/main/java/org/apache/spark/sql/vectorized/ColumnarBatchRow.java:
##########
@@ -228,6 +229,13 @@ public Object get(int ordinal, DataType dataType) {
} else if (dataType instanceof UserDefinedType<?> udt) {
return get(ordinal, udt.sqlType());
} else {
+ // Framework types: dispatch through PhysicalDataType which resolves the
raw
Review Comment:
**Nit (P3):** This branch is the catch-all for every type the `instanceof`
chain above misses, and its only gate is that `PhysicalDataType` recognizes the
type, so it isn't limited to framework types. It now returns `getInterval` for
`CalendarIntervalType` and `getLong` for TIME here and in `ColumnarRow.get`,
and `getBinaryView` for `GeometryType` and `GeographyType` in
`ColumnarRow.get`. All of these threw `_LEGACY_ERROR_TEMP_3152` or
`_LEGACY_ERROR_TEMP_3155` on the base branch. The new values are correct, but
the comment describes only framework-type dispatch.
This method also has no leading `isNullAt` check. `get(i, NullType)`
therefore passes the gate and fails inside `SpecializedGettersReader` with
`_LEGACY_ERROR_TEMP_3131`, not the `_LEGACY_ERROR_TEMP_3152` the comment says
it keeps.
No test covers the new values on these public classes, or checks that an
unrecognized type such as `ObjectType` still gets the legacy error. The
`TIME(precision=p)` test in `ColumnarBatchSuite` still says the generic `get`
is intentionally not extended for `TimeType`.
Suggested fix: leave the null physical type out of the gate so `NullType`
keeps the base-branch error, make the comment in both classes say which types
the branch reads, and add tests for these types and the kept errors.
**Verification:**
- **Behavior:** ColumnarRow.get and ColumnarBatchRow.get return the stored
value for TIME and CalendarIntervalType columns, and ColumnarRow.get does for
geometry and geography columns, each equal to what the matching typed getter
returns.
- **Regression:** ColumnarBatchRow.get with NullType raises the base
branch's _LEGACY_ERROR_TEMP_3152 rather than the reader's
_LEGACY_ERROR_TEMP_3131, and both classes still raise their original errors for
a type without a physical type such as ObjectType.
- **Inspection:** The fallback comments in both classes and the
ColumnarBatchSuite TIME comment describe the types the generic get reads and
the errors it keeps as the code does.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala:
##########
@@ -0,0 +1,394 @@
+/*
+ * 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.{GenerateMutableProjection,
GenerateOrdering, GenerateSafeProjection, GenerateUnsafeProjection}
+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 used to validate that framework types work end-to-end
through all
+ * dispatch points (interpreted and codegen) by returning a raw
PhysicalStructType.
+ *
+ * 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 DataType with 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.
+ *
+ * Returns PhysicalStructType(fields) as its physical type - this causes all
row
+ * infrastructure dispatchers (SpecializedGettersReader,
InterpretedUnsafeProjection,
+ * CodeGenerator, GenerateUnsafeProjection) to handle it as a struct
automatically.
+ * No PhysicalFrameworkDelegatedType or custom getValue/unsafeWrite needed.
+ */
+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)
+
+ // 8 bytes: struct is variable-length, stored as offset+size pointer in
UnsafeArrayData.
+ override def getElementSize: Int = 8
+
+ // Struct-backed: infrastructure code recurses through StructType branches
for this type.
+ override def rowRepresentationType: Option[DataType] =
+ Some(StructType(TestStructBackedType.FIELDS))
+
+ 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")
+}
+
+/**
+ * Suite validating that framework types with struct-backed physical
representation work
+ * end-to-end through all dispatch points - both interpreted and codegen paths.
+ *
+ * The key design principle: TypeOps.getPhysicalType returns the raw physical
type
+ * (PhysicalStructType). All dispatchers handle it automatically via
PhysicalDataType
+ * dispatch. No special PhysicalFrameworkDelegatedType or ops delegation
needed.
+ */
+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()
+
+ // Read back - UnsafeRow.get dispatches through PhysicalStructType
+ 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") {
Review Comment:
**Non-blocking (P2):** This test feeds a `GenericInternalRow` whose struct
is also a `GenericInternalRow` and compares field values. It therefore still
passes if `setColumn` loses its row-representation lookup and falls back to
`row.update(0, value)` without the copy. The copy only matters when the input
is an `UnsafeRow` whose buffer is reused afterwards.
Several other sites the PR changes have no test at all. Reading the code,
with each lookup reverted, `genEqual` throws
`cannotGenerateCodeForIncomparableTypeError` for the type, `addBufferedState`
and the `MapObjects` and `CatalystToExternalMap` copies keep pointing into the
input `UnsafeRow`, and `GenerateUnsafeProjection.canSupport` returns false,
which makes `ExpressionEvalHelper` quietly skip its unsafe-projection checks.
The suite stays green in each case, and `ObjectExpressionsSuite`'s copy test
covers only built-in types. No production type reaches these branches yet, so
this suite is the only thing that would catch a regression there. Each site
needs a test of its own, and the copy sites need a reused `UnsafeRow` as input.
**Verification:**
- **Regression:** With the row-representation lookup removed from any one of
genEqual, canSupport, addBufferedState, setColumn, MapObjects or
CatalystToExternalMap, at least one of the new struct-backed type tests fails,
and with every lookup in place they all pass.
- **Behavior:** Values of the struct-backed type that the generated mutable
projection writes and that the MapObjects and CatalystToExternalMap lambdas
return keep their contents after the UnsafeRow or unsafe array they were read
from is reused, and the code addBufferedState generates for a value of the type
copies it.
- **Behavior:** Code-generated equality of two values of the type is true
for equal values and false for values that differ in either field, and
canSupport accepts the type and arrays, maps and structs that contain it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TypeOps.scala:
##########
@@ -53,6 +53,12 @@ import org.apache.spark.sql.types.{DataType,
TimestampLTZNanosType, TimestampNTZ
* }
* }}}
*
+ * PHYSICAL TYPE CONTRACT: getPhysicalType must return the raw physical
storage type (e.g.,
+ * PhysicalLongType for Long-backed types, PhysicalStructType for
struct-backed types). All
+ * row infrastructure dispatchers (SpecializedGettersReader,
InterpretedUnsafeProjection,
+ * CodeGenerator, etc.) use PhysicalDataType dispatch and handle the raw type
automatically.
Review Comment:
**Non-blocking (P2):** A developer adding the struct-, array- or map-backed
type this phase prepares for (FILE, for example) reads here that
`getPhysicalType` is enough, but only part of the infrastructure dispatches on
the physical type: `CodeGenerator.getValue` and `javaType`,
`SpecializedGettersReader`, `InternalRow.getAccessor`,
`InterpretedUnsafeProjection`'s field writers and the columnar rows. The
helpers this PR changes match on the logical type and reach such a type only
through `rowRepresentationType`, which defaults to `None`: `genEqual`,
`genComp`, `addBufferedState`, `setColumn`, `getValueFromVector`,
`writeElement`, `canSupport`, `convertToSafe`, and the `MapObjects` and
`CatalystToExternalMap` copies. The interpreted mutable and safe projections
write through the type's `getRowWriter`.
Reading the code, a type that implements only `getPhysicalType =
PhysicalStructType(fields)` gets `row.update(i, value)` with no copy from
`setColumn`, a plain assignment from `addBufferedState`, no `UnsafeRow` copy in
`MapObjects` and `CatalystToExternalMap`, and an unconverted value from
`GenerateSafeProjection`. It therefore keeps references into reused input
buffers with no error. It also hits
`cannotGenerateCodeForIncomparableTypeError` in `genEqual` and a
`writer.write(index, value)` call that matches no `UnsafeWriter` overload for
an `InternalRow`. The IMPLEMENTATION steps never mention
`rowRepresentationType`; the test type works only because
`TestStructBackedTypeOps` overrides it (suite lines 75-77).
The infinite-recursion reason given in the `rowRepresentationType` doc
doesn't match the code either. The resolving sites loop only on a cycle, so a
representation that is another framework type with a `StructType`
representation terminates. `addBufferedState` and the two copies look the
representation up once, miss their `StructType` case and skip the copy with no
error.
The docs should name both routes, list every member a complex-backed type
has to provide, and describe the failure modes these sites actually have.
**Verification:**
- **Inspection:** Checked against the code-generation helpers, the
interpreted projections and the readers, the TypeOps documentation names the
route each uses for a struct-, array- or map-backed type, lists every member
such a type must provide, and states only failure modes those sites have.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/StructBackedFrameworkTypeSuite.scala:
##########
@@ -0,0 +1,394 @@
+/*
+ * 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.{GenerateMutableProjection,
GenerateOrdering, GenerateSafeProjection, GenerateUnsafeProjection}
+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 used to validate that framework types work end-to-end
through all
+ * dispatch points (interpreted and codegen) by returning a raw
PhysicalStructType.
+ *
+ * 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 DataType with 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.
+ *
+ * Returns PhysicalStructType(fields) as its physical type - this causes all
row
+ * infrastructure dispatchers (SpecializedGettersReader,
InterpretedUnsafeProjection,
+ * CodeGenerator, GenerateUnsafeProjection) to handle it as a struct
automatically.
+ * No PhysicalFrameworkDelegatedType or custom getValue/unsafeWrite needed.
+ */
+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)
+
+ // 8 bytes: struct is variable-length, stored as offset+size pointer in
UnsafeArrayData.
+ override def getElementSize: Int = 8
+
+ // Struct-backed: infrastructure code recurses through StructType branches
for this type.
+ override def rowRepresentationType: Option[DataType] =
+ Some(StructType(TestStructBackedType.FIELDS))
+
+ 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")
+}
+
+/**
+ * Suite validating that framework types with struct-backed physical
representation work
+ * end-to-end through all dispatch points - both interpreted and codegen paths.
+ *
+ * The key design principle: TypeOps.getPhysicalType returns the raw physical
type
+ * (PhysicalStructType). All dispatchers handle it automatically via
PhysicalDataType
+ * dispatch. No special PhysicalFrameworkDelegatedType or ops delegation
needed.
Review Comment:
**Nit (P3):** Neither `PhysicalFrameworkDelegatedType` (cited here and at
line 57) nor the `unsafeWrite` hook that line 57 mentions exists anywhere in
the repository, so readers who go looking for them are searching for part of a
design this PR didn't take.
The surrounding claims also overstate what the suite shows:
- Lines 31-32 and 102-103 say framework types are validated end-to-end
through all dispatch points on both paths. Nothing here exercises
`ColumnarRow`, `ColumnarBatchRow`, `getValueFromVector`, `genEqual`,
`addBufferedState`, `MapObjects`, `CatalystToExternalMap`, or the interpreted
safe and mutable projections.
- Lines 54-56 and 105-106 say `PhysicalStructType` alone makes
`CodeGenerator` and `GenerateUnsafeProjection` handle the type. Those helpers
reach it only through the `rowRepresentationType` override at lines 75-77.
- The comment at line 176 says the read-back goes through `UnsafeRow.get`,
but line 177 calls `getStruct`.
The comments should describe what the suite exercises and how: the readers
and the interpreted unsafe writer go through the physical type, and the
generated helpers go through the row representation.
**Verification:**
- **Inspection:** Every dispatch point, path, class and accessor the suite's
comments mention exists in the code and, where a comment says the suite covers
it, is exercised by one of its tests, and the comments' account of how the
generated helpers reach the test type matches the code.
--
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]