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


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/sink/StripedBucketWriteChannelComputer.java:
##########
@@ -0,0 +1,175 @@
+/*
+ * 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;
+        int startChannel = ChannelComputer.startChannel(partition, 
numChannels);
+        return (int) ((startChannel + bucketSlot) % numChannels);

Review Comment:
   [P2] Prevent partition rotation from cancelling append round-robin
   
   The append counter is shared by partitions of the same bucket, while 
startChannel rotates by partition. These terms can cancel on a regular 
interleaving. With a valid ordinary append schema (pt INT, k INT, v INT), 
partitioned by pt, bucket=1, bucket-key=k, write-only=true, 
bucket-append-ordered=false and two writers, alternate (pt=1,k=7,v=0), 
(pt=0,k=7,v=1), etc. Partition offsets 0/1 and stripes 0/1 cancel, sending 
every row to channel 0. On the exact compiled head, 8000 rows route [8000,0]; 
the existing router and single-partition striped control each route 
[4000,4000]. A real Flink job using the production partitioner/computer and 
FixedBucketSink confirms [2000,0] versus [1000,1000], retaining all 2000 rows. 
Enabling striping thus leaves a writer idle on a normal partitioned workload. 
Avoid the partition rotation for multi-stripe append routing, or use another 
bounded policy preventing cancellation; preserve single-stripe compatibility 
and add this regression.



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