rich7420 commented on code in PR #7155:
URL: https://github.com/apache/datafusion-comet/pull/7155#discussion_r4775319876
##########
spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala:
##########
@@ -610,7 +611,35 @@ case class CometExecRule(session: SparkSession,
queryStagePrep: Boolean = false)
// A shuffle directly under the native write stays in the child stage
and is not wrapped
// again.
case op: IcebergWriteExec if
CometConf.COMET_ICEBERG_NATIVE_WRITE_ENABLED.get(op.conf) =>
- convertToComet(op, CometIcebergNativeWrite).getOrElse(op)
+ // Spark inserts AssertNotNull projections for nullable input to
required Iceberg fields.
+ // Keep their row-wise evaluation in Spark, including any sort or
limit above them, and
+ // convert the writer's input to Arrow only after Spark has evaluated
those operators.
+ val needsRowConversion = !op.child.isInstanceOf[CometNativeExec] &&
+ op.child.exists {
+ case project: ProjectExec =>
+
project.projectList.exists(_.exists(_.isInstanceOf[AssertNotNull]))
+ case _ => false
+ }
+ val rowConversionReasons = ListBuffer.empty[String]
+ val prepared =
+ if (needsRowConversion &&
Review Comment:
On a merge-on-read `PositionDeltaWrite` with `AssertNotNull`,
`isRowInputEvaluationSupported` runs before `getSupportLevel(op)` and tags a
constraint-resolution reason. Could we check `getSupportLevel(op)` first so we
skip discarded bridges and the `FALLBACK_REASONS` copy-back?
##########
spark/src/main/scala/org/apache/spark/sql/comet/CometSparkToColumnarExec.scala:
##########
@@ -129,7 +132,75 @@ case class CometSparkToColumnarExec(child: SparkPlan,
batchSize: Option[Int] = N
}
-object CometSparkToColumnarExec extends CometSink[SparkPlan] with
DataTypeSupport {
+object CometSparkToColumnarExec
+ extends CometSink[SparkPlan]
+ with DataTypeSupport
+ with CometTypeShim {
+
+ /**
+ * Whether the Iceberg writer may convert this Spark row subtree to Arrow.
Native import
+ * normalizes invalid UTF-8, while Spark rows can retain those bytes. A new
conversion is safe
+ * only when its string outputs preserve already valid strings or contain
validated literals.
+ */
+ def isRowConversionSupported(plan: SparkPlan, fallbackReasons:
ListBuffer[String]): Boolean = {
+ if (!isSchemaSupported(plan.schema, fallbackReasons)) {
+ false
+ } else if (hasValidStrings(plan)) {
+ true
+ } else {
+ fallbackReasons += "Iceberg writer row conversion cannot prove that
string outputs contain " +
+ "valid UTF-8; native Arrow import could change their bytes"
+ false
+ }
+ }
+
+ private def containsString(dt: DataType): Boolean =
+ dt.existsRecursively(_.isInstanceOf[StringType])
+
+ private def hasValidStrings(plan: SparkPlan): Boolean = {
+ if (!containsString(plan.schema)) {
Review Comment:
When `plan.schema` has no `StringType`, this returns `true` for any Spark
plan and bridges `LocalTableScanExec` or `RDDScanExec` even with their configs
off. Could we require a Comet producer for non-string schemas too, matching
`iceberg-writes.md`?
##########
spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala:
##########
@@ -104,6 +111,746 @@ class CometIcebergWriteActionSuite
}
}
+ Seq(
+ "id INT NOT NULL, s STRUCT<a: INT, b: STRING>",
+ "id INT NOT NULL, s STRUCT<a: INT NOT NULL, b: STRING>",
+ "id INT, s STRUCT<a: INT, b: STRING> NOT NULL").zipWithIndex.foreach {
case (schema, index) =>
+ val adaptiveModes = if (index == 0) Seq(false, true) else Seq(false)
+ adaptiveModes.foreach { adaptive =>
+ test(s"native Iceberg writer: Spark validates nullable input $index,
AQE=$adaptive") {
+ assume(icebergAvailable)
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key ->
adaptive.toString) {
+ withIcebergCatalog { _ =>
+ withTempPath { path =>
+ sql("SELECT 1 AS id, named_struct('a', 2, 'b', 'value') AS
s").write.parquet(
+ path.toString)
+ val input = spark.read.parquet(path.toString)
+ withTempView("required_write_source") {
+ input.createOrReplaceTempView("required_write_source")
+ Seq("", "PARTITIONED BY (bucket(4, id))").zipWithIndex.foreach
{
+ case (partition, partIndex) =>
+ val table =
s"required_input_${index}_${partIndex}_$adaptive"
+ val reference = s"${table}_jvm"
+ Seq(table, reference).foreach { name =>
+ sql(s"""CREATE TABLE cat.db.$name ($schema) USING
iceberg $partition
+ |TBLPROPERTIES
('write.distribution-mode'='none')""".stripMargin)
+ }
+ def appendBoth(name: String): Unit = {
+ sql(s"INSERT INTO cat.db.$name SELECT * FROM
required_write_source")
+ input.writeTo(s"cat.db.$name").append()
+ }
+ val snapshot = withNativeEnabled {
+ captureWrite(table) {
+ withSQLConf("spark.sql.adaptive.forceApply" ->
adaptive.toString) {
+ appendBoth(table)
+ }
+ }
+ }
+ assert(snapshot.snapshotDelta == 2)
+ assertSparkRequiredWrite(snapshot.plans)
+ assertRequiredWriteAdaptivePlan(snapshot.plans, adaptive)
+ assert(
+ snapshot.plans.count(p =>
+ collectWithSubqueries(p) { case w:
CometIcebergWriteExec =>
+ w
+ }.nonEmpty) == 2,
+ snapshot.plans.mkString("\n"))
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ appendBoth(reference)
+ }
+ checkAnswer(
+ sql(s"SELECT * FROM cat.db.$table"),
+ sql(s"SELECT * FROM cat.db.$reference"))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Seq(false, true).foreach { adaptive =>
+ test(s"native Iceberg writer: required input keeps the default shuffle,
AQE=$adaptive") {
Review Comment:
The `fanout` check catches removing
`!op.child.isInstanceOf[CometNativeExec]` cleanly. Maybe add one `AQE=true`
test with a shuffle stage below `AssertNotNull` so AQE re-planning into the
bridge is covered too?
##########
spark/src/test/scala/org/apache/comet/CometIcebergWriteActionSuite.scala:
##########
@@ -4425,6 +5172,260 @@ class CometIcebergWriteActionSuite
}
}
+ test(
+ "native Iceberg writer: required-field bridge preserves primitive values
and UTC partitions") {
+ assume(icebergAvailable)
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.SESSION_LOCAL_TIMEZONE.key -> "America/Los_Angeles",
+ SQLConf.DATETIME_JAVA8API_ENABLED.key -> "false",
+ SQLConf.TIMESTAMP_TYPE.key -> "TIMESTAMP_LTZ",
+ SQLConf.PARQUET_OUTPUT_TIMESTAMP_TYPE.key -> "TIMESTAMP_MICROS") {
+ withIcebergCatalog { warehouseDir =>
+ withTempPath { path =>
+ val columns = "ts TIMESTAMP, dt DATE, dec_value DECIMAL(38,10), f
FLOAT, d DOUBLE"
+ def row(id: Int, ts: String, date: String, decimal: String, f:
Float, d: Double): Row =
+ Row(
+ id,
+ Timestamp.from(Instant.parse(ts)),
+ Date.valueOf(date),
+ new BigDecimal(decimal),
+ f,
+ d)
+
+ // The first two instants straddle UTC midnight. The next one
crosses local midnight
+ // but still belongs to the second UTC partition.
+ val expectedRows = Seq(
+ row(
+ 1,
+ "1969-12-31T23:59:59.999999Z",
+ "1969-12-31",
+ "1234567890123456789012345678.0123456789",
+ -0.0f,
+ 0.0d),
+ row(
+ 2,
+ "1970-01-01T00:00:00.000001Z",
+ "1970-01-01",
+ "-1234567890123456789012345678.9876543210",
+ 0.0f,
+ -0.0d),
+ row(
+ 3,
+ "1970-01-01T08:00:00.000001Z",
+ "2000-02-29",
+ "0.0000000001",
+ Float.NaN,
+ Double.NaN),
+ row(4, "1970-01-02T00:00:00.123456Z", "2024-03-01",
"-0.0000000001", 1.25f, -2.5d))
+ spark
+ .createDataFrame(
+ spark.sparkContext.parallelize(expectedRows, 1),
+ StructType.fromDDL(s"id INT, $columns"))
+ .write
+ .parquet(path.toString)
+ val input = spark.read.parquet(path.toString)
+ assert(input.schema("id").nullable)
+
+ val (nativeTable, jvmTable) = ("required_primitive_native",
"required_primitive_jvm")
+ val tables = Seq(nativeTable, jvmTable)
+ tables.foreach { table =>
+ sql(s"""CREATE TABLE $catalog.$ns.$table (id INT NOT NULL,
$columns)
+ |USING iceberg PARTITIONED BY (days(ts))
+ |TBLPROPERTIES ('write.spark.fanout.enabled'='false')
+ |""".stripMargin)
+ sql(s"ALTER TABLE $catalog.$ns.$table WRITE ORDERED BY id")
+ }
+ def append(table: String): Unit =
+ input.writeTo(s"$catalog.$ns.$table").option("distribution-mode",
"none").append()
+
+ val native = withNativeEnabled {
captureWrite(nativeTable)(append(nativeTable)) }
+ assert(native.snapshotDelta == 1)
+ assertSparkRequiredWrite(native.plans)
+
+ val jvm = captureWrite(jvmTable)(append(jvmTable))
+ assertExactlyOneCommit(jvm)
+ val (_, javaWriters) = collectIcebergWriteOps(jvm.plans)
+ assert(javaWriters.forall(hasRequiredProjection),
jvm.plans.mkString("\n"))
+ assert(jvm.plans.forall(p =>
+ collectWithSubqueries(p) { case w: CometIcebergWriteExec => w
}.isEmpty))
+
+ def partitionSummaries(table: String): Seq[Row] = spark
+ .sql(s"SELECT partition_summaries FROM
$catalog.$ns.$table.manifests")
+ .collect()
+ .flatMap(_.getSeq[Row](0))
+ .toSeq
+
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ tables.foreach { table =>
+ val rows = sql(s"SELECT * FROM $catalog.$ns.$table ORDER BY
id").collect()
+ assert(rows.length == expectedRows.length, table)
+ rows.zip(expectedRows).foreach { case (actual, expected) =>
+ assert(actual.toSeq.take(4) == expected.toSeq.take(4),
s"$table: $actual")
+ val (f, expectedF) = (actual.getFloat(4), expected.getFloat(4))
+ val (d, expectedD) = (actual.getDouble(5),
expected.getDouble(5))
+ val floatMatches =
+ if (expectedF.isNaN) f.isNaN
+ else floatToRawIntBits(f) == floatToRawIntBits(expectedF)
+ val doubleMatches =
+ if (expectedD.isNaN) d.isNaN
+ else doubleToRawLongBits(d) == doubleToRawLongBits(expectedD)
+ assert(floatMatches && doubleMatches, s"$table: $actual")
+ }
+
+ assert(
+ partitionDirs(warehouseDir, table) == Set(
+ "ts_day=1969-12-31",
+ "ts_day=1970-01-01",
+ "ts_day=1970-01-02"))
+ val partitions = sql(s"""SELECT partition.ts_day, record_count
+ |FROM $catalog.$ns.$table.files ORDER BY
partition.ts_day""".stripMargin)
+ .collect()
+ .toSeq
+ assert(
+ partitions == Seq(
+ Row(Date.valueOf("1969-12-31"), 1L),
+ Row(Date.valueOf("1970-01-01"), 2L),
+ Row(Date.valueOf("1970-01-02"), 1L)),
+ s"$table: $partitions")
+ }
+ val summaries = partitionSummaries(nativeTable)
+ assert(summaries == partitionSummaries(jvmTable), s"native
summaries: $summaries")
+ assert(summaries.size == 1, s"native summaries: $summaries")
+ val summary = summaries.head
+ assert(!summary.getAs[Boolean]("contains_null"))
+ assert(summary.getAs[String]("lower_bound") == "1969-12-31")
+ assert(summary.getAs[String]("upper_bound") == "1970-01-02")
+ }
+ }
+ }
+ }
+ }
+
+ Seq(false, true).foreach { laterNull =>
+ test(
+ "native Iceberg writer: fixed-length validation preserves the first
error, " +
+ s"laterNull=$laterNull") {
+ assume(icebergAvailable)
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ CometConf.COMET_BATCH_SIZE.key -> "8") {
+ withIcebergCatalog { _ =>
+ withTempPath { path =>
+ val schema = StructType(
+ Seq(
+ StructField("id", IntegerType, nullable = true),
+ StructField("fx", BinaryType, nullable = true)))
+ val invalidRows = Seq(Row(1, Array[Byte](1, 2, 3))) ++
+ (if (laterNull) Seq(Row(null, Array[Byte](5, 6, 7, 8))) else
Seq.empty)
+ val invalidPath = new File(path, "invalid").toString
+ val validPath = new File(path, "valid").toString
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ spark
+ .createDataFrame(spark.sparkContext.parallelize(invalidRows,
1), schema)
+ .write
+ .parquet(invalidPath)
+ spark
+ .createDataFrame(
+ spark.sparkContext.parallelize(
+ Seq(Row(1, Array[Byte](1, 2, 3, 4)), Row(2, Array[Byte](5,
6, 7, 8))),
+ 1),
+ schema)
+ .write
+ .parquet(validPath)
+ val expectedInput = Seq(Row(1, "010203")) ++
+ (if (laterNull) Seq(Row(null, "05060708")) else Seq.empty)
+ assert(
+ spark.read.parquet(invalidPath).selectExpr("id",
"hex(fx)").collect().toSeq ==
+ expectedInput)
+ }
+ val candidate = s"required_fixed_native_$laterNull"
+ val reference = s"required_fixed_jvm_$laterNull"
+ val nativeControl = s"required_fixed_control_native_$laterNull"
+ val jvmControl = s"required_fixed_control_jvm_$laterNull"
Review Comment:
Could we lift `assertJvmRequiredWrite` and the repeated error-parity plus
cleanup checks into shared suite helpers? That block repeats four times across
the new tests.
##########
spark/src/main/scala/org/apache/spark/sql/comet/CometSparkToColumnarExec.scala:
##########
@@ -129,7 +132,75 @@ case class CometSparkToColumnarExec(child: SparkPlan,
batchSize: Option[Int] = N
}
-object CometSparkToColumnarExec extends CometSink[SparkPlan] with
DataTypeSupport {
+object CometSparkToColumnarExec
+ extends CometSink[SparkPlan]
+ with DataTypeSupport
+ with CometTypeShim {
+
+ /**
+ * Whether the Iceberg writer may convert this Spark row subtree to Arrow.
Native import
+ * normalizes invalid UTF-8, while Spark rows can retain those bytes. A new
conversion is safe
+ * only when its string outputs preserve already valid strings or contain
validated literals.
+ */
+ def isRowConversionSupported(plan: SparkPlan, fallbackReasons:
ListBuffer[String]): Boolean = {
+ if (!isSchemaSupported(plan.schema, fallbackReasons)) {
+ false
+ } else if (hasValidStrings(plan)) {
+ true
+ } else {
+ fallbackReasons += "Iceberg writer row conversion cannot prove that
string outputs contain " +
+ "valid UTF-8; native Arrow import could change their bytes"
+ false
+ }
+ }
+
+ private def containsString(dt: DataType): Boolean =
+ dt.existsRecursively(_.isInstanceOf[StringType])
+
+ private def hasValidStrings(plan: SparkPlan): Boolean = {
+ if (!containsString(plan.schema)) {
+ true
+ } else {
+ plan match {
+ // These planning placeholders disappear without running a native
import.
+ case CometScanWrapper(_, source) => hasValidStrings(source)
Review Comment:
Every `CometSinkPlaceHolder` wraps a non-`CometNativeExec` node, so this
falls through to `false` for `CometCoalesceExec`, `CometUnionExec`, and native
`CometShuffleExchangeExec` on string tables. Could we handle those here and
drop the dead placeholder cases in `hasMaterializedRowInput`?
--
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]