JingsongLi commented on code in PR #11015: URL: https://github.com/apache/paimon/pull/11015#discussion_r4522964676
########## 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.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 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. 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; + // Round-robin progress per (partition, bucket). A single shared counter would correlate with + // the bucket arrival pattern (e.g. alternating buckets always pick the same stripe), leaving + // each bucket on one writer even though more are available. + private transient Map<BinaryRow, 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(); + this.stripeCounters = new HashMap<>(); + } + + 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 (hasPrimaryKey) { + stripe = keyStripe(extractor.trimmedPrimaryKey()); + } else { + int[] counters = stripeCounters.get(partition); + if (counters == null) { + counters = new int[numBuckets]; Review Comment: **[P2] Bound append routing state by the buckets actually observed** An append router allocates `int[numBuckets]` for every distinct partition it touches, retains it for the life of the task, and does this even when there is only one stripe. For a 4,096-bucket backfill touching 100,000 tenant/date partitions, that is about 1.5 GiB of counters per router that sees those partitions, even if each partition has rows in only one bucket. Could we bypass the counter for one stripe and use sparse, bounded state for active partition/bucket pairs? ########## docs/docs/flink/sql-write.mdx: ########## @@ -114,6 +114,53 @@ 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 rather than +duplicating the whole key space. For an append-only table, records are distributed across the +writers round-robin. + +:::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. + +Do not change the writer parallelism or the number of writers per bucket when restoring from a +savepoint: each bucket's writer states are redistributed by bucket, and states for the same bucket Review Comment: **[P2] Verify the savepoint restore contract for the actual striped sink** The warning says redistributing writer state silently loses rows, but this fixed-bucket branch requires `write-only=true` and uses `StoreSinkWriteImpl`, whose Flink `snapshotState()` is a no-op. Its `write.checkpoint()/restore()` calls are in same-task table replacement. Flink flushes and emits committables at the checkpoint barrier on the ordinary path. Could we add a rescaled-savepoint integration case to establish the real behavior, and reject the restore at startup if it can lose data? The current sink suite does not exercise this production path. -- 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]
