Coverage Report

Created: 2026-07-08 14:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/channel/tablets_channel.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "load/channel/tablets_channel.h"
19
20
#include <bvar/bvar.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/internal_service.pb.h>
23
#include <gen_cpp/types.pb.h>
24
25
#include <ctime>
26
27
#include "common/compiler_util.h" // IWYU pragma: keep
28
#include "common/status.h"
29
// IWYU pragma: no_include <bits/chrono.h>
30
#include <chrono> // IWYU pragma: keep
31
#include <initializer_list>
32
#include <optional>
33
#include <set>
34
#include <thread>
35
#include <utility>
36
37
#ifdef DEBUG
38
#include <unordered_set>
39
#endif
40
41
#include "common/logging.h"
42
#include "common/metrics/doris_metrics.h"
43
#include "common/metrics/metrics.h"
44
#include "core/block/block.h"
45
#include "load/channel/load_channel.h"
46
#include "load/delta_writer/delta_writer.h"
47
#include "storage/storage_engine.h"
48
#include "storage/tablet/tablet_manager.h"
49
#include "storage/tablet_info.h"
50
#include "storage/txn/txn_manager.h"
51
#include "util/defer_op.h"
52
53
namespace doris {
54
class SlotDescriptor;
55
56
bvar::Adder<int64_t> g_tablets_channel_send_data_allocated_size(
57
        "tablets_channel_send_data_allocated_size");
58
59
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(tablet_writer_count, MetricUnit::NOUNIT);
60
61
std::atomic<uint64_t> BaseTabletsChannel::_s_tablet_writer_count;
62
63
BaseTabletsChannel::BaseTabletsChannel(const TabletsChannelKey& key, const UniqueId& load_id,
64
                                       bool is_high_priority, RuntimeProfile* profile)
65
30.1k
        : _key(key),
66
30.1k
          _state(kInitialized),
67
30.1k
          _load_id(load_id),
68
30.1k
          _closed_senders(64),
69
30.1k
          _is_high_priority(is_high_priority) {
70
30.1k
    static std::once_flag once_flag;
71
30.1k
    if (profile != nullptr) {
72
11
        _init_profile(profile);
73
11
    }
74
30.1k
    std::call_once(once_flag, [] {
75
4
        REGISTER_HOOK_METRIC(tablet_writer_count, [&]() { return _s_tablet_writer_count.load(); });
76
4
    });
77
30.1k
}
78
79
TabletsChannel::TabletsChannel(StorageEngine& engine, const TabletsChannelKey& key,
80
                               const UniqueId& load_id, bool is_high_priority,
81
                               RuntimeProfile* profile)
82
12
        : BaseTabletsChannel(key, load_id, is_high_priority, profile), _engine(engine) {}
83
84
30.1k
BaseTabletsChannel::~BaseTabletsChannel() {
85
30.1k
    _s_tablet_writer_count -= _tablet_writers.size();
86
30.1k
}
87
88
TabletsChannel::~TabletsChannel() = default;
89
90
Status BaseTabletsChannel::_get_current_seq(int64_t& cur_seq,
91
32.9k
                                            const PTabletWriterAddBlockRequest& request) {
92
32.9k
    std::lock_guard<std::mutex> l(_lock);
93
32.9k
    if (_state != kOpened) {
94
0
        return _state == kFinished ? _close_status
95
0
                                   : Status::InternalError("TabletsChannel {} state: {}",
96
0
                                                           _key.to_string(), _state);
97
0
    }
98
32.9k
    cur_seq = _next_seqs[request.sender_id()];
99
    // check packet
100
32.9k
    if (request.packet_seq() > cur_seq) {
101
0
        LOG(WARNING) << "lost data packet, expect_seq=" << cur_seq
102
0
                     << ", recept_seq=" << request.packet_seq();
103
0
        return Status::InternalError("lost data packet");
104
0
    }
105
32.9k
    return Status::OK();
106
32.9k
}
107
108
11
void BaseTabletsChannel::_init_profile(RuntimeProfile* profile) {
109
11
    DCHECK(profile != nullptr);
110
11
    _profile =
111
11
            profile->create_child(fmt::format("TabletsChannel {}", _key.to_string()), true, true);
112
11
    _add_batch_number_counter = ADD_COUNTER(_profile, "NumberBatchAdded", TUnit::UNIT);
113
114
11
    auto* memory_usage = _profile->create_child("PeakMemoryUsage", true, true);
115
11
    _add_batch_timer = ADD_TIMER(_profile, "AddBatchTime");
116
11
    _write_block_timer = ADD_TIMER(_profile, "WriteBlockTime");
117
11
    _incremental_open_timer = ADD_TIMER(_profile, "IncrementalOpenTabletTime");
118
11
    _memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Total", TUnit::BYTES);
119
11
    _write_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Write", TUnit::BYTES);
120
11
    _flush_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Flush", TUnit::BYTES);
121
11
    _max_tablet_memory_usage_counter =
122
11
            memory_usage->AddHighWaterMarkCounter("MaxTablet", TUnit::BYTES);
123
11
    _max_tablet_write_memory_usage_counter =
124
11
            memory_usage->AddHighWaterMarkCounter("MaxTabletWrite", TUnit::BYTES);
125
11
    _max_tablet_flush_memory_usage_counter =
126
11
            memory_usage->AddHighWaterMarkCounter("MaxTabletFlush", TUnit::BYTES);
127
11
}
128
129
0
void TabletsChannel::_init_profile(RuntimeProfile* profile) {
130
0
    DCHECK(profile != nullptr);
131
0
    BaseTabletsChannel::_init_profile(profile);
132
0
    _slave_replica_timer = ADD_TIMER(_profile, "SlaveReplicaTime");
133
0
}
134
135
44.3k
Status BaseTabletsChannel::open(const PTabletWriterOpenRequest& request) {
136
44.3k
    std::lock_guard<std::mutex> l(_lock);
137
    // if _state is kOpened, it's a normal case, already open by other sender
138
    // if _state is kFinished, already cancelled by other sender
139
44.3k
    if (_state == kOpened) {
140
14.2k
        RETURN_IF_ERROR(_init_adaptive_random_bucket_state(request));
141
14.2k
        return Status::OK();
142
14.2k
    }
143
30.1k
    if (_state == kFinished) {
144
0
        return Status::OK();
145
0
    }
146
30.1k
    _txn_id = request.txn_id();
147
30.1k
    _index_id = request.index_id();
148
30.1k
    _schema = std::make_shared<OlapTableSchemaParam>();
149
30.1k
    RETURN_IF_ERROR(_schema->init(request.schema()));
150
30.1k
    _tuple_desc = _schema->tuple_desc();
151
30.1k
    int max_sender = request.num_senders();
152
    /*
153
     * a tablets channel in reciever is related to a bulk of VNodeChannel of sender. each instance one or none.
154
     * there are two possibilities:
155
     *  1. there's partitions originally broadcasted by FE. so all sender(instance) know it at start. and open() will be 
156
     *     called directly, not by incremental_open(). and after _state changes to kOpened. _open_by_incremental will never 
157
     *     be true. in this case, _num_remaining_senders will keep same with senders number. when all sender sent close rpc,
158
     *     the tablets channel will close. and if for auto partition table, these channel's closing will hang on reciever and
159
     *     return together to avoid close-then-incremental-open problem.
160
     *  2. this tablets channel is opened by incremental_open of sender's sink node. so only this sender will know this partition
161
     *     (this TabletsChannel) at that time. and we are not sure how many sender will know in the end. it depends on data
162
     *     distribution. in this situation open() is called by incremental_open() at first time. so _open_by_incremental is true.
163
     *     then _num_remaining_senders will not be set here. but inc every time when incremental_open() called. so it's dynamic
164
     *     and also need same number of senders' close to close. but will not hang.
165
     */
166
30.1k
    if (_open_by_incremental) {
167
0
        DCHECK(_num_remaining_senders == 0) << _num_remaining_senders;
168
30.1k
    } else {
169
30.1k
        _num_remaining_senders = max_sender;
170
30.1k
    }
171
30.1k
    LOG(INFO) << fmt::format(
172
30.1k
            "open tablets channel {}, tablets num: {} timeout(s): {}, init senders {} with "
173
30.1k
            "incremental {}",
174
30.1k
            _key.to_string(), request.tablets().size(), request.load_channel_timeout_s(),
175
30.1k
            _num_remaining_senders, _open_by_incremental ? "on" : "off");
176
    // just use max_sender no matter incremental or not cuz we dont know how many senders will open.
177
30.1k
    _next_seqs.resize(max_sender, 0);
178
30.1k
    _closed_senders.Reset(max_sender);
179
180
30.1k
    RETURN_IF_ERROR(_open_all_writers(request));
181
30.1k
    RETURN_IF_ERROR(_init_adaptive_random_bucket_state(request));
182
183
30.1k
    _state = kOpened;
184
30.1k
    return Status::OK();
185
30.1k
}
186
187
185
Status BaseTabletsChannel::incremental_open(const PTabletWriterOpenRequest& params) {
188
185
    SCOPED_TIMER(_incremental_open_timer);
189
190
    // current node first opened by incremental open
191
185
    if (_state == kInitialized) {
192
0
        _open_by_incremental = true;
193
0
        RETURN_IF_ERROR(open(params));
194
0
    }
195
196
185
    std::lock_guard<std::mutex> l(_lock);
197
198
    // one sender may incremental_open many times. but only close one time. so dont count duplicately.
199
185
    if (_open_by_incremental) {
200
0
        if (params.has_sender_id() && !_recieved_senders.contains(params.sender_id())) {
201
0
            _recieved_senders.insert(params.sender_id());
202
0
            _num_remaining_senders++;
203
0
        } else if (!params.has_sender_id()) { // for compatible
204
0
            _num_remaining_senders++;
205
0
        }
206
0
        VLOG_DEBUG << fmt::format("txn {}: TabletsChannel {} inc senders to {}", _txn_id, _index_id,
207
0
                                  _num_remaining_senders);
208
0
    }
209
210
185
    std::vector<SlotDescriptor*>* index_slots = nullptr;
211
185
    int32_t schema_hash = 0;
212
213
185
    for (const auto& index : _schema->indexes()) {
214
185
        if (index->index_id == _index_id) {
215
185
            index_slots = &index->slots;
216
185
            schema_hash = index->schema_hash;
217
185
            break;
218
185
        }
219
185
    }
220
185
    if (index_slots == nullptr) {
221
0
        return Status::InternalError("unknown index id, key={}", _key.to_string());
222
0
    }
223
    // update tablets
224
185
    size_t incremental_tablet_num = 0;
225
185
    std::stringstream ss;
226
185
    ss << "LocalTabletsChannel txn_id: " << _txn_id << " load_id: " << print_id(params.id())
227
185
       << " incremental open delta writer: ";
228
229
    // every change will hold _lock. this find in under _lock too. so no need _tablet_writers_lock again.
230
6.64k
    for (const auto& tablet : params.tablets()) {
231
6.64k
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
232
96
            continue;
233
96
        }
234
6.55k
        incremental_tablet_num++;
235
236
6.55k
        WriteRequest wrequest;
237
6.55k
        wrequest.index_id = params.index_id();
238
6.55k
        wrequest.tablet_id = tablet.tablet_id();
239
6.55k
        wrequest.schema_hash = schema_hash;
240
6.55k
        wrequest.txn_id = _txn_id;
241
6.55k
        wrequest.partition_id = tablet.partition_id();
242
6.55k
        wrequest.load_id = params.id();
243
6.55k
        wrequest.tuple_desc = _tuple_desc;
244
6.55k
        wrequest.slots = index_slots;
245
6.55k
        wrequest.is_high_priority = _is_high_priority;
246
6.55k
        wrequest.table_schema_param = _schema;
247
6.55k
        wrequest.txn_expiration = params.txn_expiration(); // Required by CLOUD.
248
6.55k
        wrequest.write_file_cache = params.write_file_cache();
249
6.55k
        wrequest.storage_vault_id = params.storage_vault_id();
250
6.55k
        wrequest.enable_table_memtable_backpressure = params.is_adaptive_random_bucket();
251
252
6.55k
        auto delta_writer = create_delta_writer(wrequest);
253
6.55k
        {
254
            // here we modify _tablet_writers. so need lock.
255
6.55k
            std::lock_guard<std::mutex> lt(_tablet_writers_lock);
256
6.55k
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
257
6.55k
        }
258
259
6.55k
        ss << "[" << tablet.tablet_id() << "]";
260
6.55k
    }
261
262
185
    _s_tablet_writer_count += incremental_tablet_num;
263
185
    LOG(INFO) << ss.str();
264
185
    RETURN_IF_ERROR(_init_adaptive_random_bucket_state(params));
265
266
185
    _state = kOpened;
267
185
    return Status::OK();
268
185
}
269
270
Status BaseTabletsChannel::_init_adaptive_random_bucket_state(
271
44.5k
        const PTabletWriterOpenRequest& request) {
272
44.5k
    if (!request.is_adaptive_random_bucket() || request.random_bucket_partitions_size() == 0) {
273
35.2k
        return Status::OK();
274
35.2k
    }
275
9.30k
    if (_adaptive_random_bucket_state == nullptr) {
276
2.65k
        _adaptive_random_bucket_state = std::make_shared<AdaptiveRandomBucketState>(_load_id);
277
2.65k
    }
278
9.51k
    for (const auto& partition : request.random_bucket_partitions()) {
279
9.51k
        if (partition.ordered_tablet_ids_size() == 0) {
280
0
            return Status::InternalError(
281
0
                    "ordered_tablet_ids is empty for adaptive random bucket, load_id={}, "
282
0
                    "sender_id={}, partition_id={}",
283
0
                    print_id(_load_id), request.sender_id(), partition.partition_id());
284
0
        }
285
9.51k
        std::vector<int32_t> ordered_positions;
286
9.51k
        ordered_positions.reserve(partition.ordered_tablet_ids_size());
287
41.6k
        for (int i = 0; i < partition.ordered_tablet_ids_size(); ++i) {
288
32.1k
            ordered_positions.push_back(cast_set<int32_t>(i));
289
32.1k
        }
290
9.51k
        std::vector<int64_t> ordered_tablet_ids;
291
9.51k
        ordered_tablet_ids.reserve(partition.ordered_tablet_ids_size());
292
32.1k
        for (auto tablet_id : partition.ordered_tablet_ids()) {
293
32.1k
            ordered_tablet_ids.push_back(tablet_id);
294
32.1k
        }
295
9.51k
        RETURN_IF_ERROR(_adaptive_random_bucket_state->init_partition(
296
9.51k
                partition.partition_id(), ordered_tablet_ids, ordered_positions, 0));
297
9.51k
    }
298
9.30k
    return Status::OK();
299
9.30k
}
300
301
89
std::unique_ptr<BaseDeltaWriter> TabletsChannel::create_delta_writer(const WriteRequest& request) {
302
89
    DCHECK(request.write_req_type == WriteRequestType::DATA);
303
89
    DCHECK(request.table_schema_param != nullptr);
304
305
89
    int64_t row_binlog_index_id = 0;
306
89
    for (const auto* index_schema : request.table_schema_param->indexes()) {
307
89
        if (index_schema->index_id == request.index_id) {
308
89
            row_binlog_index_id = index_schema->row_binlog_id;
309
89
            break;
310
89
        }
311
89
    }
312
89
    if (row_binlog_index_id <= 0) {
313
89
        return std::make_unique<DeltaWriter>(_engine, request, _profile, _load_id);
314
89
    }
315
316
0
    const auto* row_binlog_index_schema = request.table_schema_param->row_binlog_index_schema();
317
0
    DCHECK(row_binlog_index_schema != nullptr);
318
0
    DCHECK(row_binlog_index_schema->index_id == row_binlog_index_id);
319
320
    // group_build_req is only for the group wrapper itself. It provides the group semantics and
321
    // metadata used by BaseDeltaWriter/GroupRowsetBuilder to expose tablet_id, txn_id,
322
    // partition_id, load_id and profile information, while concrete rowset builders use the
323
    // sub requests below.
324
0
    WriteRequest group_build_req = request;
325
0
    group_build_req.write_req_type = WriteRequestType::GROUP;
326
327
0
    WriteRequest sub_data_req = request;
328
0
    sub_data_req.write_req_type = WriteRequestType::DATA;
329
330
0
    WriteRequest sub_row_binlog_req = request;
331
0
    sub_row_binlog_req.write_req_type = WriteRequestType::ROW_BINLOG;
332
0
    sub_row_binlog_req.index_id = row_binlog_index_schema->index_id;
333
0
    sub_row_binlog_req.schema_hash = row_binlog_index_schema->schema_hash;
334
335
0
    return std::make_unique<DeltaWriter>(_engine, group_build_req, sub_data_req, sub_row_binlog_req,
336
0
                                         _profile, _load_id);
337
89
}
338
339
Status TabletsChannel::close(LoadChannel* parent, const PTabletWriterAddBlockRequest& req,
340
12
                             PTabletWriterAddBlockResult* res, bool* finished) {
341
12
    int sender_id = req.sender_id();
342
12
    int64_t backend_id = req.backend_id();
343
12
    const auto& partition_ids = req.partition_ids();
344
12
    auto* tablet_errors = res->mutable_tablet_errors();
345
12
    std::lock_guard<std::mutex> l(_lock);
346
12
    if (_state == kFinished) {
347
0
        return _close_status;
348
0
    }
349
12
    if (_closed_senders.Get(sender_id)) {
350
        // Double close from one sender, just return OK
351
0
        *finished = (_num_remaining_senders == 0);
352
0
        return _close_status;
353
0
    }
354
355
212
    for (auto pid : partition_ids) {
356
212
        _partition_ids.emplace(pid);
357
212
    }
358
12
    _closed_senders.Set(sender_id, true);
359
12
    _num_remaining_senders--;
360
12
    *finished = (_num_remaining_senders == 0);
361
362
12
    LOG(INFO) << fmt::format(
363
12
            "txn {}: close tablets channel of index {} , sender id: {}, backend {}, remain "
364
12
            "senders: {}",
365
12
            _txn_id, _index_id, sender_id, backend_id, _num_remaining_senders);
366
367
12
    if (!*finished) {
368
0
        return Status::OK();
369
0
    }
370
371
12
    _state = kFinished;
372
    // All senders are closed
373
    // 1. close all delta writers
374
12
    std::set<DeltaWriter*> need_wait_writers;
375
    // under _lock. no need _tablet_writers_lock again.
376
89
    for (auto&& [tablet_id, writer] : _tablet_writers) {
377
89
        if (_partition_ids.contains(writer->partition_id())) {
378
59
            auto st = writer->close();
379
59
            if (!st.ok()) {
380
0
                auto err_msg = fmt::format(
381
0
                        "close tablet writer failed, tablet_id={}, "
382
0
                        "transaction_id={}, err={}",
383
0
                        tablet_id, _txn_id, st.to_string());
384
0
                LOG(WARNING) << err_msg;
385
0
                PTabletError* tablet_error = tablet_errors->Add();
386
0
                tablet_error->set_tablet_id(tablet_id);
387
0
                tablet_error->set_msg(st.to_string());
388
                // just skip this tablet(writer) and continue to close others
389
0
                continue;
390
0
            }
391
            // tablet writer in `_broken_tablets` should not call `build_rowset` and
392
            // `commit_txn` method, after that, the publish-version task will success,
393
            // which can cause the replica inconsistency.
394
59
            if (_is_broken_tablet(writer->tablet_id())) {
395
0
                LOG(WARNING) << "SHOULD NOT HAPPEN, tablet writer is broken but not cancelled"
396
0
                             << ", tablet_id=" << tablet_id << ", transaction_id=" << _txn_id;
397
0
                continue;
398
0
            }
399
59
            need_wait_writers.insert(static_cast<DeltaWriter*>(writer.get()));
400
59
        } else {
401
30
            auto st = writer->cancel();
402
30
            if (!st.ok()) {
403
0
                LOG(WARNING) << "cancel tablet writer failed, tablet_id=" << tablet_id
404
0
                             << ", transaction_id=" << _txn_id;
405
                // just skip this tablet(writer) and continue to close others
406
0
                continue;
407
0
            }
408
30
            VLOG_PROGRESS << "cancel tablet writer successfully, tablet_id=" << tablet_id
409
0
                          << ", transaction_id=" << _txn_id;
410
30
        }
411
89
    }
412
413
12
    _write_single_replica = req.write_single_replica();
414
415
    // 2. wait all writer finished flush.
416
59
    for (auto* writer : need_wait_writers) {
417
59
        RETURN_IF_ERROR((writer->wait_flush()));
418
59
    }
419
420
    // 3. build rowset
421
71
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
422
59
        Status st = (*it)->build_rowset();
423
59
        if (!st.ok()) {
424
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
425
0
            it = need_wait_writers.erase(it);
426
0
            continue;
427
0
        }
428
        // 3.1 calculate delete bitmap for Unique Key MoW tables
429
59
        st = (*it)->submit_calc_delete_bitmap_task();
430
59
        if (!st.ok()) {
431
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
432
0
            it = need_wait_writers.erase(it);
433
0
            continue;
434
0
        }
435
59
        it++;
436
59
    }
