This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new ada9ada5e1 [flink] Support stripe write for fixed bucket (#11015)
ada9ada5e1 is described below
commit ada9ada5e1e325bde3b1016e31492e4db73d99c5
Author: yunfengzhou-hub <[email protected]>
AuthorDate: Tue Nov 17 23:29:47 2026 +0800
[flink] Support stripe write for fixed bucket (#11015)
---
docs/docs/flink/sql-write.mdx | 46 ++
docs/generated/flink_connector_configuration.html | 12 +
.../main/java/org/apache/paimon/CoreOptions.java | 13 +
.../java/org/apache/paimon/KeyValueFileStore.java | 8 +-
.../apache/paimon/flink/FlinkConnectorOptions.java | 18 +
.../apache/paimon/flink/sink/FlinkSinkBuilder.java | 66 +++
.../paimon/flink/sink/RowDataChannelComputer.java | 4 +-
.../sink/StripedBucketWriteChannelComputer.java | 181 ++++++++
.../StripedBucketWriteChannelComputerTest.java | 480 +++++++++++++++++++++
.../sink/StripedBucketWriteSavepointITCase.java | 194 +++++++++
.../flink/sink/StripedBucketWriteSinkITCase.java | 404 +++++++++++++++++
11 files changed, 1417 insertions(+), 9 deletions(-)
diff --git a/docs/docs/flink/sql-write.mdx b/docs/docs/flink/sql-write.mdx
index ba173adef5..36c989d1bd 100644
--- a/docs/docs/flink/sql-write.mdx
+++ b/docs/docs/flink/sql-write.mdx
@@ -146,6 +146,52 @@ keys remain supported aliases. To reduce sampling or
sorting work, tune
See [Append-table Query Performance](../append-table/query-performance) and
[FlinkConnectorOptions](../maintenance/configurations#flinkconnectoroptions)
for tuning details.
+### Write Parallelism Beyond Bucket Count
+
+For a fixed-bucket table, the sink shuffles records by bucket, so each bucket
is written by a single
+writer subtask. When the bucket count is small, this limits write parallelism
and leaves writer
+subtasks idle.
+
+When the bucket count cannot be changed easily,
`sink.striped-bucket-write.enabled` lets a
+fixed-bucket table stripe each bucket's writes across multiple writer
subtasks, improving write
+throughput and resource utilization without rescaling the table:
+
+| Option | Effect |
+| --- | --- |
+| `sink.striped-bucket-write.enabled` | Stripe each bucket's writes across
multiple writer subtasks to raise write parallelism beyond the bucket count |
+| `sink.striped-bucket-write.writers-per-bucket` | Number of writer subtasks
per bucket; the writer parallelism becomes this number times the bucket count.
Set to -1 to let every writer subtask write every bucket. Only takes effect
when enabled |
+
+For a primary-key table, records that share a primary key still land on the
same writer, so each
+writer produces sorted runs over a hash-partitioned subset of the bucket's
keys. For an append-only
+table, records are distributed round-robin across the bucket's writers.
+
+:::warning Requirements and costs
+
+Striped write requires `write-only = true` together with a
+[dedicated compaction job](../maintenance/dedicated-compaction): multiple
writers per bucket cannot
+run inline compaction without conflicting commits.
+
+Striped write does not support `deletion-vectors.enabled`: each writer would
maintain a conflicting
+deletion-vector index for the same bucket.
+
+Striped write of an append-only table requires `bucket-append-ordered =
false`. Striping spreads
+successive rows across independent writers whose files are read whole, so it
cannot preserve the
+append order within a bucket that ordered reads rely on.
+
+These misconfigurations are rejected when the sink is built.
+
+Compaction still merges each bucket as a single task, now handling
proportionally more sorted runs.
+Striped write trades extra compaction work and more small files for higher
write parallelism; it does not
+raise compaction parallelism, which stays bounded by the bucket count. Prefer
increasing the bucket
+count when a [rescale](../maintenance/rescale-bucket) is acceptable.
+
+You can change the writer parallelism or the number of writers per bucket when
restoring from a
+savepoint. A striped writer is write-only and keeps no per-bucket state in the
savepoint: records are
+committed at the checkpoint barrier and each writer rebuilds from the table on
restore, so committed
+rows survive the rescale.
+
+:::
+
## Overwriting the Whole Table
Use `INSERT OVERWRITE` to replace the contents of an unpartitioned table. For
example, continuing
diff --git a/docs/generated/flink_connector_configuration.html
b/docs/generated/flink_connector_configuration.html
index 6cc457a264..43dd354534 100644
--- a/docs/generated/flink_connector_configuration.html
+++ b/docs/generated/flink_connector_configuration.html
@@ -248,6 +248,18 @@ under the License.
<td>Duration</td>
<td>If no records flow in a partition of a stream for that amount
of time, then that partition is considered "idle" and will not hold back the
progress of watermarks in downstream operators.</td>
</tr>
+ <tr>
+ <td><h5>sink.striped-bucket-write.enabled</h5></td>
+ <td style="word-wrap: break-word;">false</td>
+ <td>Boolean</td>
+ <td>If true, a fixed-bucket table stripes each bucket's writes
across multiple writer subtasks so that write parallelism can exceed the bucket
count without rescaling the table.</td>
+ </tr>
+ <tr>
+ <td><h5>sink.striped-bucket-write.writers-per-bucket</h5></td>
+ <td style="word-wrap: break-word;">(none)</td>
+ <td>Integer</td>
+ <td>Sets how many writer subtasks write each bucket. Set to -1 to
let every writer subtask write every bucket. Only takes effect when
'sink.striped-bucket-write.enabled' is true.</td>
+ </tr>
<tr>
<td><h5>sink.clustering.sample-factor</h5></td>
<td style="word-wrap: break-word;">100</td>
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
index 3886267fce..a1a0abefed 100644
--- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
+++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
@@ -5174,6 +5174,19 @@ public class CoreOptions implements Serializable {
return !fmIndexColumns().isEmpty();
}
+ /**
+ * Whether any source-backed primary-key index (vector, full-text, FM,
BTree, bitmap,
+ * multivalue) is configured.
+ */
+ public boolean primaryKeyIndexEnabled() {
+ return !VectorIndexOptions.columns(options).isEmpty()
+ || fullTextIndexEnabled()
+ || fmIndexEnabled()
+ || !btreeIndexColumns().isEmpty()
+ || !bitmapIndexColumns().isEmpty()
+ || !multiValueIndexColumns().isEmpty();
+ }
+
public List<String> btreeIndexColumns() {
return globalIndexColumns("btree");
}
diff --git a/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
b/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
index 462b0ba162..9af01f35be 100644
--- a/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
+++ b/paimon-core/src/main/java/org/apache/paimon/KeyValueFileStore.java
@@ -34,7 +34,6 @@ import org.apache.paimon.operation.KeyValueFileStoreWrite;
import org.apache.paimon.operation.MergeFileSplitRead;
import org.apache.paimon.operation.RawFileSplitRead;
import org.apache.paimon.options.Options;
-import org.apache.paimon.options.VectorIndexOptions;
import org.apache.paimon.postpone.PostponeBucketFileStoreWrite;
import org.apache.paimon.schema.KeyValueFieldsExtractor;
import org.apache.paimon.schema.SchemaManager;
@@ -189,12 +188,7 @@ public class KeyValueFileStore extends
AbstractFileStore<KeyValue> {
dvMaintainerFactory =
BucketedDvMaintainer.factory(newIndexFileHandler());
}
BucketedPrimaryKeyIndexMaintainer.Factory
primaryKeyIndexMaintainerFactory = null;
- if
(!VectorIndexOptions.columns(writeOptions.toConfiguration()).isEmpty()
- || writeOptions.fullTextIndexEnabled()
- || writeOptions.fmIndexEnabled()
- || !writeOptions.btreeIndexColumns().isEmpty()
- || !writeOptions.bitmapIndexColumns().isEmpty()
- || !writeOptions.multiValueIndexColumns().isEmpty()) {
+ if (writeOptions.primaryKeyIndexEnabled()) {
primaryKeyIndexMaintainerFactory =
BucketedPrimaryKeyIndexMaintainer.Factory.create(
newIndexFileHandler(), newReaderFactoryBuilder(),
schema);
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkConnectorOptions.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkConnectorOptions.java
index ae1486be08..6c4a541846 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkConnectorOptions.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/FlinkConnectorOptions.java
@@ -84,6 +84,24 @@ public class FlinkConnectorOptions {
+ "This eliminates data transfer overhead
when the source already "
+ "provides suitable data distribution
(e.g., Kafka partitions).");
+ public static final ConfigOption<Boolean>
SINK_STRIPED_BUCKET_WRITE_ENABLED =
+ ConfigOptions.key("sink.striped-bucket-write.enabled")
+ .booleanType()
+ .defaultValue(false)
+ .withDescription(
+ "If true, a fixed-bucket table stripes each
bucket's writes across multiple "
+ + "writer subtasks so that write
parallelism can exceed the bucket count "
+ + "without rescaling the table.");
+
+ public static final ConfigOption<Integer>
SINK_STRIPED_BUCKET_WRITE_WRITERS_PER_BUCKET =
+ ConfigOptions.key("sink.striped-bucket-write.writers-per-bucket")
+ .intType()
+ .noDefaultValue()
+ .withDescription(
+ "Sets how many writer subtasks write each bucket.
Set to -1 to let every "
+ + "writer subtask write every bucket. Only
takes effect when "
+ + "'sink.striped-bucket-write.enabled' is
true.");
+
public static final ConfigOption<CompactionBucketDistributionStrategy>
COMPACTION_BUCKET_DISTRIBUTION_STRATEGY =
ConfigOptions.key("compaction.bucket-distribution-strategy")
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSinkBuilder.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSinkBuilder.java
index 8bea0b5acf..52b759f15d 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSinkBuilder.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/FlinkSinkBuilder.java
@@ -33,6 +33,7 @@ import
org.apache.paimon.flink.sink.partition.StatisticsOrRecordChannelComputer;
import org.apache.paimon.flink.sink.partition.StatisticsOrRecordTypeInfo;
import org.apache.paimon.flink.sorter.TableSortInfo;
import org.apache.paimon.flink.sorter.TableSorter;
+import org.apache.paimon.options.Options;
import org.apache.paimon.table.BlobDescriptorReaderFactory;
import org.apache.paimon.table.BucketMode;
import org.apache.paimon.table.FileStoreTable;
@@ -62,6 +63,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import static org.apache.paimon.CoreOptions.clusteringStrategy;
@@ -351,6 +353,70 @@ public class FlinkSinkBuilder {
protected DataStreamSink<?> buildForFixedBucket(DataStream<InternalRow>
input) {
int bucketNums = table.bucketSpec().getNumBuckets();
+ Options options = Options.fromMap(table.options());
+ // sink.striped-bucket-write.enabled is the sole switch;
writers-per-bucket only applies
+ // when it is
+ // on
+ if
(options.get(FlinkConnectorOptions.SINK_STRIPED_BUCKET_WRITE_ENABLED)) {
+ checkArgument(
+ !table.coreOptions().deletionVectorsEnabled(),
+ "Striped bucket write does not support
deletion-vectors.enabled: multiple writers "
+ + "per bucket would maintain conflicting
deletion-vector indexes and corrupt "
+ + "reads. Disable deletion vectors or striped
bucket write.");
+ checkArgument(
+ table.coreOptions().writeOnly(),
+ "Striped bucket write requires write-only=true: multiple
writers per bucket cannot "
+ + "run inline compaction without conflicts. Set
write-only=true and run a "
+ + "dedicated compaction job.");
+ checkArgument(
+ !table.schema().primaryKeys().isEmpty()
+ || !table.coreOptions().bucketAppendOrdered(),
+ "Striped bucket write requires bucket-append-ordered=false
for an append-only "
+ + "table: striping spreads successive rows across
independent writers, "
+ + "breaking the append order that ordered reads
rely on. Set "
+ + "bucket-append-ordered=false or disable striped
bucket write.");
+ // Mirrors the primary-key index enablement in
KeyValueFileStore#newFixedBucketWrite:
+ // all of these are maintained per bucket by a single publisher,
so multiple writers
+ // per bucket would each publish a conflicting index for the same
bucket.
+ checkArgument(
+ !table.coreOptions().primaryKeyIndexEnabled(),
+ "Striped bucket write does not support primary-key indexes
(vector, full-text, "
+ + "FM, BTree, bitmap, multivalue): each writer
would maintain and publish "
+ + "a conflicting index for the same bucket. Remove
the primary-key "
+ + "indexes or disable striped bucket write.");
+ Optional<Integer> configuredWritersPerBucket =
+ options.getOptional(
+
FlinkConnectorOptions.SINK_STRIPED_BUCKET_WRITE_WRITERS_PER_BUCKET);
+ checkArgument(
+ !configuredWritersPerBucket.isPresent()
+ || configuredWritersPerBucket.get()
+ ==
StripedBucketWriteChannelComputer.MATCH_PARALLELISM
+ || configuredWritersPerBucket.get() >= 1,
+ "sink.striped-bucket-write.writers-per-bucket must be a
positive integer or -1.");
+ int writersPerBucket =
+
configuredWritersPerBucket.orElse(StripedBucketWriteChannelComputer.AUTO);
+ if (writersPerBucket > 0) {
+ // An explicit writers-per-bucket derives the writer
parallelism instead of capping
+ // it
+ // to bucketNums
+ long derivedParallelism = (long) writersPerBucket * bucketNums;
+ checkArgument(
+ derivedParallelism <= Integer.MAX_VALUE,
+ "sink.striped-bucket-write.writers-per-bucket %s *
bucket count %s overflowed.",
+ writersPerBucket,
+ bucketNums);
+ parallelism = (int) derivedParallelism;
+ }
+ DataStream<InternalRow> partitioned =
+ partition(
+ input,
+ new
StripedBucketWriteChannelComputer(table.schema(), writersPerBucket),
+ parallelism);
+ return configureBlobDescriptorReaderFactory(
+ new FixedBucketSink(table, overwritePartition))
+ .sinkFrom(partitioned);
+ }
+
if (parallelism == null
&& bucketNums < input.getParallelism()
&& table.partitionKeys().isEmpty()) {
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataChannelComputer.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataChannelComputer.java
index 1df93c82bc..6b1037b2c0 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataChannelComputer.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/RowDataChannelComputer.java
@@ -32,8 +32,8 @@ public class RowDataChannelComputer implements
ChannelComputer<InternalRow> {
private final TableSchema schema;
- private transient int numChannels;
- private transient KeyAndBucketExtractor<InternalRow> extractor;
+ protected transient int numChannels;
+ protected transient KeyAndBucketExtractor<InternalRow> extractor;
public RowDataChannelComputer(TableSchema schema) {
this.schema = schema;
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputer.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputer.java
new file mode 100644
index 0000000000..62e3261d2b
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputer.java
@@ -0,0 +1,181 @@
+/*
+ * 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.flink.sink;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.table.sink.ChannelComputer;
+import org.apache.paimon.types.DataTypeRoot;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.MurmurHashUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A {@link RowDataChannelComputer} that stripes each bucket's writes across
multiple writer
+ * channels, so that write parallelism can exceed the bucket count without
rescaling the table.
+ *
+ * <p>Each bucket is routed to several channels. For a primary-key table the
record's primary key
+ * picks the channel, so records sharing a key still land on the same channel;
for an append-only
+ * table records are distributed round-robin across the bucket's channels, so
a bucket fans out even
+ * when its bucket key has low cardinality. A single writer per bucket is
equivalent to {@link
+ * RowDataChannelComputer}.
+ */
+public class StripedBucketWriteChannelComputer extends RowDataChannelComputer {
+
+ private static final long serialVersionUID = 1L;
+
+ /** Derive the number of stripes from the channel count and the bucket
count. */
+ public static final int AUTO = 0;
+
+ /** Route every bucket to all channels, so every writer writes every
bucket. */
+ public static final int MATCH_PARALLELISM = -1;
+
+ private final int writesPerBucket;
+ private final int numBuckets;
+ private final boolean hasPrimaryKey;
+
+ // Positions of FLOAT/DOUBLE fields in the trimmed primary key, whose NaN
payloads must be
+ // canonicalized before hashing so that keys equal under the key
comparator hash alike.
+ private final int[] floatingKeyPositions;
+ private final boolean[] floatingKeyIsDouble;
+
+ private transient int numStripes;
+ // Append-only round-robin progress per bucket. One counter per bucket
(not per partition), so
+ // the state is bounded by the bucket count and a bucket fans out
regardless of key cardinality.
+ private transient int[] stripeCounters;
+
+ public StripedBucketWriteChannelComputer(TableSchema schema, int
writesPerBucket) {
+ super(schema);
+ this.writesPerBucket = writesPerBucket;
+ this.numBuckets = new CoreOptions(schema.options()).bucket();
+ this.hasPrimaryKey = !schema.primaryKeys().isEmpty();
+
+ List<Integer> positions = new ArrayList<>();
+ List<Boolean> isDouble = new ArrayList<>();
+ if (hasPrimaryKey) {
+ RowType keyType = schema.logicalTrimmedPrimaryKeysType();
+ for (int i = 0; i < keyType.getFieldCount(); i++) {
+ DataTypeRoot root = keyType.getTypeAt(i).getTypeRoot();
+ if (root == DataTypeRoot.DOUBLE) {
+ positions.add(i);
+ isDouble.add(true);
+ } else if (root == DataTypeRoot.FLOAT) {
+ positions.add(i);
+ isDouble.add(false);
+ }
+ }
+ }
+ this.floatingKeyPositions = new int[positions.size()];
+ this.floatingKeyIsDouble = new boolean[positions.size()];
+ for (int i = 0; i < positions.size(); i++) {
+ this.floatingKeyPositions[i] = positions.get(i);
+ this.floatingKeyIsDouble[i] = isDouble.get(i);
+ }
+ }
+
+ @Override
+ public void setup(int numChannels) {
+ super.setup(numChannels);
+ this.numStripes = resolveNumStripes();
+ if (!hasPrimaryKey && numStripes > 1) {
+ this.stripeCounters = new int[numBuckets];
+ }
+ }
+
+ private int resolveNumStripes() {
+ if (writesPerBucket > 0) {
+ return writesPerBucket;
+ }
+ if (writesPerBucket == MATCH_PARALLELISM) {
+ return numChannels;
+ }
+ // AUTO: ceil(numChannels / numBuckets), but never less than one
writer per bucket
+ return Math.max(1, (numChannels + numBuckets - 1) / numBuckets);
+ }
+
+ @Override
+ public int channel(InternalRow record) {
+ extractor.setRecord(record);
+ BinaryRow partition = extractor.partition();
+ int bucket = extractor.bucket();
+ int stripe;
+ if (numStripes == 1) {
+ stripe = 0;
+ } else if (hasPrimaryKey) {
+ stripe = keyStripe(extractor.trimmedPrimaryKey());
+ } else {
+ // Round-robin per bucket so a bucket spreads across its writers
even when the bucket
+ // key has low cardinality (a hash of the bucket key would pin all
such rows to one
+ // writer).
+ stripe = Math.floorMod(stripeCounters[bucket]++, numStripes);
+ }
+ // Widen to long so that bucket * numStripes cannot overflow for large
bucket counts
+ long bucketSlot = (long) bucket * numStripes + stripe;
+ // Multi-stripe append omits the partition rotation:
startChannel(partition) would advance
+ // in step with the shared per-bucket counter on interleaved
partitions and cancel the
+ // round-robin. Single-stripe and primary-key routing keep the
rotation.
+ int startChannel =
+ (!hasPrimaryKey && numStripes > 1)
+ ? 0
+ : ChannelComputer.startChannel(partition, numChannels);
+ return (int) ((startChannel + bucketSlot) % numChannels);
+ }
+
+ private int keyStripe(BinaryRow key) {
+ // Avalanche the key hash so the stripe is independent of the bucket
modulo, which also
+ // derives from the key hash; otherwise shared factors between
numStripes and numBuckets
+ // skew it.
+ return Math.floorMod(MurmurHashUtils.fmix(canonicalKeyHash(key)),
numStripes);
+ }
+
+ private int canonicalKeyHash(BinaryRow key) {
+ if (floatingKeyPositions.length == 0) {
+ return key.hashCode();
+ }
+ // The key comparator treats all NaN payloads as equal, but
BinaryRow.hashCode hashes the
+ // raw bits. Canonicalize NaNs on a copy so logically equal keys route
to the same writer
+ // and cannot acquire independent sequence streams; the written record
is left unchanged.
+ BinaryRow normalized = key.copy();
+ for (int i = 0; i < floatingKeyPositions.length; i++) {
+ int pos = floatingKeyPositions[i];
+ if (normalized.isNullAt(pos)) {
+ continue;
+ }
+ if (floatingKeyIsDouble[i]) {
+ if (Double.isNaN(normalized.getDouble(pos))) {
+ normalized.setDouble(pos, Double.NaN);
+ }
+ } else {
+ if (Float.isNaN(normalized.getFloat(pos))) {
+ normalized.setFloat(pos, Float.NaN);
+ }
+ }
+ }
+ return normalized.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "striped bucket shuffle";
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputerTest.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputerTest.java
new file mode 100644
index 0000000000..af1cf99f53
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputerTest.java
@@ -0,0 +1,480 @@
+/*
+ * 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.flink.sink;
+
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.schema.SchemaManager;
+import org.apache.paimon.schema.TableSchema;
+import org.apache.paimon.table.sink.FixedBucketRowKeyExtractor;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.types.RowType;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+import static
org.apache.paimon.flink.sink.StripedBucketWriteChannelComputer.AUTO;
+import static
org.apache.paimon.flink.sink.StripedBucketWriteChannelComputer.MATCH_PARALLELISM;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for {@link StripedBucketWriteChannelComputer}. */
+public class StripedBucketWriteChannelComputerTest {
+
+ @TempDir java.nio.file.Path tempDir;
+
+ @Test
+ public void testSingleWriterPerBucketEqualsRowDataChannelComputer() throws
Exception {
+ TableSchema schema = createNoPartitionSchema(4);
+ List<InternalRow> input = randomRows(2000, 12345L);
+
+ int numChannels = 4;
+ StripedBucketWriteChannelComputer striped =
+ new StripedBucketWriteChannelComputer(schema, 1);
+ striped.setup(numChannels);
+ RowDataChannelComputer base = new RowDataChannelComputer(schema);
+ base.setup(numChannels);
+
+ for (InternalRow row : input) {
+ assertThat(striped.channel(row)).isEqualTo(base.channel(row));
+ }
+ }
+
+ @Test
+ public void testStripedChannelsPerBucket() throws Exception {
+ int numBuckets = 4;
+ int numStripes = 2;
+ int numChannels = numBuckets * numStripes;
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+
+ Map<Integer, Set<Integer>> channelsByBucket =
+ groupByBucket(schema, randomRows(4000, 42L), numStripes,
numChannels);
+ assertThat(channelsByBucket.keySet()).hasSize(numBuckets);
+
+ Set<Integer> allChannels = new HashSet<>();
+ for (int bucket = 0; bucket < numBuckets; bucket++) {
+ Set<Integer> channels = channelsByBucket.get(bucket);
+ // each bucket is striped to exactly numStripes distinct channels
+ assertThat(channels).hasSize(numStripes);
+ // with numChannels = numBuckets * numStripes the per-bucket
channel sets are disjoint
+ // (the partition start-channel only rotates them, it does not
overlap them)
+ for (int channel : channels) {
+ assertThat(allChannels.add(channel)).isTrue();
+ }
+ }
+ // together they cover every channel exactly once
+ assertThat(allChannels).hasSize(numChannels);
+ }
+
+ @Test
+ public void testSameKeyAlwaysSameChannel() throws Exception {
+ TableSchema schema = createNoPartitionSchema(4);
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, 3);
+ computer.setup(12);
+
+ Random random = new Random(7L);
+ for (int i = 0; i < 200; i++) {
+ long key = random.nextInt(50);
+ InternalRow first = GenericRow.of(key, random.nextDouble());
+ int expected = computer.channel(first);
+ // same key, different value -> must route to the same channel
+ for (int repeat = 0; repeat < 5; repeat++) {
+ InternalRow again = GenericRow.of(key, random.nextDouble());
+ assertThat(computer.channel(again)).isEqualTo(expected);
+ }
+ }
+ }
+
+ @Test
+ public void testMatchParallelismCoversAllChannels() throws Exception {
+ int numBuckets = 4;
+ int numChannels = 8;
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+
+ // numStripes = numChannels -> every bucket is written by all channels
+ Map<Integer, Set<Integer>> channelsByBucket =
+ groupByBucket(schema, randomRows(4000, 99L), numChannels,
numChannels);
+ assertStripesPerBucket(channelsByBucket, numBuckets, numChannels);
+ }
+
+ @Test
+ public void testDistributionIsBalanced() throws Exception {
+ int numBuckets = 4;
+ int numStripes = 2;
+ int numChannels = numBuckets * numStripes;
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+ int numRecords = 8000;
+ List<InternalRow> input = randomRows(numRecords, 2026L);
+
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numChannels);
+
+ int[] count = new int[numChannels];
+ for (InternalRow row : input) {
+ count[computer.channel(row)]++;
+ }
+
+ int max = Arrays.stream(count).max().getAsInt();
+ int min = Arrays.stream(count).min().getAsInt();
+ // every channel should receive a fair share; allow 30% deviation from
the mean
+ assertThat(min).isGreaterThan(0);
+ assertThat(max - min).isLessThanOrEqualTo((int) (numRecords / (double)
numChannels * 0.3));
+ }
+
+ @Test
+ public void testAutoStripesResolveFromChannelCount() throws Exception {
+ int numBuckets = 4;
+ int numChannels = 8; // numStripes = ceil(8/4) = 2
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+
+ Map<Integer, Set<Integer>> channelsByBucket =
+ groupByBucket(schema, randomRows(4000, 5L), AUTO, numChannels);
+ assertStripesPerBucket(channelsByBucket, numBuckets, 2);
+ }
+
+ @Test
+ public void testAutoStripesCeilWhenNotDivisible() throws Exception {
+ int numBuckets = 3;
+ int numChannels =
+ 7; // numStripes = ceil(7/3) = 3, stripes*buckets >
numChannels so sets wrap
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+
+ Map<Integer, Set<Integer>> channelsByBucket =
+ groupByBucket(schema, randomRows(6000, 6L), AUTO, numChannels);
+ // each bucket still stripes to exactly 3 distinct channels even when
sets wrap
+ assertStripesPerBucket(channelsByBucket, numBuckets, 3);
+ }
+
+ @Test
+ public void testMatchParallelismResolvesToChannelCount() throws Exception {
+ int numBuckets = 4;
+ int numChannels = 8;
+ TableSchema schema = createNoPartitionSchema(numBuckets);
+
+ Map<Integer, Set<Integer>> channelsByBucket =
+ groupByBucket(schema, randomRows(4000, 7L), MATCH_PARALLELISM,
numChannels);
+ assertStripesPerBucket(channelsByBucket, numBuckets, numChannels);
+ }
+
+ @Test
+ public void testPartitionedTableStripes() throws Exception {
+ int numBuckets = 2;
+ int numStripes = 2;
+ int numChannels = numBuckets * numStripes;
+ TableSchema schema = createPartitionedSchema(numBuckets);
+ List<InternalRow> input = new ArrayList<>();
+ Random random = new Random(11L);
+ for (int i = 0; i < 4000; i++) {
+ input.add(GenericRow.of(random.nextInt(3) + 1, random.nextLong(),
random.nextDouble()));
+ }
+
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numChannels);
+ FixedBucketRowKeyExtractor extractor = new
FixedBucketRowKeyExtractor(schema);
+
+ // each (partition, bucket) pair must still stripe to exactly
numStripes distinct channels
+ Map<String, Set<Integer>> channelsByPartitionBucket = new HashMap<>();
+ for (InternalRow row : input) {
+ extractor.setRecord(row);
+ BinaryRow partition = extractor.partition();
+ int bucket = extractor.bucket();
+ int channel = computer.channel(row);
+ assertThat(channel).isBetween(0, numChannels - 1);
+ channelsByPartitionBucket
+ .computeIfAbsent(partition.hashCode() + ":" + bucket, k ->
new HashSet<>())
+ .add(channel);
+ }
+ for (Set<Integer> channels : channelsByPartitionBucket.values()) {
+ assertThat(channels).hasSize(numStripes);
+ }
+ }
+
+ @Test
+ public void testAppendAlternatingBucketsFanOut() throws Exception {
+ int numBuckets = 2;
+ int numStripes = 2;
+ int numChannels = numBuckets * numStripes;
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.INT()}, new
String[] {"k", "v"});
+ TableSchema schema =
+ createSchema(
+ rowType,
+ Collections.emptyList(),
+ Collections.emptyList(),
+ numBuckets,
+ Collections.singletonMap("bucket-key", "k"));
+
+ // one fixed bucket-key value per bucket: a low-cardinality key must
still fan out
+ FixedBucketRowKeyExtractor extractor = new
FixedBucketRowKeyExtractor(schema);
+ int key0 = -1;
+ int key1 = -1;
+ for (int x = 0; x < 1000 && (key0 < 0 || key1 < 0); x++) {
+ extractor.setRecord(GenericRow.of(x, 0));
+ int bucket = extractor.bucket();
+ if (bucket == 0 && key0 < 0) {
+ key0 = x;
+ } else if (bucket == 1 && key1 < 0) {
+ key1 = x;
+ }
+ }
+ assertThat(key0).isGreaterThanOrEqualTo(0);
+ assertThat(key1).isGreaterThanOrEqualTo(0);
+
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numChannels);
+
+ // alternate the two buckets, each with a single fixed key;
round-robin per bucket must fan
+ // each bucket out to every stripe (a bucket-key hash would pin each
bucket to one writer)
+ Map<Integer, Set<Integer>> channelsByBucket = new HashMap<>();
+ for (int i = 0; i < 2000; i++) {
+ InternalRow row = GenericRow.of(i % 2 == 0 ? key0 : key1, i);
+ extractor.setRecord(row);
+ int bucket = extractor.bucket();
+ int channel = computer.channel(row);
+ assertThat(channel).isBetween(0, numChannels - 1);
+ channelsByBucket.computeIfAbsent(bucket, k -> new
HashSet<>()).add(channel);
+ }
+ assertStripesPerBucket(channelsByBucket, numBuckets, numStripes);
+ }
+
+ @Test
+ public void testEqualNaNKeysRouteToSameChannel() throws Exception {
+ int numBuckets = 2;
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.DOUBLE()},
+ new String[] {"tenant", "k"});
+ TableSchema schema =
+ createSchema(
+ rowType,
+ Collections.emptyList(),
+ Arrays.asList("tenant", "k"),
+ numBuckets,
+ Collections.singletonMap("bucket-key", "tenant"));
+
+ // two quiet-NaN payloads that compare equal as primary keys but
differ in raw bits
+ double nanA = Double.longBitsToDouble(0x7ff8000000000001L);
+ double nanB = Double.longBitsToDouble(0x7ff8000000000003L);
+ assertThat(Double.compare(nanA, nanB)).isEqualTo(0);
+ InternalRow a = GenericRow.of(1, nanA);
+ InternalRow b = GenericRow.of(1, nanB);
+
+ for (int numStripes = 2; numStripes <= 5; numStripes++) {
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numBuckets * numStripes);
+ // equal primary keys must never be split across writers, or they
acquire independent
+ // sequence streams and a stale upsert can win
+ assertThat(computer.channel(a)).isEqualTo(computer.channel(b));
+ }
+ }
+
+ @Test
+ public void testAppendSingleStripeEqualsRowDataChannelComputer() throws
Exception {
+ int numBuckets = 4;
+ int numChannels = 4;
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.INT()}, new
String[] {"k", "v"});
+ TableSchema schema =
+ createSchema(
+ rowType,
+ Collections.emptyList(),
+ Collections.emptyList(),
+ numBuckets,
+ Collections.singletonMap("bucket-key", "k"));
+
+ // a single writer per bucket needs no round-robin state and
degenerates to bucket routing
+ StripedBucketWriteChannelComputer striped =
+ new StripedBucketWriteChannelComputer(schema, 1);
+ striped.setup(numChannels);
+ RowDataChannelComputer base = new RowDataChannelComputer(schema);
+ base.setup(numChannels);
+
+ Random random = new Random(31L);
+ for (int i = 0; i < 2000; i++) {
+ InternalRow row = GenericRow.of(random.nextInt(1000), i);
+ assertThat(striped.channel(row)).isEqualTo(base.channel(row));
+ }
+ }
+
+ @Test
+ public void testPartitionedAppendFanOut() throws Exception {
+ int numBuckets = 2;
+ int numStripes = 2;
+ int numChannels = numBuckets * numStripes;
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.INT(),
DataTypes.INT()},
+ new String[] {"pt", "k", "v"});
+ TableSchema schema =
+ createSchema(
+ rowType,
+ Collections.singletonList("pt"),
+ Collections.emptyList(),
+ numBuckets,
+ Collections.singletonMap("bucket-key", "k"));
+
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numChannels);
+ FixedBucketRowKeyExtractor extractor = new
FixedBucketRowKeyExtractor(schema);
+
+ // round-robin per bucket must fan each bucket out across writers even
with partitions
+ Random random = new Random(77L);
+ Map<Integer, Set<Integer>> channelsByBucket = new HashMap<>();
+ for (int i = 0; i < 6000; i++) {
+ InternalRow row = GenericRow.of(random.nextInt(5),
random.nextInt(1000), i);
+ extractor.setRecord(row);
+ int bucket = extractor.bucket();
+ int channel = computer.channel(row);
+ assertThat(channel).isBetween(0, numChannels - 1);
+ channelsByBucket.computeIfAbsent(bucket, k -> new
HashSet<>()).add(channel);
+ }
+ for (Set<Integer> channels : channelsByBucket.values()) {
+ assertThat(channels.size()).isGreaterThanOrEqualTo(numStripes);
+ }
+ }
+
+ @Test
+ public void testAppendPartitionInterleavingDoesNotCancelRoundRobin()
throws Exception {
+ int numBuckets = 1;
+ int numStripes = 2;
+ int numChannels = 2;
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.INT(),
DataTypes.INT()},
+ new String[] {"pt", "k", "v"});
+ TableSchema schema =
+ createSchema(
+ rowType,
+ Collections.singletonList("pt"),
+ Collections.emptyList(),
+ numBuckets,
+ Collections.singletonMap("bucket-key", "k"));
+
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, numStripes);
+ computer.setup(numChannels);
+
+ // alternate two partitions of the same bucket with a fixed bucket
key; the partition
+ // rotation must not cancel the per-bucket round-robin and pin every
row to one channel
+ Set<Integer> channels = new HashSet<>();
+ for (int i = 0; i < 8000; i++) {
+ InternalRow row = GenericRow.of(i % 2, 7, i);
+ int channel = computer.channel(row);
+ assertThat(channel).isBetween(0, numChannels - 1);
+ channels.add(channel);
+ }
+ assertThat(channels).hasSize(numChannels);
+ }
+
+ private Map<Integer, Set<Integer>> groupByBucket(
+ TableSchema schema, List<InternalRow> input, int writesPerBucket,
int numChannels) {
+ StripedBucketWriteChannelComputer computer =
+ new StripedBucketWriteChannelComputer(schema, writesPerBucket);
+ computer.setup(numChannels);
+ FixedBucketRowKeyExtractor extractor = new
FixedBucketRowKeyExtractor(schema);
+
+ Map<Integer, Set<Integer>> channelsByBucket = new HashMap<>();
+ for (InternalRow row : input) {
+ extractor.setRecord(row);
+ int channel = computer.channel(row);
+ assertThat(channel).isBetween(0, numChannels - 1);
+ channelsByBucket.computeIfAbsent(extractor.bucket(), k -> new
HashSet<>()).add(channel);
+ }
+ return channelsByBucket;
+ }
+
+ private void assertStripesPerBucket(
+ Map<Integer, Set<Integer>> channelsByBucket, int numBuckets, int
expectedChannels) {
+ for (int bucket = 0; bucket < numBuckets; bucket++) {
+ assertThat(channelsByBucket.get(bucket)).hasSize(expectedChannels);
+ }
+ }
+
+ private TableSchema createNoPartitionSchema(int bucket) throws Exception {
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.BIGINT(),
DataTypes.DOUBLE()},
+ new String[] {"k", "v"});
+ return createSchema(
+ rowType, Collections.emptyList(),
Collections.singletonList("k"), bucket);
+ }
+
+ private TableSchema createPartitionedSchema(int bucket) throws Exception {
+ RowType rowType =
+ RowType.of(
+ new DataType[] {DataTypes.INT(), DataTypes.BIGINT(),
DataTypes.DOUBLE()},
+ new String[] {"pt", "k", "v"});
+ return createSchema(
+ rowType, Collections.singletonList("pt"), Arrays.asList("pt",
"k"), bucket);
+ }
+
+ private TableSchema createSchema(
+ RowType rowType, List<String> partitionKeys, List<String>
primaryKeys, int bucket)
+ throws Exception {
+ return createSchema(rowType, partitionKeys, primaryKeys, bucket,
Collections.emptyMap());
+ }
+
+ private TableSchema createSchema(
+ RowType rowType,
+ List<String> partitionKeys,
+ List<String> primaryKeys,
+ int bucket,
+ Map<String, String> extraOptions)
+ throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("bucket", String.valueOf(bucket));
+ options.putAll(extraOptions);
+ SchemaManager schemaManager =
+ new FileSystemSchemaManager(LocalFileIO.create(), new
Path(tempDir.toString()));
+ return schemaManager.createTable(
+ new Schema(rowType.getFields(), partitionKeys, primaryKeys,
options, ""));
+ }
+
+ private List<InternalRow> randomRows(int count, long seed) {
+ Random random = new Random(seed);
+ List<InternalRow> rows = new ArrayList<>(count);
+ for (int i = 0; i < count; i++) {
+ rows.add(GenericRow.of(random.nextLong(), random.nextDouble()));
+ }
+ return rows;
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSavepointITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSavepointITCase.java
new file mode 100644
index 0000000000..0e7755de5c
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSavepointITCase.java
@@ -0,0 +1,194 @@
+/*
+ * 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.flink.sink;
+
+import org.apache.paimon.flink.util.AbstractTestBase;
+
+import org.apache.flink.api.common.JobStatus;
+import org.apache.flink.configuration.CheckpointingOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.StateBackendOptions;
+import org.apache.flink.core.execution.JobClient;
+import org.apache.flink.core.execution.SavepointFormatType;
+import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
+import
org.apache.flink.runtime.scheduler.stopwithsavepoint.StopWithSavepointStoppingException;
+import org.apache.flink.table.api.TableEnvironment;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
+import org.apache.flink.util.ExceptionUtils;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Establishes the real behavior of restoring a striped write-only
fixed-bucket sink from a
+ * savepoint after the writer parallelism (and therefore the stripe count)
changes.
+ */
+public class StripedBucketWriteSavepointITCase extends AbstractTestBase {
+
+ private static final int NUM_KEYS = 5000;
+ private static final int NUM_RECORDS = 100000;
+
+ private String path;
+
+ @BeforeEach
+ public void before() throws Exception {
+ path = getTempDirPath();
+ }
+
+ @Test
+ @Timeout(180)
+ public void testRescaleFromSavepointKeepsAllRows() throws Exception {
+ // job 1: striped (writer parallelism 4 > bucket 2), stopped with a
savepoint mid-stream
+ String savepointPath = stopWithSavepoint(runJob(4, null));
+
+ // job 2: restore from the savepoint with a different writer
parallelism (and stripe count),
+ // then run the bounded source to completion
+ JobClient jobClient = runJob(2, savepointPath);
+ while (jobClient.getJobStatus().get() != JobStatus.FINISHED) {
+
assertThat(jobClient.getJobStatus().get().isGloballyTerminalState())
+ .as("job terminated without finishing: %s",
jobClient.getJobStatus().get())
+ .isFalse();
+ Thread.sleep(1000);
+ }
+
+ // every key must be present with its latest value: a rescaled restore
neither drops
+ // committed rows nor corrupts the striped routing
+ Map<Integer, Integer> expected = new HashMap<>();
+ for (int i = 0; i < NUM_RECORDS; i++) {
+ expected.put(i % NUM_KEYS, i);
+ }
+ Map<Integer, Integer> actual = new HashMap<>();
+ TableEnvironment tEnv = tableEnvironmentBuilder().batchMode().build();
+ tEnv.executeSql(
+ String.join(
+ "\n",
+ "CREATE CATALOG my_catalog WITH (",
+ " 'type' = 'paimon',",
+ " 'warehouse' = '" + path + "'",
+ ")"));
+ tEnv.executeSql("USE CATALOG my_catalog");
+ try (CloseableIterator<Row> it = tEnv.executeSql("SELECT * FROM
T").collect()) {
+ while (it.hasNext()) {
+ Row row = it.next();
+ assertThat(row.getArity()).isEqualTo(2);
+ actual.put((Integer) row.getField(0), (Integer)
row.getField(1));
+ }
+ }
+ assertThat(actual).isEqualTo(expected);
+ }
+
+ private String stopWithSavepoint(JobClient jobClient) throws Exception {
+ while (true) {
+ Thread.sleep(2000);
+ if (jobClient.getJobStatus().get() == JobStatus.FINISHED) {
+ throw new AssertionError("job finished before a savepoint
could be taken");
+ }
+ try {
+ return jobClient
+ .stopWithSavepoint(false, path + "/savepoint",
SavepointFormatType.DEFAULT)
+ .get();
+ } catch (Exception e) {
+ if (ExceptionUtils.findThrowable(e,
InterruptedException.class).isPresent()) {
+ throw e;
+ }
+ Optional<StopWithSavepointStoppingException> t =
+ ExceptionUtils.findThrowable(e,
StopWithSavepointStoppingException.class);
+ if (t.isPresent()) {
+ return t.get().getSavepointPath();
+ }
+ // the savepoint may fail transiently (job still initializing,
or already
+ // stopping); retry until it succeeds or the job finishes
+ }
+ }
+ }
+
+ private JobClient runJob(int sinkParallelism, String savepointPath) throws
Exception {
+ Configuration conf = new Configuration();
+ if (savepointPath != null) {
+ SavepointRestoreSettings.toConfiguration(
+ SavepointRestoreSettings.forPath(savepointPath, false),
conf);
+ }
+ TableEnvironment tEnv =
+ tableEnvironmentBuilder()
+ .streamingMode()
+ .checkpointIntervalMs(500)
+ .parallelism(1)
+ .allowRestart()
+ .setConf(conf)
+ .setConf(StateBackendOptions.STATE_BACKEND, "hashmap")
+ .setConf(
+ CheckpointingOptions.CHECKPOINTS_DIRECTORY,
+ "file://" + path + "/checkpoint")
+ .build();
+
+ tEnv.executeSql(
+ String.join(
+ "\n",
+ "CREATE CATALOG my_catalog WITH (",
+ " 'type' = 'paimon',",
+ " 'warehouse' = '" + path + "'",
+ ")"));
+ tEnv.executeSql("USE CATALOG my_catalog");
+
+ tEnv.executeSql(
+ String.join(
+ "\n",
+ "CREATE TEMPORARY TABLE S (",
+ " a INT",
+ ") WITH (",
+ " 'connector' = 'datagen',",
+ " 'rows-per-second' = '20000',",
+ " 'fields.a.kind' = 'sequence',",
+ " 'fields.a.start' = '0',",
+ " 'fields.a.end' = '" + (NUM_RECORDS - 1) + "'",
+ ")"));
+
+ tEnv.executeSql(
+ String.join(
+ "\n",
+ "CREATE TABLE IF NOT EXISTS T (",
+ " k INT,",
+ " v INT,",
+ " PRIMARY KEY (k) NOT ENFORCED",
+ ") WITH (",
+ " 'bucket' = '2',",
+ " 'file.format' = 'avro',",
+ " 'write-only' = 'true',",
+ " 'sink.striped-bucket-write.enabled' = 'true'",
+ ")"));
+
+ String insertIntoSql =
+ String.format(
+ "INSERT INTO T /*+ OPTIONS('sink.parallelism' = '%d')
*/ "
+ + "SELECT (a %% %d) AS k, a AS v FROM S",
+ sinkParallelism, NUM_KEYS);
+ JobClient jobClient =
tEnv.executeSql(insertIntoSql).getJobClient().get();
+ while (jobClient.getJobStatus().get() == JobStatus.INITIALIZING) {
+ Thread.sleep(500);
+ }
+ return jobClient;
+ }
+}
diff --git
a/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSinkITCase.java
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSinkITCase.java
new file mode 100644
index 0000000000..9164ff00b2
--- /dev/null
+++
b/paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/sink/StripedBucketWriteSinkITCase.java
@@ -0,0 +1,404 @@
+/*
+ * 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.flink.sink;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.flink.source.FlinkSourceBuilder;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.options.Options;
+import org.apache.paimon.schema.FileSystemSchemaManager;
+import org.apache.paimon.schema.Schema;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.FileStoreTableFactory;
+
+import org.apache.flink.api.common.RuntimeExecutionMode;
+import org.apache.flink.configuration.BatchExecutionOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.ExecutionOptions;
+import org.apache.flink.runtime.jobgraph.JobVertex;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.IntType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.VarCharType;
+import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.apache.flink.configuration.CoreOptions.DEFAULT_PARALLELISM;
+import static org.apache.paimon.CoreOptions.BUCKET;
+import static org.apache.paimon.CoreOptions.FILE_FORMAT;
+import static org.apache.paimon.CoreOptions.PATH;
+import static org.apache.paimon.flink.LogicalTypeConversion.toDataType;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** ITCase for {@code sink.striped-bucket-write.*} on fixed-bucket tables. */
+public class StripedBucketWriteSinkITCase {
+
+ @TempDir private static java.nio.file.Path temporaryFolder;
+
+ private static final RowType TABLE_TYPE =
+ new RowType(
+ Arrays.asList(
+ new RowType.RowField("k", new IntType()),
+ new RowType.RowField("v", new IntType())));
+
+ private static final DataType INPUT_TYPE =
+ DataTypes.ROW(
+ DataTypes.FIELD("k", DataTypes.INT()),
DataTypes.FIELD("v", DataTypes.INT()));
+
+ private static final RowType INDEX_TABLE_TYPE =
+ new RowType(
+ Arrays.asList(
+ new RowType.RowField("id", new IntType()),
+ new RowType.RowField(
+ "content", new
VarCharType(VarCharType.MAX_LENGTH))));
+
+ private static final DataType INDEX_INPUT_TYPE =
+ DataTypes.ROW(
+ DataTypes.FIELD("id", DataTypes.INT()),
+ DataTypes.FIELD("content", DataTypes.STRING()));
+
+ private static final int NUM_KEYS = 100;
+ private static final int NUM_BUCKETS = 2;
+
+ @Test
+ public void testAutoStripesExpandWriterParallelism() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("sink.parallelism", "4");
+ // sink parallelism 4 > bucket 2, striping should keep all 4 writers
instead of capping to 2
+ assertThat(writerParallelism(options, 4)).isEqualTo(4);
+ }
+
+ @Test
+ public void testExplicitWritersPerBucketDerivesParallelism() throws
Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("sink.striped-bucket-write.writers-per-bucket", "3");
+ options.put("write-only", "true");
+ // explicit writers-per-bucket=3 -> writer parallelism is 3 * bucket =
6, regardless of env
+ // parallelism
+ assertThat(writerParallelism(options, 1)).isEqualTo(6);
+ }
+
+ @Test
+ public void testMatchParallelismStripes() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("sink.striped-bucket-write.writers-per-bucket", "-1");
+ options.put("write-only", "true");
+ options.put("sink.parallelism", "4");
+ // K = parallelism, every writer writes every bucket, parallelism
stays 4
+ assertThat(writerParallelism(options, 4)).isEqualTo(4);
+ }
+
+ @Test
+ public void testDisabledKeepsBucketCap() throws Exception {
+ // no striped-write options and no sink.parallelism -> writer
parallelism caps to bucket
+ // count
+ assertThat(writerParallelism(new HashMap<>(),
4)).isEqualTo(NUM_BUCKETS);
+ }
+
+ @Test
+ public void testExplicitOneWriterPerBucket() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("sink.striped-bucket-write.writers-per-bucket", "1");
+ options.put("write-only", "true");
+ // a single writer per bucket still uses the striped computer
(degenerate routing);
+ // writer parallelism is 1 * bucket
+ assertThat(writerParallelism(options, 4)).isEqualTo(NUM_BUCKETS);
+ }
+
+ @Test
+ public void testWritersPerBucketIgnoredWhenDisabled() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.writers-per-bucket", "3");
+ // enabled is the sole switch: without it writers-per-bucket is
ignored, no write-only is
+ // required, and the default path caps writer parallelism to the
bucket count
+ assertThat(writerParallelism(options, 4)).isEqualTo(NUM_BUCKETS);
+ }
+
+ @Test
+ public void testWritersPerBucketZeroRejected() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("sink.striped-bucket-write.writers-per-bucket", "0");
+ FileStoreTable table = buildTable(options);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatThrownBy(() -> buildJob(env, table, 1))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("writers-per-bucket");
+ }
+
+ @Test
+ public void testStripedWriteRequiresWriteOnly() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ // write-only defaults to false; striped write must reject inline
compaction by multiple
+ // writers
+ FileStoreTable table = buildTable(options);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatThrownBy(() -> buildJob(env, table, 1))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("write-only");
+ }
+
+ @Test
+ public void testStripedWriteRejectsDeletionVectors() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("deletion-vectors.enabled", "true");
+ FileStoreTable table = buildTable(options);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatThrownBy(() -> buildJob(env, table, 1))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("deletion-vectors");
+ }
+
+ @Test
+ public void testStripedWriteAppendFixedBucket() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("sink.parallelism", "4");
+ options.put("bucket-key", "k");
+ // striping an append table breaks the append order contract, so it
requires unordered
+ options.put("bucket-append-ordered", "false");
+ // append-only fixed-bucket table: writer parallelism is not capped to
the bucket count
+ assertThat(writerParallelism(options, 4, Collections.emptyList(),
NUM_BUCKETS))
+ .isEqualTo(4);
+
+ // records round-robin across the writers of each bucket; all appended
rows are retained
+ FileStoreTable table = buildTable(options, Collections.emptyList(),
NUM_BUCKETS);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ buildJob(env, table, 1);
+ env.execute();
+ assertThat(readResults(table)).hasSize(NUM_KEYS);
+ }
+
+ @Test
+ public void testStripedWriteRejectsOrderedAppend() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("bucket-key", "k");
+ // bucket-append-ordered defaults to true; striping successive rows
across writers would
+ // break the ordered append read contract, so the sink must reject it
+ FileStoreTable table = buildTable(options, Collections.emptyList(),
NUM_BUCKETS);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatThrownBy(() -> buildJob(env, table, 1))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("bucket-append-ordered");
+ }
+
+ @Test
+ public void testStripedWriteRejectsPrimaryKeyIndex() throws Exception {
+ // a full-text index on a FIRST_ROW table is valid without deletion
vectors, so the
+ // primary-key index guard (not the deletion-vectors guard) must
reject striped write:
+ // each writer would publish a conflicting index for the same bucket
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("merge-engine", "first-row");
+ options.put("pk-full-text.index.columns", "content");
+ FileStoreTable table =
+ buildTableWithType(options, INDEX_TABLE_TYPE,
Collections.singletonList("id"), 1);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ DataStream<Row> source =
+ env.fromSequence(1, 3).map(x -> Row.of(x.intValue(),
"content-" + x));
+ source.getTransformation().setParallelism(source.getParallelism(),
false);
+ FlinkSinkBuilder builder =
+ new FlinkSinkBuilder(table).forRow(source,
INDEX_INPUT_TYPE).parallelism(4);
+ assertThatThrownBy(() -> builder.build())
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("primary-key indexes");
+ }
+
+ @Test
+ public void testStripedWriteIgnoredForDynamicBucket() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ // dynamic-bucket mode never reads the striped-write option: no
write-only needed, builds
+ // normally
+ FileStoreTable table = buildTable(options,
Collections.singletonList("k"), -1);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatCode(() -> buildJob(env, table,
1)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testStripedWriteIgnoredForUnawareBucket() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ // unaware-bucket append mode never reads the striped-write option:
builds normally
+ FileStoreTable table = buildTable(options, Collections.emptyList(),
-1);
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ assertThatCode(() -> buildJob(env, table,
1)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testStripedWriteReadCorrectness() throws Exception {
+ Map<String, String> options = new HashMap<>();
+ options.put("sink.striped-bucket-write.enabled", "true");
+ options.put("write-only", "true");
+ options.put("sink.parallelism", "4");
+ FileStoreTable table = buildTable(options);
+
+ // two rounds of upserts on the same keys; the second round must win
after merge-on-read
+ for (int round = 1; round <= 2; round++) {
+ StreamExecutionEnvironment env =
+
StreamExecutionEnvironment.getExecutionEnvironment(batchConfiguration(4));
+ buildJob(env, table, round);
+ env.execute();
+ }
+
+ List<Row> results = readResults(table);
+ assertThat(results).hasSize(NUM_KEYS);
+ results.sort(Comparator.comparingInt(x -> x.getFieldAs(0)));
+ for (int i = 0; i < NUM_KEYS; i++) {
+ Row result = results.get(i);
+ assertThat(result.getField(0)).isEqualTo(i);
+ assertThat((int) result.getFieldAs(1)).isEqualTo(NUM_KEYS + i);
+ }
+ }
+
+ private int writerParallelism(Map<String, String> tableOptions, int
envParallelism)
+ throws Exception {
+ return writerParallelism(
+ tableOptions, envParallelism, Collections.singletonList("k"),
NUM_BUCKETS);
+ }
+
+ private int writerParallelism(
+ Map<String, String> tableOptions,
+ int envParallelism,
+ List<String> primaryKeys,
+ int bucket)
+ throws Exception {
+ FileStoreTable table = buildTable(tableOptions, primaryKeys, bucket);
+ StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment(
+ batchConfiguration(envParallelism));
+ buildJob(env, table, 1);
+ for (JobVertex vertex :
env.getStreamGraph(false).getJobGraph().getVertices()) {
+ if (vertex.getName().startsWith("Writer")) {
+ return vertex.getParallelism();
+ }
+ }
+ throw new AssertionError("Writer vertex not found");
+ }
+
+ private Configuration batchConfiguration(int parallelism) {
+ Configuration configuration = new Configuration();
+ configuration.set(ExecutionOptions.RUNTIME_MODE,
RuntimeExecutionMode.BATCH);
+ configuration.set(DEFAULT_PARALLELISM, parallelism);
+ configuration.set(
+
BatchExecutionOptions.ADAPTIVE_AUTO_PARALLELISM_MIN_PARALLELISM, parallelism);
+ configuration.set(
+
BatchExecutionOptions.ADAPTIVE_AUTO_PARALLELISM_MAX_PARALLELISM, parallelism);
+ return configuration;
+ }
+
+ private FileStoreTable buildTable(Map<String, String> tableOptions) throws
Exception {
+ return buildTable(tableOptions, Collections.singletonList("k"),
NUM_BUCKETS);
+ }
+
+ private FileStoreTable buildTable(
+ Map<String, String> tableOptions, List<String> primaryKeys, int
bucket)
+ throws Exception {
+ return buildTableWithType(tableOptions, TABLE_TYPE, primaryKeys,
bucket);
+ }
+
+ private FileStoreTable buildTableWithType(
+ Map<String, String> tableOptions, RowType rowType, List<String>
primaryKeys, int bucket)
+ throws Exception {
+ Options options = new Options();
+ String path = new File(temporaryFolder.toFile(), UUID.randomUUID() +
"/").toString();
+ options.set(PATH, path);
+ options.set(FILE_FORMAT, CoreOptions.FILE_FORMAT_AVRO);
+ options.set(BUCKET, bucket);
+ for (Map.Entry<String, String> entry : tableOptions.entrySet()) {
+ options.set(entry.getKey(), entry.getValue());
+ }
+ Path tablePath = new CoreOptions(options.toMap()).path();
+ Schema schema =
+ new Schema(
+ toDataType(rowType).getFields(),
+ Collections.emptyList(),
+ primaryKeys,
+ options.toMap(),
+ "");
+ new FileSystemSchemaManager(LocalFileIO.create(),
tablePath).createTable(schema);
+ return FileStoreTableFactory.create(LocalFileIO.create(), options);
+ }
+
+ private void buildJob(StreamExecutionEnvironment env, FileStoreTable
table, int round) {
+ DataStream<Row> source =
+ env.fromSequence((long) (round - 1) * NUM_KEYS, (long) round *
NUM_KEYS - 1)
+ .map(x -> Row.of(x.intValue() % NUM_KEYS,
x.intValue()));
+ source.getTransformation().setParallelism(source.getParallelism(),
false);
+ FlinkSinkBuilder builder = new FlinkSinkBuilder(table).forRow(source,
INPUT_TYPE);
+ // mirror FlinkTableSinkBase, which feeds sink.parallelism into the
builder
+ String sinkParallelism = table.options().get("sink.parallelism");
+ if (sinkParallelism != null) {
+ builder.parallelism(Integer.parseInt(sinkParallelism));
+ }
+ builder.build();
+ }
+
+ private List<Row> readResults(FileStoreTable table) throws Exception {
+ StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
+ DataStream<Row> source =
+ new
FlinkSourceBuilder(table).env(env).sourceBounded(true).buildForRow();
+ List<Row> results = new ArrayList<>();
+ try (CloseableIterator<Row> iterator = source.executeAndCollect()) {
+ while (iterator.hasNext()) {
+ results.add(iterator.next());
+ }
+ }
+ return results;
+ }
+}