Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/generated/spark_connector_configuration.html
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@
<td>Boolean</td>
<td>Only effective when 'write.merge-schema' is true. If true, widen an existing column type when the incoming data has a wider compatible type (e.g. INT -&gt; BIGINT, DECIMAL precision increase). Lossy changes are still rejected unless 'write.merge-schema.explicit-cast' is also true.</td>
</tr>
<tr>
<td><h5>write.parallelism</h5></td>
<td style="word-wrap: break-word;">(none)</td>
<td>Integer</td>
<td>For fixed-bucket tables, a positive value sets the number of shuffle partitions for the write. If the option is unset, zero, or negative, Spark determines the write shuffle parallelism for each statement using its usual planning rules. Supports table, session and DataSource write options with the standard option precedence.</td>
</tr>
<tr>
<td><h5>write.use-v2-write</h5></td>
<td style="word-wrap: break-word;">true</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ import org.apache.spark.sql.types.DataType

object Compatibility {

def repartitionByExpression(expressions: Seq[Expression], query: LogicalPlan): LogicalPlan = {
RepartitionByExpression(expressions, query, None)
def repartitionByExpression(
expressions: Seq[Expression],
query: LogicalPlan,
numPartitions: Option[Int]): LogicalPlan = {
RepartitionByExpression(expressions, query, numPartitions)
}

def resolveTableOutputColumns(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ import org.apache.spark.sql.types.DataType

object Compatibility {

def repartitionByExpression(expressions: Seq[Expression], query: LogicalPlan): LogicalPlan = {
RepartitionByExpression(expressions, query, None)
def repartitionByExpression(
expressions: Seq[Expression],
query: LogicalPlan,
numPartitions: Option[Int]): LogicalPlan = {
RepartitionByExpression(expressions, query, numPartitions)
}

def resolveTableOutputColumns(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ import org.apache.spark.sql.types.DataType

object Compatibility {

def repartitionByExpression(expressions: Seq[Expression], query: LogicalPlan): LogicalPlan = {
RepartitionByExpression(expressions, query, None)
def repartitionByExpression(
expressions: Seq[Expression],
query: LogicalPlan,
numPartitions: Option[Int]): LogicalPlan = {
RepartitionByExpression(expressions, query, numPartitions)
}

def resolveTableOutputColumns(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ public class SparkConnectorOptions {
+ "If true, also allow lossy type changes between compatible types "
+ "(e.g. BIGINT -> INT, STRING -> DATE).");

public static final ConfigOption<Integer> WRITE_PARALLELISM =
key("write.parallelism")
.intType()
.noDefaultValue()
.withDescription(
"For fixed-bucket tables, a positive value sets the number of shuffle partitions for the write. "
+ "If the option is unset, zero, or negative, Spark determines the write shuffle "
+ "parallelism for each statement using its usual planning rules. "
+ "Supports table, session and DataSource write options with the standard option precedence.");

public static final ConfigOption<Boolean> USE_V2_WRITE =
key("write.use-v2-write")
.booleanType()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,25 +224,34 @@ abstract class PaimonSparkTableBase(val table: Table)

object PaimonSparkTableBase {

/** Bind the operation's switch before Spark selects write capabilities and a writer. */
/** Bind the operation's write options before Spark plans the write. */
def withWriteOptions(
table: SparkCatalogTable,
options: JMap[String, String]): SparkCatalogTable = {
val key = SparkConnectorOptions.USE_V2_WRITE.key()
Option(new CaseInsensitiveStringMap(options).get(key)) match {
case Some(value) =>
table match {
case target: SparkTable if target.getTable.options().get(key) != value =>
SparkTable.of(target.getTable.copy(Collections.singletonMap(key, value)))
case staged: RollbackStagedTable =>
val updated = withWriteOptions(staged.wrappedTable(), options)
if (updated ne staged.wrappedTable()) {
staged.replaceWrappedTable(updated)
}
staged
case _ => table
if (options.isEmpty) return table

table match {
case target: SparkTable =>
val writeOptions = new CaseInsensitiveStringMap(options)
val overrides = new JHashMap[String, String]()
val keys =
Seq(
SparkConnectorOptions.USE_V2_WRITE.key(),
SparkConnectorOptions.WRITE_PARALLELISM.key())
for (key <- keys) {
val value = writeOptions.get(key)
if (value != null && value != target.getTable.options().get(key)) {
overrides.put(key, value)
}
}
if (overrides.isEmpty) target else SparkTable.of(target.getTable.copy(overrides))
case staged: RollbackStagedTable =>
val updated = withWriteOptions(staged.wrappedTable(), options)
if (updated ne staged.wrappedTable()) {
staged.replaceWrappedTable(updated)
}
case None => table
staged
case _ => table
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ import org.apache.spark.sql.types.DataType

object Compatibility {

def repartitionByExpression(expressions: Seq[Expression], query: LogicalPlan): LogicalPlan = {
RepartitionByExpression(expressions, query, None)
def repartitionByExpression(
expressions: Seq[Expression],
query: LogicalPlan,
numPartitions: Option[Int]): LogicalPlan = {
RepartitionByExpression(expressions, query, numPartitions)
}

def resolveTableOutputColumns(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import org.apache.paimon.index.{BucketAssigner, SimpleHashBucketAssigner}
import org.apache.paimon.io.{CompactIncrement, DataIncrement}
import org.apache.paimon.manifest.FileKind
import org.apache.paimon.spark.{SparkPostponeStagedCommitter, SparkRow}
import org.apache.paimon.spark.SparkConnectorOptions.WRITE_PARALLELISM
import org.apache.paimon.spark.catalog.functions.BucketFunction
import org.apache.paimon.spark.metric.SparkMetricRegistry
import org.apache.paimon.spark.schema.SparkSystemColumns.{BUCKET_COL, ROW_KIND_COL}
Expand Down Expand Up @@ -217,11 +218,15 @@ case class PaimonSparkWriter(
}
}

def writeWithBucketProcessor(dataFrame: DataFrame, processor: BucketProcessor[Row]) = {
def writeWithBucketProcessor(
dataFrame: DataFrame,
processor: BucketProcessor[Row],
parallelism: Option[Integer] = None) = {
val repartitioned = repartitionByPartitionsAndBucket(
dataFrame
.mapPartitions(processor.processPartition)(encoderGroupWithBucketCol.encoder)
.toDF())
.toDF(),
parallelism)
writeWithBucket(repartitioned)
}

Expand Down Expand Up @@ -356,6 +361,7 @@ case class PaimonSparkWriter(
writeWithoutBucket(input)

case HASH_FIXED =>
val writeParallelism = Option(coreOptions.toConfiguration.get(WRITE_PARALLELISM))
if (
paimonExtensionEnabled(sparkSession) &&
!coreOptions.bucketFunctionProvider().isPresent && BucketFunction.supportsTable(table)
Expand All @@ -373,13 +379,15 @@ case class PaimonSparkWriter(
lit(bucketNumber)) ++ bucketKeyCol
val repartitioned =
repartitionByPartitionsAndBucket(
data.withColumn(BUCKET_COL, call_udf(BucketExpression.FIXED_BUCKET, args: _*)))
data.withColumn(BUCKET_COL, call_udf(BucketExpression.FIXED_BUCKET, args: _*)),
writeParallelism)
writeWithBucket(repartitioned)
} else {
// Topology: input -> bucket-assigner -> shuffle by partition & bucket
writeWithBucketProcessor(
withInitBucketCol,
CommonBucketProcessor(table, bucketColIdx, encoderGroupWithBucketCol))
CommonBucketProcessor(table, bucketColIdx, encoderGroupWithBucketCol),
writeParallelism)
}

case _ =>
Expand Down Expand Up @@ -578,8 +586,14 @@ case class PaimonSparkWriter(
)
}

private def repartitionByPartitionsAndBucket(df: DataFrame): DataFrame = {
df.repartition(partitionCols(df) ++ Seq(col(BUCKET_COL)): _*)
private def repartitionByPartitionsAndBucket(
df: DataFrame,
parallelism: Option[Integer] = None): DataFrame = {
val columns = partitionCols(df) :+ col(BUCKET_COL)
parallelism match {
case Some(n) if n > 0 => df.repartition(n, columns: _*)
case _ => df.repartition(columns: _*)
}
}

def partitionCols(df: DataFrame): Seq[Column] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ object OptionUtils extends SQLConfHelper with Logging {
.toBoolean
}

def writeParallelism(options: CoreOptions): Option[Int] = {
Option(options.toConfiguration.get(SparkConnectorOptions.WRITE_PARALLELISM))
.map(_.intValue())
.filter(_ > 0)
}

def writeMergeSchemaEnabled(): Boolean = {
getOptionString(SparkConnectorOptions.MERGE_SCHEMA).toBoolean
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import org.apache.paimon.options.Options
import org.apache.paimon.spark._
import org.apache.paimon.spark.commands.SchemaEvolutionHelper
import org.apache.paimon.spark.rowops.PaimonCopyOnWriteScan
import org.apache.paimon.table.BucketMode.BUCKET_UNAWARE
import org.apache.paimon.spark.util.OptionUtils.writeParallelism
import org.apache.paimon.table.BucketMode.{BUCKET_UNAWARE, HASH_FIXED}
import org.apache.paimon.table.FileStoreTable

import org.apache.spark.internal.Logging
Expand Down Expand Up @@ -61,6 +62,14 @@ class PaimonV2Write(
distribution
}

override def requiredNumPartitions(): Int = {
if (!PaimonWriteRequirement.requiresQueryPreparation && table.bucketMode() == HASH_FIXED) {
writeParallelism(coreOptions).getOrElse(0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Make the scope of per-write parallelism explicit

On Spark 4.0.5 with AQE enabled, an existing fixed-bucket table with write.parallelism=7 writes with seven tasks even when df.writeTo(table).option("write.parallelism", "3").append() requests three, or "0" requests Spark's adaptive default. The physical plan confirms AppendDataExec. V1 saveAsTable append has the same behavior. This makes it easy for a job to appear to set its own task count while still using the table's value. Please either bind the operation option ahead of the table/session value in both paths, preserving zero as an explicit fallback, or document that this setting is supported only as a table or session property.

@fengruotj fengruotj Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JingsongLi Thanks for reviewing!I agreed. I updated both V2 writeTo(...).append() and V1 saveAsTable append to honor the per-write write.parallelism option for fixed-bucket tables. I added regression tests for both paths. With the table set to 7, an explicit 3 produces three write tasks. An explicit 0 lets AQE choose the task count even with the session set to 5.

} else {
0
}
}

override def requiredOrdering(): Array[SortOrder] = {
val ordering = writeRequirement.ordering
logInfo(s"Requesting ${ordering.mkString(",")} as write ordering for table ${table.name()}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import org.apache.paimon.CoreOptions.PartitionSinkStrategy
import org.apache.paimon.spark.catalyst.Compatibility
import org.apache.paimon.spark.commands.BucketExpression.quote
import org.apache.paimon.spark.commands.FixedBucketExpression
import org.apache.paimon.spark.util.OptionUtils.writeParallelism
import org.apache.paimon.table.{FileStoreTable, FormatTable}
import org.apache.paimon.table.BucketMode._

Expand Down Expand Up @@ -68,8 +69,16 @@ object PaimonWriteRequirement extends SQLConfHelper {

apply(table).distribution match {
case clustered: ClusteredDistribution =>
val numPartitions = if (table.bucketMode() == HASH_FIXED) {
writeParallelism(table.coreOptions())
} else {
None
}
// Leave the count unspecified so AQE can coalesce the bucket shuffle on Spark 3.2/3.3.
Compatibility.repartitionByExpression(clustered.clustering().map(bind).toSeq, query)
Compatibility.repartitionByExpression(
clustered.clustering().map(bind).toSeq,
query,
numPartitions)
case _ => query
}
}
Expand Down
Loading
Loading