437
438
    // 4. wait for delete bitmap calculation complete if necessary
439
71
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
440
59
        Status st = (*it)->wait_calc_delete_bitmap();
441
59
        if (!st.ok()) {
442
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
443
0
            it = need_wait_writers.erase(it);
444
0
            continue;
445
0
        }
446
59
        it++;
447
59
    }
448
449
    // 5. commit all writers
450
451
59
    for (auto* writer : need_wait_writers) {
452
        // close may return failed, but no need to handle it here.
453
        // tablet_vec will only contains success tablet, and then let FE judge it.
454
59
        _commit_txn(writer, req, res);
455
59
    }
456
457
12
    if (_write_single_replica) {
458
0
        auto* success_slave_tablet_node_ids = res->mutable_success_slave_tablet_node_ids();
459
        // The operation waiting for all slave replicas to complete must end before the timeout,
460
        // so that there is enough time to collect completed replica. Otherwise, the task may
461
        // timeout and fail even though most of the replicas are completed. Here we set 0.9
462
        // times the timeout as the maximum waiting time.
463
0
        SCOPED_TIMER(_slave_replica_timer);
464
0
        while (!need_wait_writers.empty() &&
465
0
               (time(nullptr) - parent->last_updated_time()) < (parent->timeout() * 0.9)) {
466
0
            std::set<DeltaWriter*>::iterator it;
467
0
            for (it = need_wait_writers.begin(); it != need_wait_writers.end();) {
468
0
                bool is_done = (*it)->check_slave_replicas_done(success_slave_tablet_node_ids);
469
0
                if (is_done) {
470
0
                    need_wait_writers.erase(it++);
471
0
                } else {
472
0
                    it++;
473
0
                }
474
0
            }
475
0
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
476
0
        }
477
0
        for (auto* writer : need_wait_writers) {
478
0
            writer->add_finished_slave_replicas(success_slave_tablet_node_ids);
479
0
        }
480
0
        _engine.txn_manager()->clear_txn_tablet_delta_writer(_txn_id);
481
0
    }
