Coverage Report

Created: 2026-07-08 08:53

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
0
        : _key(key),
66
0
          _state(kInitialized),
67
0
          _load_id(load_id),
68
0
          _closed_senders(64),
69
0
          _is_high_priority(is_high_priority) {
70
0
    static std::once_flag once_flag;
71
0
    if (profile != nullptr) {
72
0
        _init_profile(profile);
73
0
    }
74
0
    std::call_once(once_flag, [] {
75
0
        REGISTER_HOOK_METRIC(tablet_writer_count, [&]() { return _s_tablet_writer_count.load(); });
76
0
    });
77
0
}
78
79
TabletsChannel::TabletsChannel(StorageEngine& engine, const TabletsChannelKey& key,
80
                               const UniqueId& load_id, bool is_high_priority,
81
                               RuntimeProfile* profile)
82
0
        : BaseTabletsChannel(key, load_id, is_high_priority, profile), _engine(engine) {}
83
84
0
BaseTabletsChannel::~BaseTabletsChannel() {
85
0
    _s_tablet_writer_count -= _tablet_writers.size();
86
0
}
87
88
0
TabletsChannel::~TabletsChannel() = default;
89
90
Status BaseTabletsChannel::_get_current_seq(int64_t& cur_seq,
91
0
                                            const PTabletWriterAddBlockRequest& request) {
92
0
    std::lock_guard<std::mutex> l(_lock);
93
0
    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
0
    cur_seq = _next_seqs[request.sender_id()];
99
    // check packet
100
0
    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
0
    return Status::OK();
106
0
}
107
108
0
void BaseTabletsChannel::_init_profile(RuntimeProfile* profile) {
109
0
    DCHECK(profile != nullptr);
110
0
    _profile =
111
0
            profile->create_child(fmt::format("TabletsChannel {}", _key.to_string()), true, true);
112
0
    _add_batch_number_counter = ADD_COUNTER(_profile, "NumberBatchAdded", TUnit::UNIT);
113
114
0
    auto* memory_usage = _profile->create_child("PeakMemoryUsage", true, true);
115
0
    _add_batch_timer = ADD_TIMER(_profile, "AddBatchTime");
116
0
    _write_block_timer = ADD_TIMER(_profile, "WriteBlockTime");
117
0
    _incremental_open_timer = ADD_TIMER(_profile, "IncrementalOpenTabletTime");
118
0
    _memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Total", TUnit::BYTES);
119
0
    _write_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Write", TUnit::BYTES);
120
0
    _flush_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Flush", TUnit::BYTES);
121
0
    _max_tablet_memory_usage_counter =
122
0
            memory_usage->AddHighWaterMarkCounter("MaxTablet", TUnit::BYTES);
123
0
    _max_tablet_write_memory_usage_counter =
124
0
            memory_usage->AddHighWaterMarkCounter("MaxTabletWrite", TUnit::BYTES);
125
0
    _max_tablet_flush_memory_usage_counter =
126
0
            memory_usage->AddHighWaterMarkCounter("MaxTabletFlush", TUnit::BYTES);
127
0
}
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
0
Status BaseTabletsChannel::open(const PTabletWriterOpenRequest& request) {
136
0
    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
0
    if (_state == kOpened) {
140
0
        RETURN_IF_ERROR(_init_adaptive_random_bucket_state(request));
141
0
        return Status::OK();
142
0
    }
143
0
    if (_state == kFinished) {
144
0
        return Status::OK();
145
0
    }
146
0
    _txn_id = request.txn_id();
147
0
    _index_id = request.index_id();
148
0
    _schema = std::make_shared<OlapTableSchemaParam>();
149
0
    RETURN_IF_ERROR(_schema->init(request.schema()));
150
0
    _tuple_desc = _schema->tuple_desc();
151
0
    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
0
    if (_open_by_incremental) {
167
0
        DCHECK(_num_remaining_senders == 0) << _num_remaining_senders;
168
0
    } else {
169
0
        _num_remaining_senders = max_sender;
170
0
    }
171
0
    LOG(INFO) << fmt::format(
172
0
            "open tablets channel {}, tablets num: {} timeout(s): {}, init senders {} with "
173
0
            "incremental {}",
174
0
            _key.to_string(), request.tablets().size(), request.load_channel_timeout_s(),
175
0
            _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
0
    _next_seqs.resize(max_sender, 0);
178
0
    _closed_senders.Reset(max_sender);
179
180
0
    RETURN_IF_ERROR(_open_all_writers(request));
181
0
    RETURN_IF_ERROR(_init_adaptive_random_bucket_state(request));
182
183
0
    _state = kOpened;
184
0
    return Status::OK();
185
0
}
186
187
0
Status BaseTabletsChannel::incremental_open(const PTabletWriterOpenRequest& params) {
188
0
    SCOPED_TIMER(_incremental_open_timer);
189
190
    // current node first opened by incremental open
191
0
    if (_state == kInitialized) {
192
0
        _open_by_incremental = true;
193
0
        RETURN_IF_ERROR(open(params));
194
0
    }
195
196
0
    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
0
    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
0
    std::vector<SlotDescriptor*>* index_slots = nullptr;
211
0
    int32_t schema_hash = 0;
212
213
0
    for (const auto& index : _schema->indexes()) {
214
0
        if (index->index_id == _index_id) {
215
0
            index_slots = &index->slots;
216
0
            schema_hash = index->schema_hash;
217
0
            break;
218
0
        }
219
0
    }
220
0
    if (index_slots == nullptr) {
221
0
        return Status::InternalError("unknown index id, key={}", _key.to_string());
222
0
    }
223
    // update tablets
224
0
    size_t incremental_tablet_num = 0;
225
0
    std::stringstream ss;
226
0
    ss << "LocalTabletsChannel txn_id: " << _txn_id << " load_id: " << print_id(params.id())
227
0
       << " 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
0
    for (const auto& tablet : params.tablets()) {
231
0
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
232
0
            continue;
233
0
        }
234
0
        incremental_tablet_num++;
235
236
0
        WriteRequest wrequest;
237
0
        wrequest.index_id = params.index_id();
238
0
        wrequest.tablet_id = tablet.tablet_id();
239
0
        wrequest.schema_hash = schema_hash;
240
0
        wrequest.txn_id = _txn_id;
241
0
        wrequest.partition_id = tablet.partition_id();
242
0
        wrequest.load_id = params.id();
243
0
        wrequest.tuple_desc = _tuple_desc;
244
0
        wrequest.slots = index_slots;
245
0
        wrequest.is_high_priority = _is_high_priority;
246
0
        wrequest.table_schema_param = _schema;
247
0
        wrequest.txn_expiration = params.txn_expiration(); // Required by CLOUD.
248
0
        wrequest.write_file_cache = params.write_file_cache();
249
0
        wrequest.storage_vault_id = params.storage_vault_id();
250
0
        wrequest.enable_table_memtable_backpressure = params.is_adaptive_random_bucket();
251
252
0
        auto delta_writer = create_delta_writer(wrequest);
253
0
        {
254
            // here we modify _tablet_writers. so need lock.
255
0
            std::lock_guard<std::mutex> lt(_tablet_writers_lock);
256
0
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
257
0
        }
258
259
0
        ss << "[" << tablet.tablet_id() << "]";
260
0
    }
261
262
0
    _s_tablet_writer_count += incremental_tablet_num;
263
0
    LOG(INFO) << ss.str();
264
0
    RETURN_IF_ERROR(_init_adaptive_random_bucket_state(params));
265
266
0
    _state = kOpened;
267
0
    return Status::OK();
268
0
}
269
270
Status BaseTabletsChannel::_init_adaptive_random_bucket_state(
271
0
        const PTabletWriterOpenRequest& request) {
272
0
    if (!request.is_adaptive_random_bucket() || request.random_bucket_partitions_size() == 0) {
273
0
        return Status::OK();
274
0
    }
275
0
    if (_adaptive_random_bucket_state == nullptr) {
276
0
        _adaptive_random_bucket_state = std::make_shared<AdaptiveRandomBucketState>(_load_id);
277
0
    }
278
0
    for (const auto& partition : request.random_bucket_partitions()) {
279
0
        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
0
        std::vector<int32_t> ordered_positions;
286
0
        ordered_positions.reserve(partition.ordered_tablet_ids_size());
287
0
        for (int i = 0; i < partition.ordered_tablet_ids_size(); ++i) {
288
0
            ordered_positions.push_back(cast_set<int32_t>(i));
289
0
        }
290
0
        std::vector<int64_t> ordered_tablet_ids;
291
0
        ordered_tablet_ids.reserve(partition.ordered_tablet_ids_size());
292
0
        for (auto tablet_id : partition.ordered_tablet_ids()) {
293
0
            ordered_tablet_ids.push_back(tablet_id);
294
0
        }
295
0
        RETURN_IF_ERROR(_adaptive_random_bucket_state->init_partition(
296
0
                partition.partition_id(), ordered_tablet_ids, ordered_positions, 0));
297
0
    }
298
0
    return Status::OK();
299
0
}
300
301
0
std::unique_ptr<BaseDeltaWriter> TabletsChannel::create_delta_writer(const WriteRequest& request) {
302
0
    DCHECK(request.write_req_type == WriteRequestType::DATA);
303
0
    DCHECK(request.table_schema_param != nullptr);
304
305
0
    int64_t row_binlog_index_id = 0;
306
0
    for (const auto* index_schema : request.table_schema_param->indexes()) {
307
0
        if (index_schema->index_id == request.index_id) {
308
0
            row_binlog_index_id = index_schema->row_binlog_id;
309
0
            break;
310
0
        }
311
0
    }
312
0
    if (row_binlog_index_id <= 0) {
313
0
        return std::make_unique<DeltaWriter>(_engine, request, _profile, _load_id);
314
0
    }
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
0
}
338
339
Status TabletsChannel::close(LoadChannel* parent, const PTabletWriterAddBlockRequest& req,
340
0
                             PTabletWriterAddBlockResult* res, bool* finished) {
341
0
    int sender_id = req.sender_id();
342
0
    int64_t backend_id = req.backend_id();
343
0
    const auto& partition_ids = req.partition_ids();
344
0
    auto* tablet_errors = res->mutable_tablet_errors();
345
0
    std::lock_guard<std::mutex> l(_lock);
346
0
    if (_state == kFinished) {
347
0
        return _close_status;
348
0
    }
349
0
    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
0
    for (auto pid : partition_ids) {
356
0
        _partition_ids.emplace(pid);
357
0
    }
358
0
    _closed_senders.Set(sender_id, true);
359
0
    _num_remaining_senders--;
360
0
    *finished = (_num_remaining_senders == 0);
361
362
0
    LOG(INFO) << fmt::format(
363
0
            "txn {}: close tablets channel of index {} , sender id: {}, backend {}, remain "
364
0
            "senders: {}",
365
0
            _txn_id, _index_id, sender_id, backend_id, _num_remaining_senders);
366
367
0
    if (!*finished) {
368
0
        return Status::OK();
369
0
    }
370
371
0
    _state = kFinished;
372
    // All senders are closed
373
    // 1. close all delta writers
374
0
    std::set<DeltaWriter*> need_wait_writers;
375
    // under _lock. no need _tablet_writers_lock again.
376
0
    for (auto&& [tablet_id, writer] : _tablet_writers) {
377
0
        if (_partition_ids.contains(writer->partition_id())) {
378
0
            auto st = writer->close();
379
0
            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
0
            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
0
            need_wait_writers.insert(static_cast<DeltaWriter*>(writer.get()));
400
0
        } else {
401
0
            auto st = writer->cancel();
402
0
            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
0
            VLOG_PROGRESS << "cancel tablet writer successfully, tablet_id=" << tablet_id
409
0
                          << ", transaction_id=" << _txn_id;
410
0
        }
411
0
    }
412
413
0
    _write_single_replica = req.write_single_replica();
414
415
    // 2. wait all writer finished flush.
416
0
    for (auto* writer : need_wait_writers) {
417
0
        RETURN_IF_ERROR((writer->wait_flush()));
418
0
    }
419
420
    // 3. build rowset
421
0
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
422
0
        Status st = (*it)->build_rowset();
423
0
        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
0
        st = (*it)->submit_calc_delete_bitmap_task();
430
0
        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
0
        it++;
436
0
    }
