github-actions[bot] commented on code in PR #62661:
URL: https://github.com/apache/doris/pull/62661#discussion_r3116595339


##########
fe/fe-core/src/main/java/org/apache/doris/qe/runtime/ThriftPlansBuilder.java:
##########
@@ -242,8 +271,121 @@ private static void 
setParamsForOlapTableSink(List<PipelineDistributedPlan> dist
                     
fragmentParams.setNumLocalSink(fragmentParams.getLocalParams().size());
                     LOG.info("num local sink for backend {} is {}", 
fragmentParams.getBackendId(),
                             fragmentParams.getNumLocalSink());
+
+                    // Assign per-BE starting bucket and local_bucket_seqs for 
random distribution
+                    if (originalOlapSink != null) {
+                        assignRandomBucketPerBe(fragmentParams, worker.id(), 
originalOlapSink);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * For random-distribution partitions, override load_tablet_idx and set 
bucket_be_id /
+     * local_bucket_seqs so that each BE starts writing to one of its own 
local buckets and
+     * can rotate within them once per-tablet bytes exceed the threshold.
+     *
+     * <p>local_bucket_seqs always contains all local buckets for this BE. The 
starting bucket
+     * rotates across consecutive load tasks via tabletIndex; within a single 
load, the BE
+     * switches to the next entry in the list only when the 200 MB threshold 
is reached.
+     * Small loads (e.g. stream load) naturally stay on one bucket because the 
threshold is
+     * never triggered.
+     *
+     * <p>When {@code Config.enable_adaptive_random_bucket_load} is true, this 
is called for all
+     * random-distribution tables, including those with {@code 
load_to_single_tablet=true}.
+     *
+     * @param originalOlapSink the shared TOlapTableSink captured before any 
per-BE mutation;
+     *                         every BE deep-copies from this original to 
avoid one BE's copy
+     *                         becoming the base for the next BE's copy.
+     */
+    private static void assignRandomBucketPerBe(TPipelineFragmentParams 
fragmentParams,
+            long beId, TOlapTableSink originalOlapSink) {
+        if (originalOlapSink.getPartition() == null
+                || !originalOlapSink.getPartition().isSetPartitions()) {
+            return;
+        }
+
+        // Check whether any partition uses random distribution (identified by 
load_tablet_idx being set)
+        boolean hasRandomPartition = 
originalOlapSink.getPartition().getPartitions().stream()
+                .anyMatch(TOlapTablePartition::isSetLoadTabletIdx);
+        if (!hasRandomPartition) {
+            return;
+        }
+
+        // Build tablet_id -> BE IDs index from the original location (not the 
potentially-mutated copy)
+        TOlapTableLocationParam location = originalOlapSink.getLocation();
+        if (location == null || !location.isSetTablets()) {
+            return;
+        }
+        Map<Long, List<Long>> tabletToBeIds = new HashMap<>();
+        for (TTabletLocation tabletLoc : location.getTablets()) {
+            tabletToBeIds.put(tabletLoc.getTabletId(), tabletLoc.getNodeIds());
+        }
+
+        // Deep-copy from the original so that per-BE mutations are fully 
isolated.
+        // Using originalOlapSink (not outputSink.getOlapTableSink()) ensures 
that even if a
+        // previous BE's call already replaced the shared reference, we still 
start from clean data.
+        TDataSink outputSink = fragmentParams.getFragment().getOutputSink();
+        TOlapTableSink sinkCopy = originalOlapSink.deepCopy();
+        outputSink.setOlapTableSink(sinkCopy);
+
+        for (TOlapTablePartition tPartition : 
sinkCopy.getPartition().getPartitions()) {
+            if (!tPartition.isSetLoadTabletIdx()) {
+                continue; // hash distribution – leave as-is
+            }
+
+            int tabletIndex = (int) tPartition.getLoadTabletIdx();
+            List<org.apache.doris.thrift.TOlapTableIndexTablets> indexes = 
tPartition.getIndexes();
+            if (indexes == null || indexes.isEmpty()) {
+                continue;
+            }
+            List<Long> tablets = indexes.get(0).getTablets();
+            int numBuckets = tPartition.getNumBuckets();
+
+            // Collect bucket indices assigned to this BE.
+            //
+            // For single-replica tablets, each bucket has exactly one entry 
in node_ids,
+            // so the bucket naturally belongs to one BE.
+            //
+            // For multi-replica tablets, multiple BEs host the same bucket. 
To avoid all BEs
+            // writing to the same bucket(s), we assign each bucket to exactly 
one BE using a
+            // deterministic rule: sort node_ids, then give bucket[i] to the 
BE at position
+            // (i % numReplicas) in the sorted list. This spreads buckets 
evenly and requires
+            // no coordination.
+            List<Integer> localBuckets = new ArrayList<>();
+            for (int bucketIdx = 0; bucketIdx < tablets.size(); bucketIdx++) {
+                List<Long> beIds = tabletToBeIds.get(tablets.get(bucketIdx));
+                if (beIds == null || beIds.isEmpty()) {
+                    continue;
+                }
+                if (beIds.size() == 1) {
+                    if (beIds.get(0).equals(beId)) {
+                        localBuckets.add(bucketIdx);
+                    }
+                } else {
+                    // Multi-replica: deterministic per-bucket owner assignment

Review Comment:
   `fragment.toThrift()` still reuses the same `TDataSink` instance for every 
worker because `PlanFragment.toThrift()` stores `sink.toThrift()` and 
`OlapTableSink.toThrift()` just returns its cached `tDataSink`. Here we only 
deep-copy the nested `TOlapTableSink`, then replace it on that shared 
`outputSink`, so the last worker processed overwrites the bucket assignment 
seen by earlier workers. To make the mutation truly BE-local we need to 
deep-copy the enclosing `TDataSink` (or `TPlanFragment`) before calling 
`setOlapTableSink()`.



##########
be/src/storage/tablet_info.cpp:
##########
@@ -700,10 +700,15 @@ Status 
VOlapTablePartitionParam::generate_partition_from(const TOlapTablePartiti
     part_result = _obj_pool.add(new VOlapTablePartition(&_partition_block));
     part_result->id = t_part.id;
     part_result->is_mutable = t_part.is_mutable;
-    // only load_to_single_tablet = true will set load_tablet_idx
     if (t_part.__isset.load_tablet_idx) {
         part_result->load_tablet_idx = t_part.load_tablet_idx;
     }
+    if (t_part.__isset.bucket_be_id) {
+        part_result->bucket_be_id = t_part.bucket_be_id;
+    }
+    if (t_part.__isset.local_bucket_seqs) {
+        part_result->local_bucket_seqs = t_part.local_bucket_seqs;

Review Comment:
   This only fixes the initial `generate_partition_from()` path. The runtime 
refresh paths still omit the new adaptive fields: FE 
`FrontendServiceImpl.createPartition()/replacePartition()` build 
`TOlapTablePartition` without `load_tablet_idx` and `local_bucket_seqs`, and BE 
`add_partitions()/replace_partitions()` also do not copy them. Once 
`FIND_TABLET_RANDOM_BUCKET` sees one of those new partitions, `load_tablet_idx` 
stays `-1` and `vtablet_finder.cpp` indexes `indexes[0].tablets[load_tablet_idx 
% num_buckets]`, which becomes an out-of-bounds access. The same propagation 
has to be added on the runtime partition-update path, not just initial sink 
construction.



##########
be/src/exec/sink/vtablet_finder.cpp:
##########
@@ -82,8 +83,82 @@ Status OlapTabletFinder::find_tablets(RuntimeState* state, 
Block* block, int row
 
     if (_find_tablet_mode == FindTabletMode::FIND_TABLET_EVERY_ROW) {
         _vpartition->find_tablets(block, qualified_rows, partitions, 
tablet_index);
+    } else if (_find_tablet_mode == FindTabletMode::FIND_TABLET_RANDOM_BUCKET) 
{
+        // Use per-batch caching: all rows in the same partition go to the 
same tablet this batch.
+        _vpartition->find_tablets(block, qualified_rows, partitions, 
tablet_index,
+                                  &_partition_to_tablet_map);
+
+        // Count actual rows per partition so we don't credit each partition 
with the
+        // full block size when a block spans multiple partitions.
+        flat_hash_map<VOlapTablePartition*, int64_t> partition_row_counts;
+        for (uint32_t qi : qualified_rows) {
+            partition_row_counts[partitions[qi]]++;
+        }
+
+        int64_t bytes_per_row = rows > 0 ? block->bytes() / rows : 0;
+        for (auto& [partition, _] : _partition_to_tablet_map) {
+            if (partition->indexes.empty()) {
+                continue;
+            }
+            const auto& seqs = partition->local_bucket_seqs;

Review Comment:
   `_tablet_written_bytes` is lifetime bytes per tablet, but the threshold is 
supposed to be bytes written since this bucket became active. After bucket 0 
crosses 200 MB once, wrapping back to bucket 0 later will re-enter this branch 
on the very next batch because its counter is still at or above 200 MB. That 
turns large loads into "rotate every batch after the first cycle" instead of 
writing roughly 200 MB chunks. We need to reset or subtract the current bucket 
counter when we advance, or track bytes per active stint rather than lifetime 
bytes per tablet.



##########
fe/fe-common/src/main/java/org/apache/doris/common/Config.java:
##########
@@ -3610,4 +3610,15 @@ public static int metaServiceRpcRetryTimes() {
                     + "obtaining partition version information when 
calculating the delete bitmap. Enabled "
                     + "by default."})
     public static boolean 
calc_delete_bitmap_get_versions_waiting_for_pending_txns = true;
+
+    @ConfField(mutable = true, masterOnly = true, description = {
+            "Whether to enable adaptive random bucket load. When enabled, the 
FE assigns each BE only the "
+                    + "buckets whose primary replica it hosts 
(local_bucket_seqs), and the BE rotates across "
+                    + "those buckets once per-tablet write volume exceeds the 
threshold (default 200 MB). "
+                    + "This reduces import memory pressure and improves 
throughput for random-distribution "
+                    + "tables. When enabled, load_to_single_tablet is also 
subsumed by this strategy.",

Review Comment:
   This default `true` config changes the meaning of the existing 
`load_to_single_tablet=true` option on Nereids-distributed broker loads. 
`NereidsLoadPlanInfoCollector` still forwards 
`taskInfo.isLoadToSingleTablet()`, `LoadLoadingTask` goes through 
`ThriftPlansBuilder`, and the BE now prefers `FIND_TABLET_RANDOM_BUCKET` 
whenever `local_bucket_seqs` is present. So an explicit "write one tablet per 
partition for this load" request can now fan out across multiple local buckets, 
and even rotate after 200 MB, with no opt-in. That is a user-visible 
compatibility break; the adaptive rewrite should skip 
`load_to_single_tablet=true` or be behind a separate property.



##########
be/src/exec/sink/writer/vtablet_writer.cpp:
##########
@@ -1538,12 +1538,25 @@ Status VTabletWriter::_init(RuntimeState* state, 
RuntimeProfile* profile) {
     if (table_sink.__isset.send_batch_parallelism && 
table_sink.send_batch_parallelism > 1) {
         _send_batch_parallelism = table_sink.send_batch_parallelism;
     }
-    // if distributed column list is empty, we can ensure that tablet is with 
random distribution info
-    // and if load_to_single_tablet is set and set to true, we should find 
only one tablet in one partition
-    // for the whole olap table sink
+    // If distributed column list is empty, the table uses random distribution.
+    // Mode priority (highest to lowest):
+    //   1. FIND_TABLET_RANDOM_BUCKET: FE set local_bucket_seqs on at least 
one partition,
+    //      meaning enable_adaptive_random_bucket_load is ON. This overrides 
load_to_single_tablet

Review Comment:
   This comment overstates what the v1 sink path does. `VTabletWriter::_init()` 
still walks every tablet in every partition at lines 1654-1675 and 
`IndexChannel::init()/VNodeChannel::open()` opens them all up front, so the 
adaptive routing only changes which tablets receive rows later. The 
import-memory reduction claimed here is therefore only true on the lazy 
`VTabletWriterV2` path, not on `VTabletWriter`.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to