482
483
12
    return Status::OK();
484
12
}
485
486
void TabletsChannel::_commit_txn(DeltaWriter* writer, const PTabletWriterAddBlockRequest& req,
487
59
                                 PTabletWriterAddBlockResult* res) {
488
59
    PSlaveTabletNodes slave_nodes;
489
59
    if (_write_single_replica) {
490
0
        auto& nodes_map = req.slave_tablet_nodes();
491
0
        auto it = nodes_map.find(writer->tablet_id());
492
0
        if (it != nodes_map.end()) {
493
0
            slave_nodes = it->second;
494
0
        }
495
0
    }
496
59
    Status st = writer->commit_txn(slave_nodes);
497
59
    if (st.ok()) [[likely]] {
498
59
        auto* tablet_vec = res->mutable_tablet_vec();
499
59
        PTabletInfo* tablet_info = tablet_vec->Add();
500
59
        tablet_info->set_tablet_id(writer->tablet_id());
501
        // unused required field.
502
59
        tablet_info->set_schema_hash(0);
503
59
        tablet_info->set_received_rows(writer->total_received_rows());
504
59
        tablet_info->set_num_rows_filtered(writer->num_rows_filtered());
505
59
        _total_received_rows += writer->total_received_rows();
506
59
        _num_rows_filtered += writer->num_rows_filtered();
507
59
    } else {
508
0
        _add_error_tablet(res->mutable_tablet_errors(), writer->tablet_id(), st);
509
0
    }
510
59
}
511
512
void BaseTabletsChannel::_add_error_tablet(
513
        google::protobuf::RepeatedPtrField<PTabletError>* tablet_errors, int64_t tablet_id,
514
0
        Status error) const {
515
0
    PTabletError* tablet_error = tablet_errors->Add();
516
0
    tablet_error->set_tablet_id(tablet_id);
517
0
    tablet_error->set_msg(error.to_string());
518
0
    VLOG_PROGRESS << "close wait failed tablet " << tablet_id << " transaction_id " << _txn_id
519
0
                  << "err msg " << error;
520
0
}
521
522
37
void BaseTabletsChannel::refresh_profile() {
523
37
    int64_t write_mem_usage = 0;
524
37
    int64_t flush_mem_usage = 0;
525
37
    int64_t max_tablet_mem_usage = 0;
526
37
    int64_t max_tablet_write_mem_usage = 0;
527
37
    int64_t max_tablet_flush_mem_usage = 0;
528
37
    {
529
37
        std::lock_guard<std::mutex> l(_tablet_writers_lock);
530
151
        for (auto&& [tablet_id, writer] : _tablet_writers) {
531
151
            int64_t write_mem = writer->mem_consumption(MemType::WRITE_FINISHED);
532
151
            write_mem_usage += write_mem;
533
151
            int64_t flush_mem = writer->mem_consumption(MemType::FLUSH);
534
151
            flush_mem_usage += flush_mem;
535
151
            if (write_mem > max_tablet_write_mem_usage) {
536
0
                max_tablet_write_mem_usage = write_mem;
537
0
            }
538
151
            if (flush_mem > max_tablet_flush_mem_usage) {
539
0
                max_tablet_flush_mem_usage = flush_mem;
540
0
            }
541
151
            if (write_mem + flush_mem > max_tablet_mem_usage) {
542
0
                max_tablet_mem_usage = write_mem + flush_mem;
543
0
            }
544
151
        }
545
37
    }
546
37
    COUNTER_SET(_memory_usage_counter, write_mem_usage + flush_mem_usage);
547
37
    COUNTER_SET(_write_memory_usage_counter, write_mem_usage);
548
37
    COUNTER_SET(_flush_memory_usage_counter, flush_mem_usage);
549
37
    COUNTER_SET(_max_tablet_memory_usage_counter, max_tablet_mem_usage);
550
37
    COUNTER_SET(_max_tablet_write_memory_usage_counter, max_tablet_write_mem_usage);
551
37
    COUNTER_SET(_max_tablet_flush_memory_usage_counter, max_tablet_flush_mem_usage);
552
37
}
553
554
30.1k
Status BaseTabletsChannel::_open_all_writers(const PTabletWriterOpenRequest& request) {
555
30.1k
    std::vector<SlotDescriptor*>* index_slots = nullptr;
556
30.1k
    int32_t schema_hash = 0;
557
34.1k
    for (const auto& index : _schema->indexes()) {
558
34.1k
        if (index->index_id == _index_id) {
559
30.1k
            index_slots = &index->slots;
560
30.1k
            schema_hash = index->schema_hash;
561
30.1k
            break;
562
30.1k
        }
563
34.1k
    }
564
30.1k
    if (index_slots == nullptr) {
565
0
        return Status::InternalError("unknown index id, key={}", _key.to_string());
566
0
    }
567
568
#ifdef DEBUG
569
    // check: tablet ids should be unique
570
    {
571
        std::unordered_set<int64_t> tablet_ids;
572
        for (const auto& tablet : request.tablets()) {
573
            CHECK(tablet_ids.count(tablet.tablet_id()) == 0)
574
                    << "found duplicate tablet id: " << tablet.tablet_id();
575
            tablet_ids.insert(tablet.tablet_id());
576
        }
577
    }
578
#endif
579
580
30.1k
    int tablet_cnt = 0;
581
    // under _lock. no need _tablet_writers_lock again.
582
262k
    for (const auto& tablet : request.tablets()) {
583
262k
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
584
0
            continue;
585
0
        }
586
262k
        tablet_cnt++;
587
262k
        WriteRequest wrequest {
588
262k
                .tablet_id = tablet.tablet_id(),
589
262k
                .schema_hash = schema_hash,
590
262k
                .txn_id = _txn_id,
591
262k
                .txn_expiration = request.txn_expiration(), // Required by CLOUD.
592
262k
                .index_id = request.index_id(),
593
262k
                .partition_id = tablet.partition_id(),
594
262k
                .load_id = request.id(),
595
262k
                .tuple_desc = _tuple_desc,
596
262k
                .slots = index_slots,
597
262k
                .table_schema_param = _schema,
598
262k
                .is_high_priority = _is_high_priority,
599
262k
                .write_file_cache = request.write_file_cache(),
600
262k
                .storage_vault_id = request.storage_vault_id(),
601
262k
                .enable_table_memtable_backpressure = request.is_adaptive_random_bucket(),
602
262k
        };
603
604
262k
        auto delta_writer = create_delta_writer(wrequest);
605
262k
        {
606
262k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
607
262k
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
608
262k
        }
609
262k
    }