437
438
    // 4. wait for delete bitmap calculation complete if necessary
439
0
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
440
0
        Status st = (*it)->wait_calc_delete_bitmap();
441
0
        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
0
        it++;
447
0
    }
448
449
    // 5. commit all writers
450
451
0
    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
0
        _commit_txn(writer, req, res);
455
0
    }
456
457
0
    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
0
    return Status::OK();
484
0
}
485
486
void TabletsChannel::_commit_txn(DeltaWriter* writer, const PTabletWriterAddBlockRequest& req,
487
0
                                 PTabletWriterAddBlockResult* res) {
488
0
    PSlaveTabletNodes slave_nodes;
489
0
    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
0
    Status st = writer->commit_txn(slave_nodes);
497
0
    if (st.ok()) [[likely]] {
498
0
        auto* tablet_vec = res->mutable_tablet_vec();
499
0
        PTabletInfo* tablet_info = tablet_vec->Add();
500
0
        tablet_info->set_tablet_id(writer->tablet_id());
501
        // unused required field.
502
0
        tablet_info->set_schema_hash(0);
503
0
        tablet_info->set_received_rows(writer->total_received_rows());
504
0
        tablet_info->set_num_rows_filtered(writer->num_rows_filtered());
505
0
        _total_received_rows += writer->total_received_rows();
506
0
        _num_rows_filtered += writer->num_rows_filtered();
507
0
    } else {
508
0
        _add_error_tablet(res->mutable_tablet_errors(), writer->tablet_id(), st);
509
0
    }
510
0
}
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
0
void BaseTabletsChannel::refresh_profile() {
523
0
    int64_t write_mem_usage = 0;
524
0
    int64_t flush_mem_usage = 0;
525
0
    int64_t max_tablet_mem_usage = 0;
526
0
    int64_t max_tablet_write_mem_usage = 0;
527
0
    int64_t max_tablet_flush_mem_usage = 0;
528
0
    {
529
0
        std::lock_guard<std::mutex> l(_tablet_writers_lock);
530
0
        for (auto&& [tablet_id, writer] : _tablet_writers) {
531
0
            int64_t write_mem = writer->mem_consumption(MemType::WRITE_FINISHED);
532
0
            write_mem_usage += write_mem;
533
0
            int64_t flush_mem = writer->mem_consumption(MemType::FLUSH);
534
0
            flush_mem_usage += flush_mem;
535
0
            if (write_mem > max_tablet_write_mem_usage) {
536
0
                max_tablet_write_mem_usage = write_mem;
537
0
            }
538
0
            if (flush_mem > max_tablet_flush_mem_usage) {
539
0
                max_tablet_flush_mem_usage = flush_mem;
540
0
            }
541
0
            if (write_mem + flush_mem > max_tablet_mem_usage) {
542
0
                max_tablet_mem_usage = write_mem + flush_mem;
543
0
            }
544
0
        }
545
0
    }
546
0
    COUNTER_SET(_memory_usage_counter, write_mem_usage + flush_mem_usage);
547
0
    COUNTER_SET(_write_memory_usage_counter, write_mem_usage);
548
0
    COUNTER_SET(_flush_memory_usage_counter, flush_mem_usage);
549
0
    COUNTER_SET(_max_tablet_memory_usage_counter, max_tablet_mem_usage);
550
0
    COUNTER_SET(_max_tablet_write_memory_usage_counter, max_tablet_write_mem_usage);
551
0
    COUNTER_SET(_max_tablet_flush_memory_usage_counter, max_tablet_flush_mem_usage);
552
0
}
553
554
0
Status BaseTabletsChannel::_open_all_writers(const PTabletWriterOpenRequest& request) {
555
0
    std::vector<SlotDescriptor*>* index_slots = nullptr;
556
0
    int32_t schema_hash = 0;
557
0
    for (const auto& index : _schema->indexes()) {
558
0
        if (index->index_id == _index_id) {
559
0
            index_slots = &index->slots;
560
0
            schema_hash = index->schema_hash;
561
0
            break;
562
0
        }
563
0
    }
564
0
    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
0
    int tablet_cnt = 0;
581
    // under _lock. no need _tablet_writers_lock again.
582
0
    for (const auto& tablet : request.tablets()) {
583
0
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
584
0
            continue;
585
0
        }
586
0
        tablet_cnt++;
587
0
        WriteRequest wrequest {
588
0
                .tablet_id = tablet.tablet_id(),
589
0
                .schema_hash = schema_hash,
590
0
                .txn_id = _txn_id,
591
0
                .txn_expiration = request.txn_expiration(), // Required by CLOUD.
592
0
                .index_id = request.index_id(),
593
0
                .partition_id = tablet.partition_id(),
594
0
                .load_id = request.id(),
595
0
                .tuple_desc = _tuple_desc,
596
0
                .slots = index_slots,
597
0
                .table_schema_param = _schema,
598
0
                .is_high_priority = _is_high_priority,
599
0
                .write_file_cache = request.write_file_cache(),
600
0
                .storage_vault_id = request.storage_vault_id(),
601
0
                .enable_table_memtable_backpressure = request.is_adaptive_random_bucket(),
602
0
        };
603
604
0
        auto delta_writer = create_delta_writer(wrequest);
605
0
        {
606
0
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
607
0
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
608
0
        }
609
0
    }
