JingsongLi commented on code in PR #11190:
URL: https://github.com/apache/paimon/pull/11190#discussion_r4584356057


##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonTableAsSelectWrite.scala:
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.paimon.spark
+
+import org.apache.paimon.spark.write.PaimonWriteRequirement
+import org.apache.paimon.table.FileStoreTable
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.plans.logical.{AppendData, LogicalPlan}
+import org.apache.spark.sql.connector.catalog.{Identifier, StagedTable, Table, 
TableCatalog}
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.paimon.shims.SparkShimLoader
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+import scala.collection.JavaConverters._
+import scala.util.control.NonFatal
+
+/** Routes Spark 3.2-3.4 table-as-select writes through the normal write 
planning rules. */
+object PaimonTableAsSelectWrite {
+
+  def supports(table: Table): Boolean = table match {
+    case target: SparkTable => target.useV2Write
+    case staged: RollbackStagedTable => supports(staged.wrappedTable())
+    case _ => false
+  }
+
+  def write(
+      spark: SparkSession,
+      catalog: TableCatalog,
+      table: Table,
+      ident: Identifier,
+      query: LogicalPlan,
+      options: CaseInsensitiveStringMap): Seq[InternalRow] = {
+    try {
+      // A staged table delegates its writer but is not a SparkTable relation, 
so PaimonAnalysis
+      // cannot add the legacy bucket distribution for it. Prepare that query 
here instead.
+      val writeQuery = table match {
+        case staged: RollbackStagedTable =>
+          staged.wrappedTable() match {
+            case target: SparkTable if target.useV2Write =>
+              PaimonWriteRequirement.prepareQuery(
+                target.getTable.asInstanceOf[FileStoreTable],
+                query)
+            case _ => query
+          }
+        case _ => query
+      }
+      val relation = DataSourceV2Relation.create(table, Some(catalog), 
Some(ident))
+      val command =
+        AppendData.byPosition(relation, writeQuery, 
options.asCaseSensitiveMap().asScala.toMap)
+      SparkShimLoader.shim.classicApi.createDataset(spark, command).collect()
+      table match {
+        case staged: StagedTable => staged.commitStagedChanges()
+        case _ =>
+      }
+      Nil
+    } catch {
+      case NonFatal(error) =>

Review Comment:
   [P2] Run CTAS failure cleanup when the driver is interrupted
   
   Scala NonFatal excludes InterruptedException, so this skips both dropTable 
and abortStagedChanges when the driver thread is interrupted after table 
creation. On this exact head with Spark 3.4.4/JDK 8, a real CTAS 
driver-interruption probe propagates the original InterruptedException for both 
routes: the V1 control removes the created table, while V2 leaves it 
registered. The assertion checks the exception before any cancelJobGroup 
cleanup, so this is not a task failure wrapped in SparkException. A retry then 
encounters the leftover table. Preserve Spark's native abort/drop behavior on 
interruption as well as ordinary exceptions, while propagating the original 
interruption. This helper is used by the new Spark 3.2–3.4 table-as-select 
path; runtime verification here is on 3.4.



##########
paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/write/PaimonWriteRequirement.scala:
##########
@@ -21,23 +21,61 @@ package org.apache.paimon.spark.write
 import org.apache.paimon.CoreOptions
 import org.apache.paimon.CoreOptions.PartitionSinkStrategy
 import org.apache.paimon.spark.commands.BucketExpression.quote
+import org.apache.paimon.spark.commands.FixedBucketExpression
 import org.apache.paimon.table.{FileStoreTable, FormatTable}
 import org.apache.paimon.table.BucketMode._
 
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import org.apache.spark.sql.catalyst.expressions.{Expression => 
CatalystExpression, Literal => CatalystLiteral}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, 
RepartitionByExpression}
 import org.apache.spark.sql.connector.distributions.{ClusteredDistribution, 
Distribution, Distributions}
-import org.apache.spark.sql.connector.expressions.{Expression, Expressions, 
SortOrder}
+import org.apache.spark.sql.connector.expressions.{Expression, Expressions, 
Literal, NamedReference, SortOrder, Transform}
 
 import scala.collection.JavaConverters._
 
 /** Distribution requirements of Spark write. */
 case class PaimonWriteRequirement(distribution: Distribution, ordering: 
Array[SortOrder])
 
-object PaimonWriteRequirement {
+object PaimonWriteRequirement extends SQLConfHelper {
 
   private val EMPTY_ORDERING: Array[SortOrder] = Array.empty
   private val EMPTY: PaimonWriteRequirement =
     PaimonWriteRequirement(Distributions.unspecified(), EMPTY_ORDERING)
 
+  // Spark 3.2/3.3 do not pass the FunctionCatalog when preparing V2 write 
distributions.
+  // Bind the same distribution with Paimon's bucket expression before Spark 
prepares the write.
+  private[spark] def requiresQueryPreparation: Boolean = 
org.apache.spark.SPARK_VERSION < "3.4"
+
+  def prepareQuery(table: FileStoreTable, query: LogicalPlan): LogicalPlan = {
+    if (!requiresQueryPreparation) {
+      return query
+    }
+
+    def bind(expression: Expression): CatalystExpression = expression match {
+      case reference: NamedReference =>
+        query.output.find(a => conf.resolver(a.name, 
reference.fieldNames().head)).get
+      case literal: Literal[_] => CatalystLiteral(literal.value(), 
literal.dataType())
+      case transform: Transform if transform.name() == "identity" =>
+        bind(transform.arguments().head)
+      case transform: Transform if transform.name() == "bucket" =>
+        FixedBucketExpression(
+          CatalystLiteral(table.coreOptions().bucketFunctionType().toString) +:
+            transform.arguments().map(bind).toSeq)
+      case other =>
+        throw new UnsupportedOperationException(s"Unsupported write 
distribution: $other")
+    }
+
+    apply(table).distribution match {
+      case clustered: ClusteredDistribution =>
+        // This Int overload is binary-compatible across Spark 3.2+.
+        RepartitionByExpression(
+          clustered.clustering().map(bind).toSeq,
+          query,
+          conf.numShufflePartitions)

Review Comment:
   [P2] Keep adaptive coalescing available for legacy V2 writes
   
   Passing an explicit partition count creates a REPARTITION_BY_NUM exchange on 
Spark 3.2/3.3; their CoalesceShufflePartitions rule does not coalesce that 
origin. The previous V1 repartition(columns) path remains adaptive. On this 
exact head with Spark 3.2.4/JDK 8, a real one-bucket write of 40 rows from four 
input partitions, with AQE/coalescing enabled and shuffle.partitions=200, 
submits stages [4,1] through V1 versus [4,200] through V2. Both read back the 
same 40 rows and one actual data file. The newly default-enabled V2 route 
therefore schedules 199 unnecessary write tasks for this small single-bucket 
input. Construct an unspecified-count repartition through the version-specific 
adapter rather than freezing conf.numShufflePartitions, and cover actual AQE 
stage counts.



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

Reply via email to