610
30.1k
    _s_tablet_writer_count += _tablet_writers.size();
611
30.1k
    DCHECK_EQ(_tablet_writers.size(), tablet_cnt);
612
30.1k
    return Status::OK();
613
30.1k
}
614
615
119
Status BaseTabletsChannel::cancel() {
616
119
    std::lock_guard<std::mutex> l(_lock);
617
119
    if (_state == kFinished) {
618
86
        return _close_status;
619
86
    }
620
1.43k
    for (auto& it : _tablet_writers) {
621
1.43k
        static_cast<void>(it.second->cancel());
622
1.43k
    }
623
33
    _state = kFinished;
624
625
33
    return Status::OK();
626
119
}
627
628
0
Status TabletsChannel::cancel() {
629
0
    RETURN_IF_ERROR(BaseTabletsChannel::cancel());
630
0
    if (_write_single_replica) {
631
0
        _engine.txn_manager()->clear_txn_tablet_delta_writer(_txn_id);
632
0
    }
633
0
    return Status::OK();
634
0
}
635
636
30.1k
std::string TabletsChannelKey::to_string() const {
637
30.1k
    std::stringstream ss;
638
30.1k
    ss << *this;
639
30.1k
    return ss.str();
640
30.1k
}
641
642
74.5k
std::ostream& operator<<(std::ostream& os, const TabletsChannelKey& key) {
643
74.5k
    os << "(load_id=" << key.id << ", index_id=" << key.index_id << ")";
644
74.5k
    return os;
645
74.5k
}
646
647
Status BaseTabletsChannel::_write_block_data(
648
        const PTabletWriterAddBlockRequest& request, int64_t cur_seq,
649
        std::unordered_map<int64_t, DorisVector<uint32_t>>& tablet_to_rowidxs,
650
28.6k
        PTabletWriterAddBlockResult* response) {
651
28.6k
    Block send_data;
652
28.6k
    [[maybe_unused]] size_t uncompressed_size = 0;
653
28.6k
    [[maybe_unused]] int64_t uncompressed_time = 0;
654
28.6k
    RETURN_IF_ERROR(send_data.deserialize(request.block(), &uncompressed_size, &uncompressed_time));
655
28.6k
    int request_rows = request.is_adaptive_random_bucket() ? request.partition_ids_size()
656
28.6k
                                                           : request.tablet_ids_size();
657
28.6k
    if (send_data.rows() != request_rows) {
658
0
        return Status::InternalError(
659
0
                "invalid add block request row count, load_id={}, index_id={}, packet_seq={}, "
660
0
                "block_rows={}, request_rows={}",
661
0
                print_id(_load_id), _index_id, request.packet_seq(), send_data.rows(),
662
0
                request_rows);
663
0
    }
664
665
28.6k
    g_tablets_channel_send_data_allocated_size << send_data.allocated_bytes();
666
28.6k
    Defer defer {
667
28.6k
            [&]() { g_tablets_channel_send_data_allocated_size << -send_data.allocated_bytes(); }};
668
669
28.6k
    auto write_tablet_data = [&](int64_t tablet_id,
670
110k
                                 std::function<Status(BaseDeltaWriter * writer)> write_func) {
671
110k
        google::protobuf::RepeatedPtrField<PTabletError>* tablet_errors =
672
110k
                response->mutable_tablet_errors();
673
674
        // add_batch may concurrency with inc_open but not under _lock.
675
        // so need to protect it with _tablet_writers_lock.
676
110k
        BaseDeltaWriter* tablet_writer = nullptr;
677
110k
        {
678
110k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
679
110k
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
680
110k
            if (tablet_writer_it == _tablet_writers.end()) {
681
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
682
0
            }
683
110k
            tablet_writer = tablet_writer_it->second.get();
684
110k
        }
685
686
0
        Status st = write_func(tablet_writer);
687
110k
        if (!st.ok()) {
688
0
            auto err_msg =
689
0
                    fmt::format("tablet writer write failed, tablet_id={}, txn_id={}, err={}",
690
0
                                tablet_id, _txn_id, st.to_string());
691
0
            LOG(WARNING) << err_msg;
692
0
            PTabletError* error = tablet_errors->Add();
693
0
            error->set_tablet_id(tablet_id);
694
0
            error->set_msg(err_msg);
695
0
            static_cast<void>(tablet_writer->cancel_with_status(st));
696
0
            _add_broken_tablet(tablet_id);
697
            // continue write to other tablet.
698
            // the error will return back to sender.
699
0
        }
700
110k
        return Status::OK();
701
110k
    };
702
703
28.6k
    SCOPED_TIMER(_write_block_timer);
704
28.6k
    auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
705
110k
    for (const auto& tablet_to_rowidxs_it : tablet_to_rowidxs) {
706
110k
        bool memtable_flushed = false;
707
110k
        RETURN_IF_ERROR(write_tablet_data(tablet_to_rowidxs_it.first, [&](BaseDeltaWriter* writer) {
708
110k
            return writer->write(&send_data, tablet_to_rowidxs_it.second, &memtable_flushed);
709
110k
        }));
710
711
110k
        BaseDeltaWriter* tablet_writer = nullptr;
712
110k
        {
713
110k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
714
110k
            auto tablet_writer_it = _tablet_writers.find(tablet_to_rowidxs_it.first);
715
110k
            if (tablet_writer_it != _tablet_writers.end()) {
716
110k
                tablet_writer = tablet_writer_it->second.get();
717
110k
            }
718
110k
        }
719
110k
        if (tablet_writer != nullptr) {
720
110k
            tablet_writer->set_tablet_load_rowset_num_info(tablet_load_infos);
721
110k
        }
722
110k
    }
723
724
28.6k
    {
725
28.6k
        std::lock_guard<std::mutex> l(_lock);
726
28.6k
        _next_seqs[request.sender_id()] = cur_seq + 1;
727
28.6k
    }
728
28.6k
    return Status::OK();
729
28.6k
}
730
731
4.34k
std::shared_ptr<std::mutex> BaseTabletsChannel::_get_partition_route_lock(int64_t partition_id) {
732
4.34k
    std::lock_guard<std::mutex> l(_partition_route_locks_lock);
733
4.34k
    auto& lock = _partition_route_locks[partition_id];
734
4.34k
    if (lock == nullptr) {
735
2.70k
        lock = std::make_shared<std::mutex>();
736
2.70k
    }
737
4.34k
    return lock;
738
4.34k
}
739
740
Status BaseTabletsChannel::_write_block_data_for_adaptive_random_bucket(
741
        const PTabletWriterAddBlockRequest& request, int64_t cur_seq,
742
        std::unordered_map<int64_t, DorisVector<uint32_t>>& partition_to_rowidxs,
743
4.23k
        PTabletWriterAddBlockResult* response) {
744
4.23k
    Block send_data;
745
4.23k
    [[maybe_unused]] size_t uncompressed_size = 0;
746
4.23k
    [[maybe_unused]] int64_t uncompressed_time = 0;
747
4.23k
    RETURN_IF_ERROR(send_data.deserialize(request.block(), &uncompressed_size, &uncompressed_time));
748
4.23k
    if (send_data.rows() != request.partition_ids_size()) {
749
0
        return Status::InternalError(
750
0
                "invalid adaptive random bucket add block request row count, load_id={}, "
751
0
                "index_id={}, packet_seq={}, block_rows={}, partition_ids_size={}",
752
0
                print_id(_load_id), _index_id, request.packet_seq(), send_data.rows(),
753
0
                request.partition_ids_size());
754
0
    }
755
756
4.23k
    {
757
4.23k
        std::lock_guard<std::mutex> l(_lock);
758
4.34k
        for (const auto& [partition_id, _] : partition_to_rowidxs) {
759
4.34k
            _partition_ids.emplace(partition_id);
760
4.34k
        }
761
4.23k
    }
762
763
4.23k
    g_tablets_channel_send_data_allocated_size << send_data.allocated_bytes();
764
4.23k
    Defer defer {
765
4.23k
            [&]() { g_tablets_channel_send_data_allocated_size << -send_data.allocated_bytes(); }};
766
767
4.23k
    auto* tablet_errors = response->mutable_tablet_errors();
768
4.23k
    auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
769
770
4.23k
    auto write_partition_data = [&](int64_t partition_id,
771
4.34k
                                    const DorisVector<uint32_t>& row_idxs) -> Status {
772
4.34k
        auto partition_lock = _get_partition_route_lock(partition_id);
773
4.34k
        std::lock_guard<std::mutex> partition_guard(*partition_lock);
774
4.34k
        int64_t tablet_id = -1;
775
4.34k
        if (_adaptive_random_bucket_state == nullptr) {
776
0
            return Status::InternalError(
777
0
                    "adaptive random bucket state is not initialized, load_id={}, "
778
0
                    "index_id={}, packet_seq={}, partition_id={}",
779
0
                    print_id(_load_id), _index_id, request.packet_seq(), partition_id);
780
0
        }
781
4.34k
        tablet_id = _adaptive_random_bucket_state->current_tablet(partition_id);
782
4.34k
        if (tablet_id < 0) {
783
0
            return Status::InternalError(
784
0
                    "invalid current tablet for adaptive random bucket, load_id={}, "
785
0
                    "index_id={}, sender_id={}, packet_seq={}, partition_id={}",
786
0
                    print_id(_load_id), _index_id, request.sender_id(), request.packet_seq(),
787
0
                    partition_id);
788
0
        }
789
4.34k
        VLOG_DEBUG << "FIND_TABLET_RANDOM_BUCKET: route+write begin"
790
0
                   << ", load_id=" << _load_id << ", index_id=" << _index_id
791
0
                   << ", sender_id=" << request.sender_id()
792
0
                   << ", packet_seq=" << request.packet_seq() << ", partition_id=" << partition_id
793
0
                   << ", tablet_id=" << tablet_id << ", row_count=" << row_idxs.size();
794
795
4.34k
        {
796
4.34k
            std::shared_lock<std::shared_mutex> broken_rlock(_broken_tablets_lock);
797
4.34k
            if (_is_broken_tablet(tablet_id)) {
798
0
                return Status::InternalError(
799
0
                        "current tablet is broken for adaptive random bucket, load_id={}, "
800
0
                        "index_id={}, sender_id={}, packet_seq={}, partition_id={}, tablet_id={}",
801
0
                        print_id(_load_id), _index_id, request.sender_id(), request.packet_seq(),
802
0
                        partition_id, tablet_id);
803
0
            }
804
4.34k
        }
805
806
4.34k
        BaseDeltaWriter* tablet_writer = nullptr;
807
4.34k
        {
808
4.34k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
809
4.34k
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
810
4.34k
            if (tablet_writer_it == _tablet_writers.end()) {
811
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
812
0
            }
813
4.34k
            tablet_writer = tablet_writer_it->second.get();
814
4.34k
        }
815
4.34k
        RETURN_IF_ERROR(_prepare_adaptive_random_bucket_writer(tablet_writer));
816
817
4.34k
        bool memtable_flushed = false;
818
4.34k
        Status st = tablet_writer->write(&send_data, row_idxs, &memtable_flushed);
819
4.34k
        if (!st.ok()) {
820
0
            auto err_msg =
821
0
                    fmt::format("tablet writer write failed, tablet_id={}, txn_id={}, err={}",
822
0
                                tablet_id, _txn_id, st.to_string());
823
0
            LOG(WARNING) << err_msg;
824
0
            PTabletError* error = tablet_errors->Add();
825
0
            error->set_tablet_id(tablet_id);
826
0
            error->set_msg(err_msg);
827
0
            static_cast<void>(tablet_writer->cancel_with_status(st));
828
0
            _add_broken_tablet(tablet_id);
829
0
            return Status::OK();
830
0
        }
831
832
4.34k
        VLOG_DEBUG << "FIND_TABLET_RANDOM_BUCKET: route+write done"
833
0
                   << ", load_id=" << _load_id << ", index_id=" << _index_id
834
0
                   << ", sender_id=" << request.sender_id()
835
0
                   << ", packet_seq=" << request.packet_seq() << ", partition_id=" << partition_id
836
0
                   << ", tablet_id=" << tablet_id << ", row_count=" << row_idxs.size()
837
0
                   << ", memtable_flushed=" << memtable_flushed;
838
4.34k
        if (memtable_flushed) {
839
0
            _adaptive_random_bucket_state->rotate_by_tablet(partition_id, tablet_id);
840
0
        }
841
4.34k
        tablet_writer->set_tablet_load_rowset_num_info(tablet_load_infos);
842
4.34k
        return Status::OK();
843
4.34k
    };
844
845
4.23k
    SCOPED_TIMER(_write_block_timer);
846
4.34k
    for (const auto& [partition_id, row_idxs] : partition_to_rowidxs) {
847
4.34k
        RETURN_IF_ERROR(write_partition_data(partition_id, row_idxs));
848
4.34k
    }
849
850
4.23k
    {
851
4.23k
        std::lock_guard<std::mutex> l(_lock);
852
4.23k
        _next_seqs[request.sender_id()] = cur_seq + 1;
853
4.23k
    }
854
4.23k
    return Status::OK();
855
4.23k
}
856
857
0
Status BaseTabletsChannel::_prepare_adaptive_random_bucket_writer(BaseDeltaWriter*) {
858
0
    return Status::OK();
859
0
}
860
861
Status BaseTabletsChannel::_build_partition_to_rowidxs_for_adaptive_random_bucket(
862
        const PTabletWriterAddBlockRequest& request,
863
4.23k
        std::unordered_map<int64_t, DorisVector<uint32_t>>* partition_to_rowidxs) {
864
4.23k
    if (_adaptive_random_bucket_state == nullptr) {
865
0
        return Status::InternalError(
866
0
                "adaptive random bucket state is not initialized, load_id={}, index_id={}, "
867
0
                "packet_seq={}",
868
0
                print_id(_load_id), _index_id, request.packet_seq());
869
0
    }
870
4.23k
    if (request.partition_ids_size() == 0) {
871
0
        return Status::InternalError(
872
0
                "empty partition ids for adaptive random bucket add block, load_id={}, "
873
0
                "index_id={}, packet_seq={}",
874
0
                print_id(_load_id), _index_id, request.packet_seq());
875
0
    }
876
2.06M
    for (uint32_t i = 0; i < request.partition_ids_size(); ++i) {
877
2.06M
        int64_t partition_id = request.partition_ids(i);
878
2.06M
        auto it = partition_to_rowidxs->find(partition_id);
879
2.06M
        if (it == partition_to_rowidxs->end()) {
880
4.34k
            partition_to_rowidxs->emplace(partition_id, std::initializer_list<uint32_t> {i});
881
2.05M
        } else {
882
2.05M
            it->second.emplace_back(i);
883
2.05M
        }
884
2.06M
    }
885
4.23k
    return Status::OK();
886
4.23k
}
887
888
Status TabletsChannel::add_batch(const PTabletWriterAddBlockRequest& request,
889
12
                                 PTabletWriterAddBlockResult* response) {
890
12
    SCOPED_TIMER(_add_batch_timer);
891
12
    int64_t cur_seq = 0;
892
12
    if (_add_batch_number_counter) {
893
0
        _add_batch_number_counter->update(1);
894
0
    }
895
896
12
    auto status = _get_current_seq(cur_seq, request);
897
12
    if (UNLIKELY(!status.ok())) {
898
0
        return status;
899
0
    }
900
901
12
    if (request.packet_seq() < cur_seq) {
902
0
        LOG(INFO) << "packet has already recept before, expect_seq=" << cur_seq
903
0
                  << ", recept_seq=" << request.packet_seq();
904
0
        return Status::OK();
905
0
    }
906
907
    // Adaptive random bucket add-block RPCs carry partition ids. The receiver maps rows to
908
    // the current tablet and advances its selected-tablet state after memtable flush.
909
12
    if (request.is_adaptive_random_bucket()) {
910
0
        std::unordered_map<int64_t /* partition_id */, DorisVector<uint32_t> /* row index */>
911
0
                partition_to_rowidxs;
912
0
        RETURN_IF_ERROR(_build_partition_to_rowidxs_for_adaptive_random_bucket(
913
0
                request, &partition_to_rowidxs));
914
0
        return _write_block_data_for_adaptive_random_bucket(request, cur_seq, partition_to_rowidxs,
915
0
                                                            response);
916
0
    }
917
918
12
    std::unordered_map<int64_t /* tablet_id */, DorisVector<uint32_t> /* row index */>
919
12
            tablet_to_rowidxs;
920
12
    _build_tablet_to_rowidxs(request, &tablet_to_rowidxs);
921
12
    return _write_block_data(request, cur_seq, tablet_to_rowidxs, response);
922
12
}
923
924
0
void BaseTabletsChannel::_add_broken_tablet(int64_t tablet_id) {
925
0
    std::unique_lock<std::shared_mutex> wlock(_broken_tablets_lock);
926
0
    _broken_tablets.insert(tablet_id);
927
0
}
928
929
33.8M
bool BaseTabletsChannel::_is_broken_tablet(int64_t tablet_id) const {
930
33.8M
    return _broken_tablets.find(tablet_id) != _broken_tablets.end();
931
33.8M
}
932
933
void BaseTabletsChannel::_build_tablet_to_rowidxs(
934
        const PTabletWriterAddBlockRequest& request,
935
28.6k
        std::unordered_map<int64_t, DorisVector<uint32_t>>* tablet_to_rowidxs) {
936
    // just add a coarse-grained read lock here rather than each time when visiting _broken_tablets
937
    // tests show that a relatively coarse-grained read lock here performs better under multicore scenario
938
    // see: https://github.com/apache/doris/pull/28552
939
28.6k
    std::shared_lock<std::shared_mutex> rlock(_broken_tablets_lock);
940
28.6k
    if (request.is_single_tablet_block()) {
941
        // The cloud mode need the tablet ids to prepare rowsets.
942
0
        int64_t tablet_id = request.tablet_ids(0);
943
0
        tablet_to_rowidxs->emplace(tablet_id, std::initializer_list<uint32_t> {0});
944
0
        return;
945
0
    }
946
33.7M
    for (uint32_t i = 0; i < request.tablet_ids_size(); ++i) {
947
33.7M
        int64_t tablet_id = request.tablet_ids(i);
948
33.7M
        if (_is_broken_tablet(tablet_id)) {
949
            // skip broken tablets
950
0
            VLOG_PROGRESS << "skip broken tablet tablet=" << tablet_id;
951
0
            continue;
952
0
        }
953
33.7M
        auto it = tablet_to_rowidxs->find(tablet_id);
954
33.7M
        if (it == tablet_to_rowidxs->end()) {
955
110k
            tablet_to_rowidxs->emplace(tablet_id, std::initializer_list<uint32_t> {i});
956
33.5M
        } else {
957
33.5M
            it->second.emplace_back(i);
958
33.5M
        }
959
33.7M
    }
960
28.6k
}
961
962
} // namespace doris