610
0
    _s_tablet_writer_count += _tablet_writers.size();
611
0
    DCHECK_EQ(_tablet_writers.size(), tablet_cnt);
612
0
    return Status::OK();
613
0
}
614
615
0
Status BaseTabletsChannel::cancel() {
616
0
    std::lock_guard<std::mutex> l(_lock);
617
0
    if (_state == kFinished) {
618
0
        return _close_status;
619
0
    }
620
0
    for (auto& it : _tablet_writers) {
621
0
        static_cast<void>(it.second->cancel());
622
0
    }
623
0
    _state = kFinished;
624
625
0
    return Status::OK();
626
0
}
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
0
std::string TabletsChannelKey::to_string() const {
637
0
    std::stringstream ss;
638
0
    ss << *this;
639
0
    return ss.str();
640
0
}
641
642
0
std::ostream& operator<<(std::ostream& os, const TabletsChannelKey& key) {
643
0
    os << "(load_id=" << key.id << ", index_id=" << key.index_id << ")";
644
0
    return os;
645
0
}
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
0
        PTabletWriterAddBlockResult* response) {
651
0
    Block send_data;
652
0
    [[maybe_unused]] size_t uncompressed_size = 0;
653
0
    [[maybe_unused]] int64_t uncompressed_time = 0;
654
0
    RETURN_IF_ERROR(send_data.deserialize(request.block(), &uncompressed_size, &uncompressed_time));
655
0
    int request_rows = request.is_adaptive_random_bucket() ? request.partition_ids_size()
656
0
                                                           : request.tablet_ids_size();
657
0
    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
0
    g_tablets_channel_send_data_allocated_size << send_data.allocated_bytes();
666
0
    Defer defer {
667
0
            [&]() { g_tablets_channel_send_data_allocated_size << -send_data.allocated_bytes(); }};
668
669
0
    auto write_tablet_data = [&](int64_t tablet_id,
670
0
                                 std::function<Status(BaseDeltaWriter * writer)> write_func) {
671
0
        google::protobuf::RepeatedPtrField<PTabletError>* tablet_errors =
672
0
                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
0
        BaseDeltaWriter* tablet_writer = nullptr;
677
0
        {
678
0
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
679
0
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
680
0
            if (tablet_writer_it == _tablet_writers.end()) {
681
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
682
0
            }
683
0
            tablet_writer = tablet_writer_it->second.get();
684
0
        }
685
686
0
        Status st = write_func(tablet_writer);
687
0
        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
0
        return Status::OK();
701
0
    };
702
703
0
    SCOPED_TIMER(_write_block_timer);
704
0
    auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
705
0
    for (const auto& tablet_to_rowidxs_it : tablet_to_rowidxs) {
706
0
        bool memtable_flushed = false;
707
0
        RETURN_IF_ERROR(write_tablet_data(tablet_to_rowidxs_it.first, [&](BaseDeltaWriter* writer) {
708
0
            return writer->write(&send_data, tablet_to_rowidxs_it.second, &memtable_flushed);
709
0
        }));
710
711
0
        BaseDeltaWriter* tablet_writer = nullptr;
712
0
        {
713
0
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
714
0
            auto tablet_writer_it = _tablet_writers.find(tablet_to_rowidxs_it.first);
715
0
            if (tablet_writer_it != _tablet_writers.end()) {
716
0
                tablet_writer = tablet_writer_it->second.get();
717
0
            }
718
0
        }
719
0
        if (tablet_writer != nullptr) {
720
0
            tablet_writer->set_tablet_load_rowset_num_info(tablet_load_infos);
721
0
        }
722
0
    }
723
724
0
    {
725
0
        std::lock_guard<std::mutex> l(_lock);
726
0
        _next_seqs[request.sender_id()] = cur_seq + 1;
727
0
    }
728
0
    return Status::OK();
729
0
}
730
731
0
std::shared_ptr<std::mutex> BaseTabletsChannel::_get_partition_route_lock(int64_t partition_id) {
732
0
    std::lock_guard<std::mutex> l(_partition_route_locks_lock);
733
0
    auto& lock = _partition_route_locks[partition_id];
734
0
    if (lock == nullptr) {
735
0
        lock = std::make_shared<std::mutex>();
736
0
    }
737
0
    return lock;
738
0
}
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
0
        PTabletWriterAddBlockResult* response) {
744
0
    Block send_data;
745
0
    [[maybe_unused]] size_t uncompressed_size = 0;
746
0
    [[maybe_unused]] int64_t uncompressed_time = 0;
747
0
    RETURN_IF_ERROR(send_data.deserialize(request.block(), &uncompressed_size, &uncompressed_time));
748
0
    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
0
    {
757
0
        std::lock_guard<std::mutex> l(_lock);
758
0
        for (const auto& [partition_id, _] : partition_to_rowidxs) {
759
0
            _partition_ids.emplace(partition_id);
760
0
        }
761
0
    }
762
763
0
    g_tablets_channel_send_data_allocated_size << send_data.allocated_bytes();
764
0
    Defer defer {
765
0
            [&]() { g_tablets_channel_send_data_allocated_size << -send_data.allocated_bytes(); }};
766
767
0
    auto* tablet_errors = response->mutable_tablet_errors();
768
0
    auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
769
770
0
    auto write_partition_data = [&](int64_t partition_id,
771
0
                                    const DorisVector<uint32_t>& row_idxs) -> Status {
772
0
        auto partition_lock = _get_partition_route_lock(partition_id);
773
0
        std::lock_guard<std::mutex> partition_guard(*partition_lock);
774
0
        int64_t tablet_id = -1;
775
0
        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
0
        tablet_id = _adaptive_random_bucket_state->current_tablet(partition_id);
782
0
        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
0
        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
0
        {
796
0
            std::shared_lock<std::shared_mutex> broken_rlock(_broken_tablets_lock);
797
0
            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
0
        }
805
806
0
        BaseDeltaWriter* tablet_writer = nullptr;
807
0
        {
808
0
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
809
0
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
810
0
            if (tablet_writer_it == _tablet_writers.end()) {
811
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
812
0
            }
813
0
            tablet_writer = tablet_writer_it->second.get();
814
0
        }
815
0
        RETURN_IF_ERROR(_prepare_adaptive_random_bucket_writer(tablet_writer));
816
817
0
        bool memtable_flushed = false;
818
0
        Status st = tablet_writer->write(&send_data, row_idxs, &memtable_flushed);
819
0
        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
0
        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
0
        if (memtable_flushed) {
839
0
            _adaptive_random_bucket_state->rotate_by_tablet(partition_id, tablet_id);
840
0
        }
841
0
        tablet_writer->set_tablet_load_rowset_num_info(tablet_load_infos);
842
0
        return Status::OK();
843
0
    };
844
845
0
    SCOPED_TIMER(_write_block_timer);
846
0
    for (const auto& [partition_id, row_idxs] : partition_to_rowidxs) {
847
0
        RETURN_IF_ERROR(write_partition_data(partition_id, row_idxs));
848
0
    }
849
850
0
    {
851
0
        std::lock_guard<std::mutex> l(_lock);
852
0
        _next_seqs[request.sender_id()] = cur_seq + 1;
853
0
    }
854
0
    return Status::OK();
855
0
}
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
0
        std::unordered_map<int64_t, DorisVector<uint32_t>>* partition_to_rowidxs) {
864
0
    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
0
    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
0
    for (uint32_t i = 0; i < request.partition_ids_size(); ++i) {
877
0
        int64_t partition_id = request.partition_ids(i);
878
0
        auto it = partition_to_rowidxs->find(partition_id);
879
0
        if (it == partition_to_rowidxs->end()) {
880
0
            partition_to_rowidxs->emplace(partition_id, std::initializer_list<uint32_t> {i});
881
0
        } else {
882
0
            it->second.emplace_back(i);
883
0
        }
884
0
    }
885
0
    return Status::OK();
886
0
}
887
888
Status TabletsChannel::add_batch(const PTabletWriterAddBlockRequest& request,
889
0
                                 PTabletWriterAddBlockResult* response) {
890
0
    SCOPED_TIMER(_add_batch_timer);
891
0
    int64_t cur_seq = 0;
892
0
    if (_add_batch_number_counter) {
893
0
        _add_batch_number_counter->update(1);
894
0
    }
895
896
0
    auto status = _get_current_seq(cur_seq, request);
897
0
    if (UNLIKELY(!status.ok())) {
898
0
        return status;
899
0
    }
900
901
0
    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
0
    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
0
    std::unordered_map<int64_t /* tablet_id */, DorisVector<uint32_t> /* row index */>
919
0
            tablet_to_rowidxs;
920
0
    _build_tablet_to_rowidxs(request, &tablet_to_rowidxs);
921
0
    return _write_block_data(request, cur_seq, tablet_to_rowidxs, response);
922
0
}
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
0
bool BaseTabletsChannel::_is_broken_tablet(int64_t tablet_id) const {
930
0
    return _broken_tablets.find(tablet_id) != _broken_tablets.end();
931
0
}
932
933
void BaseTabletsChannel::_build_tablet_to_rowidxs(
934
        const PTabletWriterAddBlockRequest& request,
935
0
        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
0
    std::shared_lock<std::shared_mutex> rlock(_broken_tablets_lock);
940
0
    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
0
    for (uint32_t i = 0; i < request.tablet_ids_size(); ++i) {
947
0
        int64_t tablet_id = request.tablet_ids(i);
948
0
        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
0
        auto it = tablet_to_rowidxs->find(tablet_id);
954
0
        if (it == tablet_to_rowidxs->end()) {
955
0
            tablet_to_rowidxs->emplace(tablet_id, std::initializer_list<uint32_t> {i});
956
0
        } else {
957
0
            it->second.emplace_back(i);
958
0
        }
959
0
    }
960
0
}
961
962
} // namespace doris