spark-test commented on code in PR #60741: URL: https://github.com/apache/spark/pull/60741#discussion_r4638502542
########## sql/api/src/main/scala/org/apache/spark/sql/catalyst/types/ops/FileTypeApiOps.scala: ########## @@ -0,0 +1,107 @@ +/* + * 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 java.io.StringWriter + +import com.fasterxml.jackson.core.JsonFactory + +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoder +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.FileRefEncoder +import org.apache.spark.sql.types.{DataType, FileRef, FileRefInternals, FileType} + +/** + * Client-side (spark-api) operations for FileType. + * + * This class implements TypeApiOps methods for the FILE data type: + * - String formatting: the canonical JSON of a value (see [[FileTypeApiOps.formatJson]]) + * - Row encoding: FileRefEncoder for [[FileRef]] + * - Hive and Row JSON formatting of a FileRef + * + * RELATIONSHIP TO FileTypeOps: FileTypeOps (in catalyst package) extends this class to inherit + * client-side operations while adding server-side operations (physical type, literals, etc.). + * + * @param ft + * The FileType with its mode + * @since 4.4.0 + */ +class FileTypeApiOps(val ft: FileType) extends TypeApiOps { + + override def dataType: DataType = ft + + // ==================== String Formatting ==================== + + // FileTypeOps overrides this for the internal InternalRow value, as InternalRow is not + // available in sql/api. A FileRef is formatted the same way. + override def format(v: Any): String = v match { + case f: FileRef => FileTypeApiOps.formatJson(f) + case _ => v.toString + } + + // FILE has no literal syntax, so this is for display only, such as in EXPLAIN output. Review Comment: **Nit (P3):** Nothing calls a framework type's `toSQLValue`, so this `FILE {...}` form never reaches EXPLAIN. EXPLAIN, generated column names (`toPrettySQL`) and error messages (`QueryErrorsBase.toSQLValue`) render a literal through `Literal.toString` and `Literal.sql` in literals.scala, which have arms for TIME and the nanosecond timestamps but none for FILE, so a FILE literal falls through to its row's `toString`. Reading the code, `df.select(typedLit(new FileRef("s3://bucket/a.pdf", 10L, 2048L, "application/pdf", "MD5:abc")))` gets the column name `[s3://bucket/a.pdf,10,2048,application/pdf,MD5:abc,null]`, and EXPLAIN prints the same text; this change is what makes such literals constructible, through `typedLit` and `Literal.default(FileType)`. FILE arms in `Literal.toString` and `Literal.sql` that render through `FileTypeOps` (`format`, and the `FILE {...}` form of `toSQLValue`), like the arms the TIME and nanosecond-timestamp literals have, would make this comment true. **Verification:** - **Behavior:** The string and SQL forms of a FILE literal built from a FileRef, and of the FILE default literal, are the canonical JSON and the FILE {...} form, and the generated column name of a typed FILE literal uses that form. - **Compatibility:** Literals of TIME, the nanosecond timestamps, structs and other existing types render exactly as before. ########## sql/core/src/main/java/org/apache/spark/sql/execution/vectorized/WritableColumnVector.java: ########## @@ -802,7 +803,7 @@ public final int appendStruct(boolean isNull) { putNull(elementsAppended); elementsAppended++; for (WritableColumnVector c: childColumns) { - if (c.type instanceof StructType || c.type instanceof VariantType + if (isStruct(c.type) || c.type instanceof VariantType Review Comment: **Non-blocking (P2):** `isStruct(c.type)` now runs `TypeOps.rowRepresentationOrSelf` for every child of every null struct-like value: `TypeOps.apply`'s class checks, `flatMap` and a by-name `getOrElse`, plus an ops allocation for TIME, nanosecond-timestamp and FILE children, where the base branch tested `c.type instanceof StructType`. This path is shared by every type, not just FILE: `SparkShreddingUtils.assembleVariantBatch` calls `appendStruct(true)` for every null row when the vectorized Parquet reader assembles a shredded VARIANT column, and `RowToColumnConverter` does so for every null struct, variant, interval or nanosecond timestamp it appends. The vectors produced are the same, but the added work grows with null values times children, the PR does not mention it, and its size has not been measured. A vector's type is fixed when it is constructed, and the constructor already evaluates `rowRepresentationOrSelf(type)` (line 1123 of this file), so a final boolean set there and read here for each child gives the same answer without the per-row lookups. **Verification:** - **Regression:** Appending null rows through the row-to-columnar converter, on and off heap, for a struct whose children include a FILE, a variant, a calendar interval, a nanosecond timestamp and a nested struct still produces null values with every child vector advanced in step. - **Inspection:** The null-struct append path of WritableColumnVector reads a value fixed when the vector was constructed and calls no Types Framework method per appended row. ########## sql/api/src/main/java/org/apache/spark/sql/types/FileRef.java: ########## @@ -0,0 +1,159 @@ +/* + * 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.types; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Objects; +import java.util.StringJoiner; + +import javax.annotation.Nullable; + +import org.apache.spark.annotation.Unstable; + +/** + * The external value of the {@link FileType FILE} data type: a reference to a file, with metadata + * describing it. This is what a FILE value is in a {@code Row}, in {@code collect()} results and + * in the arguments and results of JVM UDFs. + * + * <p>Every field is nullable, as in the Parquet FILE logical type. A reference names the bytes it + * refers to through {@link #uri}, and {@link #offset} and {@link #size} select the byte range + * {@code [offset, offset + size)} of it. The Parquet FILE type also allows the bytes to be stored + * inline in the value. Spark keeps those inline bytes internal: a FileRef carries them, so that a Review Comment: **Nit (P3):** "Spark keeps those inline bytes internal: ... but does not expose them" is broader than the behavior: the canonical JSON that `FileTypeApiOps.formatJson` writes includes `inline` base64-encoded, and that text is what `df.show()` prints (through `ToPrettyString` and `FileTypeOps.format`) and what `Row.json` and the spark-sql CLI print (through `formatExternal`). A value whose inline bytes are 1, 2, 3 is shown as `{...,"inline":"AQID"}`, as `FileTypeOpsSuite` asserts, and `show(truncate = false)` prints the whole payload. Since the PR displays inline on purpose, limiting this sentence to FileRef's API (no public constructor or getter for the bytes) and noting that the displayed JSON includes them would match the behavior; the note on `FileType.FIELDS` (FileType.scala line 117) that `inline` is not exposed as a user-facing field needs the same adjustment. **Verification:** - **Inspection:** The FileRef and FileType.FIELDS documentation no longer states that Spark does not expose the inline bytes, and names the canonical JSON display as including them. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/types/ops/TypeOps.scala: ########## @@ -329,10 +329,18 @@ object TypeOps { case tt: TimeType => Some(TimeTypeOps(tt)) case t: TimestampNTZNanosType => Some(TimestampNTZNanosTypeOps(t)) case t: TimestampLTZNanosType => Some(TimestampLTZNanosTypeOps(t)) + case ft: FileType => Some(FileTypeOps(ft)) // Add new types here - single registration point case ft: TestableFrameworkType => Some(ft.createTypeOps()) case _ => None } + + /** + * Returns the row representation of `dt` (see [[TypeOps.rowRepresentationType]]), or `dt` + * itself when it has none. For callers in Java, such as the column vectors. Review Comment: **Nit (P3):** With this helper the column vectors now build one child vector per field for a struct-backed framework type (WritableColumnVector.java line 1123, ConstantColumnVector.java line 67), but the trait documentation at lines 76-77 of this file still says "Column vectors (WritableColumnVector, ConstantColumnVector) do not yet build child vectors for a struct-, array- or map-backed framework type." Whoever adds the next struct-backed type would be told column-vector support is missing. Limiting that sentence to array- and map-backed types, which `isArray()` and the `MapType` branch still recognize only by their logical type, would make it accurate. **Verification:** - **Inspection:** The TypeOps trait documentation no longer says that column vectors build no child vectors for a struct-backed framework type. ########## sql/core/src/test/scala/org/apache/spark/sql/FileTypeDatasetSuite.scala: ########## @@ -0,0 +1,119 @@ +/* + * 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 + +import scala.beans.BeanProperty +import scala.jdk.CollectionConverters._ + +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types._ + +case class FileRecord(id: Int, file: FileRef, files: Seq[FileRef]) + +class FileBean extends Serializable { + @BeanProperty var id: Int = _ + @BeanProperty var file: FileRef = _ +} + +/** + * Tests for FILE values in Datasets and DataFrames: the FileRef encoder, Row.getFile and the + * paths a FILE value takes through the engine. + */ +class FileTypeDatasetSuite extends QueryTest with SharedSparkSession { + import testImplicits._ + + private val f1 = new FileRef("s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc") + private val f2 = new FileRef("/data/b.txt", null, null, null, null) + + test("a Dataset of FileRef") { + val ds = Seq(f1, f2, null).toDS() + assert(ds.schema === new StructType().add("value", FileType(), nullable = true)) + assert(ds.collect().toSeq === Seq(f1, f2, null)) + assert(ds.map(f => if (f == null) null else f.uri).collect().toSeq === + Seq(f1.uri, f2.uri, null)) + } + + test("a Dataset of a case class with FileRef fields") { + val records = Seq(FileRecord(1, f1, Seq(f2)), FileRecord(2, null, Seq(f1, null))) + val ds = records.toDS() + assert(ds.schema("file").dataType === FileType()) + assert(ds.collect().toSeq === records) + assert(ds.filter($"id" === 2).collect().toSeq === records.tail) + val rows = ds.select($"file", $"files").collect() + assert(rows.map(_.getFile(0)).toSeq === Seq(f1, null)) + assert(rows.map(_.getSeq[FileRef](1)).toSeq === Seq(Seq(f2), Seq(f1, null))) + } + + test("a DataFrame with a FILE EXTERNAL column, read back as FileRef") { + val schema = new StructType().add("id", IntegerType).add("f", FileType.external) + val df = spark.createDataFrame(Seq(Row(1, f1), Row(2, f2), Row(3, null)).asJava, schema) + assert(df.schema === schema) + checkAnswer(df, Seq(Row(1, f1), Row(2, f2), Row(3, null))) + assert(df.collect().map(_.getFile(1)).toSeq === Seq(f1, f2, null)) + assert(df.select($"f").as[FileRef].collect().toSeq === Seq(f1, f2, null)) + } + + test("show renders a FILE value as its canonical JSON") { + val df = Seq(FileRecord(1, f2, Seq(f2))).toDF() + Seq(true, false).foreach { codegen => + withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) { Review Comment: **Nit (P3):** Toggling `spark.sql.codegen.wholeStage` does not reach the interpreted display path: test sessions set the codegen factory mode to `CODEGEN_ONLY`, disable codegen fallback and exclude `ConvertToLocalRelation` (SparkSessionBinder.scala lines 84-90), so `ToPrettyString` runs as generated code in both iterations. No other test evaluates `ToPrettyString` on a FILE interpretively (`FileTypeOpsSuite` calls `FileTypeOps.format` directly and `ToPrettyStringSuite` has no FILE case), so if `ToStringBase.frameworkOps` went back to the client-side ops, the interpreted path would print the internal row and every test would still pass. In production that is the usual path for `show()` of local data, because `ConvertToLocalRelation` evaluates the projection with `InterpretedMutableProjection`. Running the iteration without whole-stage code generation under the `NO_CODEGEN` factory mode as well, or a FILE case in `ToPrettyStringSuite` that evaluates both ways, would cover it. **Verification:** - **Regression:** Interpreted and generated evaluation of ToPrettyString on a top-level FILE value and on FILE values nested in an array, a map value and a struct give the canonical JSON, and the interpreted case fails if the interpreted path formats a FILE through its client-side ops. - **Behavior:** show() of a local DataFrame with FILE columns gives the canonical JSON with whole-stage code generation on, and with it off under interpreted expression evaluation. ########## sql/api/src/main/scala/org/apache/spark/sql/types/FileType.scala: ########## @@ -31,8 +31,8 @@ import org.apache.spark.annotation.Unstable * `"file unknown"` for `FileType()`, except that an external file in a struct field is the plain * `"file"`. A bare `"file"` is read as external inside a struct field and as unknown elsewhere. * - * FileType is planned to be physically stored as a struct with the following fields (see - * `FileType.FIELDS`), but it deliberately does not extend [[StructType]]: + * FileType is physically stored as a struct with the following fields (see `FileType.FIELDS`), + * but it deliberately does not extend [[StructType]]. Its external value is [[FileRef]]: Review Comment: **Nit (P3):** Because the new sentence ends with the colon, the bullet list below (uri, offset, size, content_type, checksum, inline) now reads as the fields of `FileRef`, which has `contentType` rather than `content_type` and deliberately exposes no `inline`. Ending the first sentence with the colon (`... does not extend [[StructType]]:`) and moving `Its external value is [[FileRef]].` after the list keeps the list attached to the physical struct layout. **Verification:** - **Inspection:** The FileType Scaladoc's bullet list of uri, offset, size, content_type, checksum and inline follows the sentence about the physical struct, not the one naming FileRef. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ToStringBase.scala: ########## @@ -86,10 +86,16 @@ trait ToStringBase { self: UnaryExpression with TimeZoneAwareExpression => // nanos renders in it; zone-independent types (TimeType, TIMESTAMP_NTZ nanos) ignore it // (SPARK-57285). private def castToString(from: DataType): Any => UTF8String = - TypeApiOps(from, zoneId) + frameworkOps(from) .map(ops => acceptAny[Any](ops.formatUTF8)) .getOrElse(castToStringDefault(from)) + // The internal value of a type stored as a struct, such as FileType, is an InternalRow, which + // only its catalyst-side ops can format. Other framework types use their client-side ops, which + // carry the cast's zone. + private def frameworkOps(from: DataType): Option[TypeApiOps] = + TypeOps(from).filter(_.rowRepresentationType.isDefined).orElse(TypeApiOps(from, zoneId)) Review Comment: **Nit (P3):** `frameworkOps` puts a `TypeOps` lookup (class checks, `filter` and a by-name `orElse`, plus an ops allocation for TIME and the nanosecond timestamps) in front of the base branch's single `TypeApiOps` lookup. The interpreted array, map and struct formatters in `castToStringDefault` call `castToString` for their element, key, value and field types inside the lambdas that run per value (lines 116, 144-145 and 177 of this file), so this lookup now runs once per nested value for every type: for an `array<struct>` of length L whose struct has F fields, 1 + L x F extra lookups per row. That happens whenever the cast or `ToPrettyString` is evaluated interpretively, such as for a `LocalRelation` projection that `ConvertToLocalRelation` folds, after a code generation fallback, or under a `CodegenFallback` parent; generated code pays it only while generating. The cost is small next to the per-value work the base branch already does here, but the PR does not state it, and buildi ng the nested formatters once, outside the per-value lambdas, removes it without changing any output. **Verification:** - **Compatibility:** Interpreted evaluation of a cast to string over nested arrays, maps and structs holding TIME and nanosecond-timestamp values, and of ToPrettyString over nested values that also hold FILE values, including empty and null nested values, gives the same strings as generated evaluation. - **Inspection:** The interpreted array, map and struct formatters build their nested formatters outside the lambdas that run per value. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/FileTypeOpsSuite.scala: ########## @@ -0,0 +1,310 @@ +/* + * 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.{SparkException, SparkFunSuite} +import org.apache.spark.sql.{AnalysisException, Row} +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, DeserializerBuildHelper, InternalRow, SerializerBuildHelper} +import org.apache.spark.sql.catalyst.encoders.{ExpressionEncoder, RowEncoder} +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{FileRefEncoder, OptionEncoder} +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.codegen.{GenerateSafeProjection, GenerateUnsafeProjection} +import org.apache.spark.sql.catalyst.plans.SQLHelper +import org.apache.spark.sql.catalyst.types.{DataTypeUtils, PhysicalDataType, PhysicalStructType} +import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +case class FileHolder(id: Int, file: FileRef, maybe: Option[FileRef], files: Seq[FileRef]) + +/** + * Tests for FileType in the Types Framework: its physical representation, the conversions + * between [[FileRef]] and InternalRow, the row and code generation paths, formatting and the + * FileRef encoder. + */ +class FileTypeOpsSuite extends SparkFunSuite with SQLHelper { + + private val allFields = FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2, 3)) + + private val uriOnly = new FileRef("/data/a.txt", null, null, null, null) + + private def fileRow( + uri: String, + offset: java.lang.Long = null, + size: java.lang.Long = null, + contentType: String = null, + checksum: String = null, + inline: Array[Byte] = null): InternalRow = new GenericInternalRow(Array[Any]( + UTF8String.fromString(uri), offset, size, UTF8String.fromString(contentType), + UTF8String.fromString(checksum), inline)) + + private def assertFileRow(row: InternalRow, expected: FileRef): Unit = { + assert(FileTypeOps.toFileRef(row) === expected) + } + + // ==================== Physical Type Representation ==================== + + test("FileType has a struct physical type and row representation") { + Seq(FileType(), FileType.external).foreach { ft => + val ops = TypeOps(ft).get + assert(ops.isInstanceOf[FileTypeOps]) + assert(PhysicalDataType(ft) === PhysicalStructType(FileType.FIELDS)) + assert(ops.rowRepresentationType === Some(FileType.asStruct)) + assert(ops.getElementSize === 8) + assert(ops.getJavaClass === classOf[InternalRow]) + assert(ops.getMutableValue.isInstanceOf[MutableAny]) + assert(TypeApiOps(ft).get.isInstanceOf[FileTypeApiOps]) + } + assert(TypeOps.rowRepresentationOrSelf(FileType()) === FileType.asStruct) + assert(TypeOps.rowRepresentationOrSelf(IntegerType) === IntegerType) + } + + test("default literal") { + val lit = Literal.default(FileType.external) + assert(lit.dataType === FileType.external) + assertFileRow(lit.value.asInstanceOf[InternalRow], new FileRef("", null, null, null, null)) + } + + test("there is no Java literal") { + val e = intercept[SparkException] { + FileTypeOps(FileType()).getJavaLiteral(fileRow("/a")) + } + assert(e.getCondition === "INTERNAL_ERROR") + } + + test("literal validation") { + Literal.create(fileRow("/a"), FileType()) + intercept[IllegalArgumentException](Literal.create("/a", FileType())) + } + + // ==================== External Type Conversion ==================== + + test("FileRef to InternalRow and back keeps every field, including inline") { + val ops = FileTypeOps(FileType()) + Seq(allFields, uriOnly, new FileRef(null, null, 3L, "image/png", null), + FileRefInternals.create(null, null, null, null, null, Array[Byte](7))).foreach { f => + val row = ops.toCatalystImpl(f).asInstanceOf[InternalRow] + assert(row.numFields === FileType.FIELDS.length) + assert(ops.toScala(row) === f) + } + val row = ops.toCatalystImpl(allFields).asInstanceOf[InternalRow] + assert(row.getUTF8String(FileType.URI_INDEX).toString === "s3://bucket/dir/doc.pdf") + assert(row.getLong(FileType.OFFSET_INDEX) === 10L) + assert(row.getLong(FileType.SIZE_INDEX) === 2048L) + assert(row.getUTF8String(FileType.CONTENT_TYPE_INDEX).toString === "application/pdf") + assert(row.getUTF8String(FileType.CHECKSUM_INDEX).toString === "MD5:abc123") + assert(row.getBinary(FileType.INLINE_INDEX).toSeq === Seq[Byte](1, 2, 3)) + val nulls = ops.toCatalystImpl(uriOnly).asInstanceOf[InternalRow] + (1 until FileType.FIELDS.length).foreach(i => assert(nulls.isNullAt(i), s"field $i")) + assert(ops.toScala(null) === null) + } + + test("CatalystTypeConverters round-trip") { + val toCatalyst = CatalystTypeConverters.createToCatalystConverter(FileType.external) + val toScala = CatalystTypeConverters.createToScalaConverter(FileType.external) + assert(toScala(toCatalyst(allFields)) === allFields) + assert(toCatalyst(null) === null) + val structType = new StructType().add("f", FileType.external) + val rowToCatalyst = CatalystTypeConverters.createToCatalystConverter(structType) + val rowToScala = CatalystTypeConverters.createToScalaConverter(structType) + assert(rowToScala(rowToCatalyst(Row(allFields))) === Row(allFields)) + } + + // ==================== Row Access and Code Generation ==================== + + test("read through SpecializedGettersReader") { + val row = new GenericInternalRow(Array[Any](fileRow("/r.txt", size = 100L))) + val value = SpecializedGettersReader.read(row, 0, FileType(), true, false) + assertFileRow(value.asInstanceOf[InternalRow], new FileRef("/r.txt", null, 100L, null, null)) + } + + private val values: Seq[FileRef] = Seq(allFields, uriOnly) + + private def unsafeProjections(dt: DataType): Seq[(String, UnsafeProjection)] = { + val exprs = Seq(BoundReference(0, dt, nullable = true)) + Seq( + "interpreted" -> new InterpretedUnsafeProjection(exprs.toArray), + "codegen" -> GenerateUnsafeProjection.generate(exprs)) + } + + test("unsafe projection of a FILE column, a null value and null fields") { + val ops = FileTypeOps(FileType()) + unsafeProjections(FileType()).foreach { case (mode, projection) => + values.foreach { f => + val out = projection(new GenericInternalRow(Array[Any](ops.toCatalystImpl(f)))).copy() + assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length)) === f, mode) + } + assert(projection(new GenericInternalRow(Array[Any](null))).isNullAt(0), mode) + } + } + + test("unsafe projection of an array of FILE, a map with FILE values and a struct with FILE") { + val ops = FileTypeOps(FileType()) + val elems = values.map(ops.toCatalystImpl) :+ null + val arrayType = ArrayType(FileType(), containsNull = true) + unsafeProjections(arrayType).foreach { case (mode, projection) => + val out = projection(new GenericInternalRow(Array[Any](new GenericArrayData(elems)))) + val array = out.getArray(0) + assert(array.numElements() === 3, mode) + values.indices.foreach { i => + assert(FileTypeOps.toFileRef(array.getStruct(i, FileType.FIELDS.length)) === values(i)) + } + assert(array.isNullAt(2), mode) + } + val mapType = MapType(StringType, FileType(), valueContainsNull = true) + unsafeProjections(mapType).foreach { case (mode, projection) => + val map = ArrayBasedMapData( + Array[Any](UTF8String.fromString("k1"), UTF8String.fromString("k2")), + Array[Any](ops.toCatalystImpl(allFields), null)) + val out = projection(new GenericInternalRow(Array[Any](map))).getMap(0) + assert(FileTypeOps.toFileRef(out.valueArray().getStruct(0, FileType.FIELDS.length)) === + allFields, mode) + assert(out.valueArray().isNullAt(1), mode) + } + val structType = new StructType().add("id", IntegerType).add("f", FileType()) + unsafeProjections(structType).foreach { case (mode, projection) => + val inner = new GenericInternalRow(Array[Any](1, ops.toCatalystImpl(uriOnly))) + val out = projection(new GenericInternalRow(Array[Any](inner))).getStruct(0, 2) + assert(out.getInt(0) === 1, mode) + assert(FileTypeOps.toFileRef(out.getStruct(1, FileType.FIELDS.length)) === uriOnly, mode) + } + } + + test("safe projection copies a FILE value out of a reused UnsafeRow") { + val ops = FileTypeOps(FileType()) + val producer = UnsafeProjection.create(Array[DataType](FileType())) + val input = producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields)))) + val exprs = Seq(BoundReference(0, FileType(), nullable = true)) + Seq( + "interpreted" -> InterpretedSafeProjection.createProjection(exprs), + "codegen" -> GenerateSafeProjection.generate(exprs)).foreach { case (mode, projection) => + val out = projection(input) + producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(uriOnly)))) + assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length)) === allFields, mode) + producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields)))) + } + } + + // ==================== Formatting ==================== + + test("format renders the canonical JSON and omits null fields") { + val ops = FileTypeOps(FileType()) + assert(ops.format(ops.toCatalystImpl(allFields)) === + """{"uri":"s3://bucket/dir/doc.pdf","offset":10,"size":2048,""" + + """"content_type":"application/pdf","checksum":"MD5:abc123","inline":"AQID"}""") + assert(ops.format(ops.toCatalystImpl(uriOnly)) === """{"uri":"/data/a.txt"}""") + assert(ops.format(fileRow("""a "quoted"\path""")) === """{"uri":"a \"quoted\"\\path"}""") + assert(ops.toSQLValue(ops.toCatalystImpl(uriOnly)) === """FILE {"uri":"/data/a.txt"}""") + // The external value renders the same way. + assert(new FileTypeApiOps(FileType()).format(allFields) === + ops.format(ops.toCatalystImpl(allFields))) + assert(ops.formatExternal(uriOnly) === Some("""{"uri":"/data/a.txt"}""")) + } + + test("FileRef equality, hash code and string representation") { + val same = FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2, 3)) + assert(allFields === same) + assert(allFields.hashCode === same.hashCode) + assert(allFields !== FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2))) + assert(uriOnly !== new FileRef("/data/a.txt", 0L, null, null, null)) Review Comment: **Nit (P3):** This test checks inequality only for a different `inline` array (line 225) and a different `offset` (this line), while `FileRef.equals` compares all six fields and the round-trip assertions in this suite, `FileTypeDatasetSuite`, `RowToColumnConverterSuite` and `ColumnVectorUtilsSuite` compare FileRefs through it. An `equals` that ignored `uri`, `size`, `contentType` or `checksum` would keep every test green, and would also let a conversion to FileRef that drops that field pass. One inequality case for each of those four fields would close the gap. **Verification:** - **Regression:** The FileRef equality coverage fails when equals ignores any one of its six fields. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/types/ops/FileTypeOpsSuite.scala: ########## @@ -0,0 +1,310 @@ +/* + * 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.{SparkException, SparkFunSuite} +import org.apache.spark.sql.{AnalysisException, Row} +import org.apache.spark.sql.catalyst.{CatalystTypeConverters, DeserializerBuildHelper, InternalRow, SerializerBuildHelper} +import org.apache.spark.sql.catalyst.encoders.{ExpressionEncoder, RowEncoder} +import org.apache.spark.sql.catalyst.encoders.AgnosticEncoders.{FileRefEncoder, OptionEncoder} +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.codegen.{GenerateSafeProjection, GenerateUnsafeProjection} +import org.apache.spark.sql.catalyst.plans.SQLHelper +import org.apache.spark.sql.catalyst.types.{DataTypeUtils, PhysicalDataType, PhysicalStructType} +import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +case class FileHolder(id: Int, file: FileRef, maybe: Option[FileRef], files: Seq[FileRef]) + +/** + * Tests for FileType in the Types Framework: its physical representation, the conversions + * between [[FileRef]] and InternalRow, the row and code generation paths, formatting and the + * FileRef encoder. + */ +class FileTypeOpsSuite extends SparkFunSuite with SQLHelper { + + private val allFields = FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2, 3)) + + private val uriOnly = new FileRef("/data/a.txt", null, null, null, null) + + private def fileRow( + uri: String, + offset: java.lang.Long = null, + size: java.lang.Long = null, + contentType: String = null, + checksum: String = null, + inline: Array[Byte] = null): InternalRow = new GenericInternalRow(Array[Any]( + UTF8String.fromString(uri), offset, size, UTF8String.fromString(contentType), + UTF8String.fromString(checksum), inline)) + + private def assertFileRow(row: InternalRow, expected: FileRef): Unit = { + assert(FileTypeOps.toFileRef(row) === expected) + } + + // ==================== Physical Type Representation ==================== + + test("FileType has a struct physical type and row representation") { + Seq(FileType(), FileType.external).foreach { ft => + val ops = TypeOps(ft).get + assert(ops.isInstanceOf[FileTypeOps]) + assert(PhysicalDataType(ft) === PhysicalStructType(FileType.FIELDS)) + assert(ops.rowRepresentationType === Some(FileType.asStruct)) + assert(ops.getElementSize === 8) + assert(ops.getJavaClass === classOf[InternalRow]) + assert(ops.getMutableValue.isInstanceOf[MutableAny]) + assert(TypeApiOps(ft).get.isInstanceOf[FileTypeApiOps]) + } + assert(TypeOps.rowRepresentationOrSelf(FileType()) === FileType.asStruct) + assert(TypeOps.rowRepresentationOrSelf(IntegerType) === IntegerType) + } + + test("default literal") { + val lit = Literal.default(FileType.external) + assert(lit.dataType === FileType.external) + assertFileRow(lit.value.asInstanceOf[InternalRow], new FileRef("", null, null, null, null)) + } + + test("there is no Java literal") { + val e = intercept[SparkException] { + FileTypeOps(FileType()).getJavaLiteral(fileRow("/a")) + } + assert(e.getCondition === "INTERNAL_ERROR") + } + + test("literal validation") { + Literal.create(fileRow("/a"), FileType()) + intercept[IllegalArgumentException](Literal.create("/a", FileType())) + } + + // ==================== External Type Conversion ==================== + + test("FileRef to InternalRow and back keeps every field, including inline") { + val ops = FileTypeOps(FileType()) + Seq(allFields, uriOnly, new FileRef(null, null, 3L, "image/png", null), + FileRefInternals.create(null, null, null, null, null, Array[Byte](7))).foreach { f => + val row = ops.toCatalystImpl(f).asInstanceOf[InternalRow] + assert(row.numFields === FileType.FIELDS.length) + assert(ops.toScala(row) === f) + } + val row = ops.toCatalystImpl(allFields).asInstanceOf[InternalRow] + assert(row.getUTF8String(FileType.URI_INDEX).toString === "s3://bucket/dir/doc.pdf") + assert(row.getLong(FileType.OFFSET_INDEX) === 10L) + assert(row.getLong(FileType.SIZE_INDEX) === 2048L) + assert(row.getUTF8String(FileType.CONTENT_TYPE_INDEX).toString === "application/pdf") + assert(row.getUTF8String(FileType.CHECKSUM_INDEX).toString === "MD5:abc123") + assert(row.getBinary(FileType.INLINE_INDEX).toSeq === Seq[Byte](1, 2, 3)) + val nulls = ops.toCatalystImpl(uriOnly).asInstanceOf[InternalRow] + (1 until FileType.FIELDS.length).foreach(i => assert(nulls.isNullAt(i), s"field $i")) + assert(ops.toScala(null) === null) + } + + test("CatalystTypeConverters round-trip") { + val toCatalyst = CatalystTypeConverters.createToCatalystConverter(FileType.external) + val toScala = CatalystTypeConverters.createToScalaConverter(FileType.external) + assert(toScala(toCatalyst(allFields)) === allFields) + assert(toCatalyst(null) === null) + val structType = new StructType().add("f", FileType.external) + val rowToCatalyst = CatalystTypeConverters.createToCatalystConverter(structType) + val rowToScala = CatalystTypeConverters.createToScalaConverter(structType) + assert(rowToScala(rowToCatalyst(Row(allFields))) === Row(allFields)) + } + + // ==================== Row Access and Code Generation ==================== + + test("read through SpecializedGettersReader") { + val row = new GenericInternalRow(Array[Any](fileRow("/r.txt", size = 100L))) + val value = SpecializedGettersReader.read(row, 0, FileType(), true, false) + assertFileRow(value.asInstanceOf[InternalRow], new FileRef("/r.txt", null, 100L, null, null)) + } + + private val values: Seq[FileRef] = Seq(allFields, uriOnly) + + private def unsafeProjections(dt: DataType): Seq[(String, UnsafeProjection)] = { + val exprs = Seq(BoundReference(0, dt, nullable = true)) + Seq( + "interpreted" -> new InterpretedUnsafeProjection(exprs.toArray), + "codegen" -> GenerateUnsafeProjection.generate(exprs)) + } + + test("unsafe projection of a FILE column, a null value and null fields") { + val ops = FileTypeOps(FileType()) + unsafeProjections(FileType()).foreach { case (mode, projection) => + values.foreach { f => + val out = projection(new GenericInternalRow(Array[Any](ops.toCatalystImpl(f)))).copy() + assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length)) === f, mode) + } + assert(projection(new GenericInternalRow(Array[Any](null))).isNullAt(0), mode) + } + } + + test("unsafe projection of an array of FILE, a map with FILE values and a struct with FILE") { + val ops = FileTypeOps(FileType()) + val elems = values.map(ops.toCatalystImpl) :+ null + val arrayType = ArrayType(FileType(), containsNull = true) + unsafeProjections(arrayType).foreach { case (mode, projection) => + val out = projection(new GenericInternalRow(Array[Any](new GenericArrayData(elems)))) + val array = out.getArray(0) + assert(array.numElements() === 3, mode) + values.indices.foreach { i => + assert(FileTypeOps.toFileRef(array.getStruct(i, FileType.FIELDS.length)) === values(i)) + } + assert(array.isNullAt(2), mode) + } + val mapType = MapType(StringType, FileType(), valueContainsNull = true) + unsafeProjections(mapType).foreach { case (mode, projection) => + val map = ArrayBasedMapData( + Array[Any](UTF8String.fromString("k1"), UTF8String.fromString("k2")), + Array[Any](ops.toCatalystImpl(allFields), null)) + val out = projection(new GenericInternalRow(Array[Any](map))).getMap(0) + assert(FileTypeOps.toFileRef(out.valueArray().getStruct(0, FileType.FIELDS.length)) === + allFields, mode) + assert(out.valueArray().isNullAt(1), mode) + } + val structType = new StructType().add("id", IntegerType).add("f", FileType()) + unsafeProjections(structType).foreach { case (mode, projection) => + val inner = new GenericInternalRow(Array[Any](1, ops.toCatalystImpl(uriOnly))) + val out = projection(new GenericInternalRow(Array[Any](inner))).getStruct(0, 2) + assert(out.getInt(0) === 1, mode) + assert(FileTypeOps.toFileRef(out.getStruct(1, FileType.FIELDS.length)) === uriOnly, mode) + } + } + + test("safe projection copies a FILE value out of a reused UnsafeRow") { + val ops = FileTypeOps(FileType()) + val producer = UnsafeProjection.create(Array[DataType](FileType())) + val input = producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields)))) + val exprs = Seq(BoundReference(0, FileType(), nullable = true)) + Seq( + "interpreted" -> InterpretedSafeProjection.createProjection(exprs), + "codegen" -> GenerateSafeProjection.generate(exprs)).foreach { case (mode, projection) => + val out = projection(input) + producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(uriOnly)))) + assert(FileTypeOps.toFileRef(out.getStruct(0, FileType.FIELDS.length)) === allFields, mode) + producer(new GenericInternalRow(Array[Any](ops.toCatalystImpl(allFields)))) + } + } + + // ==================== Formatting ==================== + + test("format renders the canonical JSON and omits null fields") { + val ops = FileTypeOps(FileType()) + assert(ops.format(ops.toCatalystImpl(allFields)) === + """{"uri":"s3://bucket/dir/doc.pdf","offset":10,"size":2048,""" + + """"content_type":"application/pdf","checksum":"MD5:abc123","inline":"AQID"}""") + assert(ops.format(ops.toCatalystImpl(uriOnly)) === """{"uri":"/data/a.txt"}""") + assert(ops.format(fileRow("""a "quoted"\path""")) === """{"uri":"a \"quoted\"\\path"}""") + assert(ops.toSQLValue(ops.toCatalystImpl(uriOnly)) === """FILE {"uri":"/data/a.txt"}""") + // The external value renders the same way. + assert(new FileTypeApiOps(FileType()).format(allFields) === + ops.format(ops.toCatalystImpl(allFields))) + assert(ops.formatExternal(uriOnly) === Some("""{"uri":"/data/a.txt"}""")) + } + + test("FileRef equality, hash code and string representation") { + val same = FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2, 3)) + assert(allFields === same) + assert(allFields.hashCode === same.hashCode) + assert(allFields !== FileRefInternals.create( + "s3://bucket/dir/doc.pdf", 10L, 2048L, "application/pdf", "MD5:abc123", Array[Byte](1, 2))) + assert(uriOnly !== new FileRef("/data/a.txt", 0L, null, null, null)) + assert(allFields.toString === "FileRef{uri='s3://bucket/dir/doc.pdf', offset=10, size=2048, " + + "contentType='application/pdf', checksum='MD5:abc123', inline=<3 bytes>}") + assert(new FileRef(null, null, null, null, null).toString === "FileRef{}") + } + + // ==================== Encoders ==================== + + test("encoders of FileRef, of a case class with FileRef fields and of a Row") { + val enc = ExpressionEncoder[FileRef]().resolveAndBind() + assert(enc.schema === new StructType().add("value", FileType(), nullable = true)) + values.foreach { f => + assert(enc.createDeserializer()(enc.createSerializer()(f)) === f) + } + + val holderEnc = ExpressionEncoder[FileHolder]().resolveAndBind() + assert(holderEnc.schema("file").dataType === FileType()) + assert(holderEnc.schema("files").dataType === ArrayType(FileType(), containsNull = true)) + Seq(FileHolder(1, allFields, Some(uriOnly), Seq(uriOnly, null)), + FileHolder(2, null, None, Nil)).foreach { h => + assert(holderEnc.createDeserializer()(holderEnc.createSerializer()(h).copy()) === h) + } + + val schema = new StructType().add("f", FileType.external).add("fs", ArrayType(FileType())) + val rowEnc = ExpressionEncoder(RowEncoder.encoderFor(schema)).resolveAndBind() Review Comment: **Nit (P3):** The Row encoder here is checked only through round-tripped values, which do not depend on the FILE mode, while the FileRef and case-class encoders above assert their schemas. That a Row encoder keeps `FILE EXTERNAL` rests only on `FileTypeApiOps.getEncoder` returning `FileRefEncoder(ft.mode)`, and `FileTypeDatasetSuite` builds its FILE EXTERNAL DataFrame through `CatalystTypeConverters`, so if `getEncoder` returned `FileRefEncoder()`, `Encoders.row(schema)` would produce a FILE UNKNOWN column, which cannot be written to a table, and no test would fail. Asserting `rowEnc.schema === schema` would cover it. **Verification:** - **Regression:** The Row encoder coverage fails when a Row encoder serializes a FILE EXTERNAL field as a FILE of unknown mode. -- 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]
