Coverage Report

Created: 2026-04-28 15:58

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 <set>
33
#include <thread>
34
#include <utility>
35
36
#ifdef DEBUG
37
#include <unordered_set>
38
#endif
39
40
#include "common/logging.h"
41
#include "common/metrics/doris_metrics.h"
42
#include "common/metrics/metrics.h"
43
#include "core/block/block.h"
44
#include "load/channel/load_channel.h"
45
#include "load/delta_writer/delta_writer.h"
46
#include "storage/storage_engine.h"
47
#include "storage/tablet_info.h"
48
#include "storage/txn/txn_manager.h"
49
#include "util/defer_op.h"
50
51
namespace doris {
52
class SlotDescriptor;
53
54
bvar::Adder<int64_t> g_tablets_channel_send_data_allocated_size(
55
        "tablets_channel_send_data_allocated_size");
56
57
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(tablet_writer_count, MetricUnit::NOUNIT);
58
59
std::atomic<uint64_t> BaseTabletsChannel::_s_tablet_writer_count;
60
61
BaseTabletsChannel::BaseTabletsChannel(const TabletsChannelKey& key, const UniqueId& load_id,
62
                                       bool is_high_priority, RuntimeProfile* profile)
63
30.1k
        : _key(key),
64
30.1k
          _state(kInitialized),
65
30.1k
          _load_id(load_id),
66
30.1k
          _closed_senders(64),
67
30.1k
          _is_high_priority(is_high_priority) {
68
30.1k
    static std::once_flag once_flag;
69
30.1k
    if (profile != nullptr) {
70
3
        _init_profile(profile);
71
3
    }
72
30.1k
    std::call_once(once_flag, [] {
73
5
        REGISTER_HOOK_METRIC(tablet_writer_count, [&]() { return _s_tablet_writer_count.load(); });
74
5
    });
75
30.1k
}
76
77
TabletsChannel::TabletsChannel(StorageEngine& engine, const TabletsChannelKey& key,
78
                               const UniqueId& load_id, bool is_high_priority,
79
                               RuntimeProfile* profile)
80
440
        : BaseTabletsChannel(key, load_id, is_high_priority, profile), _engine(engine) {}
81
82
30.1k
BaseTabletsChannel::~BaseTabletsChannel() {
83
30.1k
    _s_tablet_writer_count -= _tablet_writers.size();
84
30.1k
}
85
86
TabletsChannel::~TabletsChannel() = default;
87
88
Status BaseTabletsChannel::_get_current_seq(int64_t& cur_seq,
89
33.1k
                                            const PTabletWriterAddBlockRequest& request) {
90
33.1k
    std::lock_guard<std::mutex> l(_lock);
91
33.1k
    if (_state != kOpened) {
92
0
        return _state == kFinished ? _close_status
93
0
                                   : Status::InternalError("TabletsChannel {} state: {}",
94
0
                                                           _key.to_string(), _state);
95
0
    }
96
33.1k
    cur_seq = _next_seqs[request.sender_id()];
97
    // check packet
98
33.1k
    if (request.packet_seq() > cur_seq) {
99
0
        LOG(WARNING) << "lost data packet, expect_seq=" << cur_seq
100
0
                     << ", recept_seq=" << request.packet_seq();
101
0
        return Status::InternalError("lost data packet");
102
0
    }
103
33.1k
    return Status::OK();
104
33.1k
}
105
106
3
void BaseTabletsChannel::_init_profile(RuntimeProfile* profile) {
107
3
    DCHECK(profile != nullptr);
108
3
    _profile =
109
3
            profile->create_child(fmt::format("TabletsChannel {}", _key.to_string()), true, true);
110
3
    _add_batch_number_counter = ADD_COUNTER(_profile, "NumberBatchAdded", TUnit::UNIT);
111
112
3
    auto* memory_usage = _profile->create_child("PeakMemoryUsage", true, true);
113
3
    _add_batch_timer = ADD_TIMER(_profile, "AddBatchTime");
114
3
    _write_block_timer = ADD_TIMER(_profile, "WriteBlockTime");
115
3
    _incremental_open_timer = ADD_TIMER(_profile, "IncrementalOpenTabletTime");
116
3
    _memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Total", TUnit::BYTES);
117
3
    _write_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Write", TUnit::BYTES);
118
3
    _flush_memory_usage_counter = memory_usage->AddHighWaterMarkCounter("Flush", TUnit::BYTES);
119
3
    _max_tablet_memory_usage_counter =
120
3
            memory_usage->AddHighWaterMarkCounter("MaxTablet", TUnit::BYTES);
121
3
    _max_tablet_write_memory_usage_counter =
122
3
            memory_usage->AddHighWaterMarkCounter("MaxTabletWrite", TUnit::BYTES);
123
3
    _max_tablet_flush_memory_usage_counter =
124
3
            memory_usage->AddHighWaterMarkCounter("MaxTabletFlush", TUnit::BYTES);
125
3
}
126
127
0
void TabletsChannel::_init_profile(RuntimeProfile* profile) {
128
0
    DCHECK(profile != nullptr);
129
0
    BaseTabletsChannel::_init_profile(profile);
130
0
    _slave_replica_timer = ADD_TIMER(_profile, "SlaveReplicaTime");
131
0
}
132
133
55.6k
Status BaseTabletsChannel::open(const PTabletWriterOpenRequest& request) {
134
55.6k
    std::lock_guard<std::mutex> l(_lock);
135
    // if _state is kOpened, it's a normal case, already open by other sender
136
    // if _state is kFinished, already cancelled by other sender
137
55.6k
    if (_state == kOpened || _state == kFinished) {
138
25.5k
        return Status::OK();
139
25.5k
    }
140
30.1k
    _txn_id = request.txn_id();
141
30.1k
    _index_id = request.index_id();
142
30.1k
    _schema = std::make_shared<OlapTableSchemaParam>();
143
30.1k
    RETURN_IF_ERROR(_schema->init(request.schema()));
144
30.1k
    _tuple_desc = _schema->tuple_desc();
145
146
30.1k
    int max_sender = request.num_senders();
147
    /*
148
     * a tablets channel in reciever is related to a bulk of VNodeChannel of sender. each instance one or none.
149
     * there are two possibilities:
150
     *  1. there's partitions originally broadcasted by FE. so all sender(instance) know it at start. and open() will be 
151
     *     called directly, not by incremental_open(). and after _state changes to kOpened. _open_by_incremental will never 
152
     *     be true. in this case, _num_remaining_senders will keep same with senders number. when all sender sent close rpc,
153
     *     the tablets channel will close. and if for auto partition table, these channel's closing will hang on reciever and
154
     *     return together to avoid close-then-incremental-open problem.
155
     *  2. this tablets channel is opened by incremental_open of sender's sink node. so only this sender will know this partition
156
     *     (this TabletsChannel) at that time. and we are not sure how many sender will know in the end. it depends on data
157
     *     distribution. in this situation open() is called by incremental_open() at first time. so _open_by_incremental is true.
158
     *     then _num_remaining_senders will not be set here. but inc every time when incremental_open() called. so it's dynamic
159
     *     and also need same number of senders' close to close. but will not hang.
160
     */
161
30.1k
    if (_open_by_incremental) {
162
0
        DCHECK(_num_remaining_senders == 0) << _num_remaining_senders;
163
30.1k
    } else {
164
30.1k
        _num_remaining_senders = max_sender;
165
30.1k
    }
166
30.1k
    LOG(INFO) << fmt::format(
167
30.1k
            "open tablets channel {}, tablets num: {} timeout(s): {}, init senders {} with "
168
30.1k
            "incremental {}",
169
30.1k
            _key.to_string(), request.tablets().size(), request.load_channel_timeout_s(),
170
30.1k
            _num_remaining_senders, _open_by_incremental ? "on" : "off");
171
    // just use max_sender no matter incremental or not cuz we dont know how many senders will open.
172
30.1k
    _next_seqs.resize(max_sender, 0);
173
30.1k
    _closed_senders.Reset(max_sender);
174
175
30.1k
    RETURN_IF_ERROR(_open_all_writers(request));
176
177
30.1k
    _state = kOpened;
178
30.1k
    return Status::OK();
179
30.1k
}
180
181
179
Status BaseTabletsChannel::incremental_open(const PTabletWriterOpenRequest& params) {
182
179
    SCOPED_TIMER(_incremental_open_timer);
183
184
    // current node first opened by incremental open
185
179
    if (_state == kInitialized) {
186
0
        _open_by_incremental = true;
187
0
        RETURN_IF_ERROR(open(params));
188
0
    }
189
190
179
    std::lock_guard<std::mutex> l(_lock);
191
192
    // one sender may incremental_open many times. but only close one time. so dont count duplicately.
193
179
    if (_open_by_incremental) {
194
0
        if (params.has_sender_id() && !_recieved_senders.contains(params.sender_id())) {
195
0
            _recieved_senders.insert(params.sender_id());
196
0
            _num_remaining_senders++;
197
0
        } else if (!params.has_sender_id()) { // for compatible
198
0
            _num_remaining_senders++;
199
0
        }
200
0
        VLOG_DEBUG << fmt::format("txn {}: TabletsChannel {} inc senders to {}", _txn_id, _index_id,
201
0
                                  _num_remaining_senders);
202
0
    }
203
204
179
    std::vector<SlotDescriptor*>* index_slots = nullptr;
205
179
    int32_t schema_hash = 0;
206
179
    for (const auto& index : _schema->indexes()) {
207
179
        if (index->index_id == _index_id) {
208
179
            index_slots = &index->slots;
209
179
            schema_hash = index->schema_hash;
210
179
            break;
211
179
        }
212
179
    }
213
179
    if (index_slots == nullptr) {
214
0
        return Status::InternalError("unknown index id, key={}", _key.to_string());
215
0
    }
216
    // update tablets
217
179
    size_t incremental_tablet_num = 0;
218
179
    std::stringstream ss;
219
179
    ss << "LocalTabletsChannel txn_id: " << _txn_id << " load_id: " << print_id(params.id())
220
179
       << " incremental open delta writer: ";
221
222
    // every change will hold _lock. this find in under _lock too. so no need _tablet_writers_lock again.
223
6.57k
    for (const auto& tablet : params.tablets()) {
224
6.57k
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
225
96
            continue;
226
96
        }
227
6.47k
        incremental_tablet_num++;
228
229
6.47k
        WriteRequest wrequest;
230
6.47k
        wrequest.index_id = params.index_id();
231
6.47k
        wrequest.tablet_id = tablet.tablet_id();
232
6.47k
        wrequest.schema_hash = schema_hash;
233
6.47k
        wrequest.txn_id = _txn_id;
234
6.47k
        wrequest.partition_id = tablet.partition_id();
235
6.47k
        wrequest.load_id = params.id();
236
6.47k
        wrequest.tuple_desc = _tuple_desc;
237
6.47k
        wrequest.slots = index_slots;
238
6.47k
        wrequest.is_high_priority = _is_high_priority;
239
6.47k
        wrequest.table_schema_param = _schema;
240
6.47k
        wrequest.txn_expiration = params.txn_expiration(); // Required by CLOUD.
241
6.47k
        wrequest.storage_vault_id = params.storage_vault_id();
242
243
6.47k
        auto delta_writer = create_delta_writer(wrequest);
244
6.47k
        {
245
            // here we modify _tablet_writers. so need lock.
246
6.47k
            std::lock_guard<std::mutex> lt(_tablet_writers_lock);
247
6.47k
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
248
6.47k
        }
249
250
6.47k
        ss << "[" << tablet.tablet_id() << "]";
251
6.47k
    }
252
253
179
    _s_tablet_writer_count += incremental_tablet_num;
254
179
    LOG(INFO) << ss.str();
255
256
179
    _state = kOpened;
257
179
    return Status::OK();
258
179
}
259
260
3.16k
std::unique_ptr<BaseDeltaWriter> TabletsChannel::create_delta_writer(const WriteRequest& request) {
261
3.16k
    return std::make_unique<DeltaWriter>(_engine, request, _profile, _load_id);
262
3.16k
}
263
264
Status TabletsChannel::close(LoadChannel* parent, const PTabletWriterAddBlockRequest& req,
265
1.02k
                             PTabletWriterAddBlockResult* res, bool* finished) {
266
1.02k
    int sender_id = req.sender_id();
267
1.02k
    int64_t backend_id = req.backend_id();
268
1.02k
    const auto& partition_ids = req.partition_ids();
269
1.02k
    auto* tablet_errors = res->mutable_tablet_errors();
270
1.02k
    std::lock_guard<std::mutex> l(_lock);
271
1.02k
    if (_state == kFinished) {
272
0
        return _close_status;
273
0
    }
274
1.02k
    if (_closed_senders.Get(sender_id)) {
275
        // Double close from one sender, just return OK
276
0
        *finished = (_num_remaining_senders == 0);
277
0
        return _close_status;
278
0
    }
279
280
1.02k
    for (auto pid : partition_ids) {
281
374
        _partition_ids.emplace(pid);
282
374
    }
283
1.02k
    _closed_senders.Set(sender_id, true);
284
1.02k
    _num_remaining_senders--;
285
1.02k
    *finished = (_num_remaining_senders == 0);
286
287
1.02k
    LOG(INFO) << fmt::format(
288
1.02k
            "txn {}: close tablets channel of index {} , sender id: {}, backend {}, remain "
289
1.02k
            "senders: {}",
290
1.02k
            _txn_id, _index_id, sender_id, backend_id, _num_remaining_senders);
291
292
1.02k
    if (!*finished) {
293
588
        return Status::OK();
294
588
    }
295
296
440
    _state = kFinished;
297
    // All senders are closed
298
    // 1. close all delta writers
299
440
    std::set<DeltaWriter*> need_wait_writers;
300
    // under _lock. no need _tablet_writers_lock again.
301
3.16k
    for (auto&& [tablet_id, writer] : _tablet_writers) {
302
3.16k
        if (_partition_ids.contains(writer->partition_id())) {
303
2.13k
            auto st = writer->close();
304
2.13k
            if (!st.ok()) {
305
0
                auto err_msg = fmt::format(
306
0
                        "close tablet writer failed, tablet_id={}, "
307
0
                        "transaction_id={}, err={}",
308
0
                        tablet_id, _txn_id, st.to_string());
309
0
                LOG(WARNING) << err_msg;
310
0
                PTabletError* tablet_error = tablet_errors->Add();
311
0
                tablet_error->set_tablet_id(tablet_id);
312
0
                tablet_error->set_msg(st.to_string());
313
                // just skip this tablet(writer) and continue to close others
314
0
                continue;
315
0
            }
316
            // tablet writer in `_broken_tablets` should not call `build_rowset` and
317
            // `commit_txn` method, after that, the publish-version task will success,
318
            // which can cause the replica inconsistency.
319
2.13k
            if (_is_broken_tablet(writer->tablet_id())) {
320
0
                LOG(WARNING) << "SHOULD NOT HAPPEN, tablet writer is broken but not cancelled"
321
0
                             << ", tablet_id=" << tablet_id << ", transaction_id=" << _txn_id;
322
0
                continue;
323
0
            }
324
2.13k
            need_wait_writers.insert(static_cast<DeltaWriter*>(writer.get()));
325
2.13k
        } else {
326
1.03k
            auto st = writer->cancel();
327
1.03k
            if (!st.ok()) {
328
0
                LOG(WARNING) << "cancel tablet writer failed, tablet_id=" << tablet_id
329
0
                             << ", transaction_id=" << _txn_id;
330
                // just skip this tablet(writer) and continue to close others
331
0
                continue;
332
0
            }
333
1.03k
            VLOG_PROGRESS << "cancel tablet writer successfully, tablet_id=" << tablet_id
334
0
                          << ", transaction_id=" << _txn_id;
335
1.03k
        }
336
3.16k
    }
337
338
440
    _write_single_replica = req.write_single_replica();
339
340
    // 2. wait all writer finished flush.
341
2.13k
    for (auto* writer : need_wait_writers) {
342
2.13k
        RETURN_IF_ERROR((writer->wait_flush()));
343
2.13k
    }
344
345
    // 3. build rowset
346
2.57k
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
347
2.13k
        Status st = (*it)->build_rowset();
348
2.13k
        if (!st.ok()) {
349
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
350
0
            it = need_wait_writers.erase(it);
351
0
            continue;
352
0
        }
353
        // 3.1 calculate delete bitmap for Unique Key MoW tables
354
2.13k
        st = (*it)->submit_calc_delete_bitmap_task();
355
2.13k
        if (!st.ok()) {
356
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
357
0
            it = need_wait_writers.erase(it);
358
0
            continue;
359
0
        }
360
2.13k
        it++;
361
2.13k
    }
362
363
    // 4. wait for delete bitmap calculation complete if necessary
364
2.57k
    for (auto it = need_wait_writers.begin(); it != need_wait_writers.end();) {
365
2.13k
        Status st = (*it)->wait_calc_delete_bitmap();
366
2.13k
        if (!st.ok()) {
367
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
368
0
            it = need_wait_writers.erase(it);
369
0
            continue;
370
0
        }
371
2.13k
        it++;
372
2.13k
    }
373
374
    // 5. commit all writers
375
376
2.13k
    for (auto* writer : need_wait_writers) {
377
        // close may return failed, but no need to handle it here.
378
        // tablet_vec will only contains success tablet, and then let FE judge it.
379
2.13k
        _commit_txn(writer, req, res);
380
2.13k
    }
381
382
440
    if (_write_single_replica) {
383
0
        auto* success_slave_tablet_node_ids = res->mutable_success_slave_tablet_node_ids();
384
        // The operation waiting for all slave replicas to complete must end before the timeout,
385
        // so that there is enough time to collect completed replica. Otherwise, the task may
386
        // timeout and fail even though most of the replicas are completed. Here we set 0.9
387
        // times the timeout as the maximum waiting time.
388
0
        SCOPED_TIMER(_slave_replica_timer);
389
0
        while (!need_wait_writers.empty() &&
390
0
               (time(nullptr) - parent->last_updated_time()) < (parent->timeout() * 0.9)) {
391
0
            std::set<DeltaWriter*>::iterator it;
392
0
            for (it = need_wait_writers.begin(); it != need_wait_writers.end();) {
393
0
                bool is_done = (*it)->check_slave_replicas_done(success_slave_tablet_node_ids);
394
0
                if (is_done) {
395
0
                    need_wait_writers.erase(it++);
396
0
                } else {
397
0
                    it++;
398
0
                }
399
0
            }
400
0
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
401
0
        }
402
0
        for (auto* writer : need_wait_writers) {
403
0
            writer->add_finished_slave_replicas(success_slave_tablet_node_ids);
404
0
        }
405
0
        _engine.txn_manager()->clear_txn_tablet_delta_writer(_txn_id);
406
0
    }
407
408
440
    return Status::OK();
409
440
}
410
411
void TabletsChannel::_commit_txn(DeltaWriter* writer, const PTabletWriterAddBlockRequest& req,
412
2.13k
                                 PTabletWriterAddBlockResult* res) {
413
2.13k
    PSlaveTabletNodes slave_nodes;
414
2.13k
    if (_write_single_replica) {
415
0
        auto& nodes_map = req.slave_tablet_nodes();
416
0
        auto it = nodes_map.find(writer->tablet_id());
417
0
        if (it != nodes_map.end()) {
418
0
            slave_nodes = it->second;
419
0
        }
420
0
    }
421
2.13k
    Status st = writer->commit_txn(slave_nodes);
422
2.13k
    if (st.ok()) [[likely]] {
423
2.13k
        auto* tablet_vec = res->mutable_tablet_vec();
424
2.13k
        PTabletInfo* tablet_info = tablet_vec->Add();
425
2.13k
        tablet_info->set_tablet_id(writer->tablet_id());
426
        // unused required field.
427
2.13k
        tablet_info->set_schema_hash(0);
428
2.13k
        tablet_info->set_received_rows(writer->total_received_rows());
429
2.13k
        tablet_info->set_num_rows_filtered(writer->num_rows_filtered());
430
2.13k
        _total_received_rows += writer->total_received_rows();
431
2.13k
        _num_rows_filtered += writer->num_rows_filtered();
432
2.13k
    } else {
433
0
        _add_error_tablet(res->mutable_tablet_errors(), writer->tablet_id(), st);
434
0
    }
435
2.13k
}
436
437
void BaseTabletsChannel::_add_error_tablet(
438
        google::protobuf::RepeatedPtrField<PTabletError>* tablet_errors, int64_t tablet_id,
439
0
        Status error) const {
440
0
    PTabletError* tablet_error = tablet_errors->Add();
441
0
    tablet_error->set_tablet_id(tablet_id);
442
0
    tablet_error->set_msg(error.to_string());
443
0
    VLOG_PROGRESS << "close wait failed tablet " << tablet_id << " transaction_id " << _txn_id
444
0
                  << "err msg " << error;
445
0
}
446
447
15
void BaseTabletsChannel::refresh_profile() {
448
15
    int64_t write_mem_usage = 0;
449
15
    int64_t flush_mem_usage = 0;
450
15
    int64_t max_tablet_mem_usage = 0;
451
15
    int64_t max_tablet_write_mem_usage = 0;
452
15
    int64_t max_tablet_flush_mem_usage = 0;
453
15
    {
454
15
        std::lock_guard<std::mutex> l(_tablet_writers_lock);
455
150
        for (auto&& [tablet_id, writer] : _tablet_writers) {
456
150
            int64_t write_mem = writer->mem_consumption(MemType::WRITE_FINISHED);
457
150
            write_mem_usage += write_mem;
458
150
            int64_t flush_mem = writer->mem_consumption(MemType::FLUSH);
459
150
            flush_mem_usage += flush_mem;
460
150
            if (write_mem > max_tablet_write_mem_usage) {
461
0
                max_tablet_write_mem_usage = write_mem;
462
0
            }
463
150
            if (flush_mem > max_tablet_flush_mem_usage) {
464
0
                max_tablet_flush_mem_usage = flush_mem;
465
0
            }
466
150
            if (write_mem + flush_mem > max_tablet_mem_usage) {
467
0
                max_tablet_mem_usage = write_mem + flush_mem;
468
0
            }
469
150
        }
470
15
    }
471
15
    COUNTER_SET(_memory_usage_counter, write_mem_usage + flush_mem_usage);
472
15
    COUNTER_SET(_write_memory_usage_counter, write_mem_usage);
473
15
    COUNTER_SET(_flush_memory_usage_counter, flush_mem_usage);
474
15
    COUNTER_SET(_max_tablet_memory_usage_counter, max_tablet_mem_usage);
475
15
    COUNTER_SET(_max_tablet_write_memory_usage_counter, max_tablet_write_mem_usage);
476
15
    COUNTER_SET(_max_tablet_flush_memory_usage_counter, max_tablet_flush_mem_usage);
477
15
}
478
479
30.1k
Status BaseTabletsChannel::_open_all_writers(const PTabletWriterOpenRequest& request) {
480
30.1k
    std::vector<SlotDescriptor*>* index_slots = nullptr;
481
30.1k
    int32_t schema_hash = 0;
482
34.1k
    for (const auto& index : _schema->indexes()) {
483
34.1k
        if (index->index_id == _index_id) {
484
30.1k
            index_slots = &index->slots;
485
30.1k
            schema_hash = index->schema_hash;
486
30.1k
            break;
487
30.1k
        }
488
34.1k
    }
489
30.1k
    if (index_slots == nullptr) {
490
0
        return Status::InternalError("unknown index id, key={}", _key.to_string());
491
0
    }
492
493
#ifdef DEBUG
494
    // check: tablet ids should be unique
495
    {
496
        std::unordered_set<int64_t> tablet_ids;
497
        for (const auto& tablet : request.tablets()) {
498
            CHECK(tablet_ids.count(tablet.tablet_id()) == 0)
499
                    << "found duplicate tablet id: " << tablet.tablet_id();
500
            tablet_ids.insert(tablet.tablet_id());
501
        }
502
    }
503
#endif
504
505
30.1k
    int tablet_cnt = 0;
506
    // under _lock. no need _tablet_writers_lock again.
507
256k
    for (const auto& tablet : request.tablets()) {
508
256k
        if (_tablet_writers.find(tablet.tablet_id()) != _tablet_writers.end()) {
509
0
            continue;
510
0
        }
511
256k
        tablet_cnt++;
512
256k
        WriteRequest wrequest {
513
256k
                .tablet_id = tablet.tablet_id(),
514
256k
                .schema_hash = schema_hash,
515
256k
                .txn_id = _txn_id,
516
256k
                .txn_expiration = request.txn_expiration(), // Required by CLOUD.
517
256k
                .index_id = request.index_id(),
518
256k
                .partition_id = tablet.partition_id(),
519
256k
                .load_id = request.id(),
520
256k
                .tuple_desc = _tuple_desc,
521
256k
                .slots = index_slots,
522
256k
                .table_schema_param = _schema,
523
256k
                .is_high_priority = _is_high_priority,
524
256k
                .write_file_cache = request.write_file_cache(),
525
256k
                .storage_vault_id = request.storage_vault_id(),
526
256k
        };
527
528
256k
        auto delta_writer = create_delta_writer(wrequest);
529
256k
        {
530
256k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
531
256k
            _tablet_writers.emplace(tablet.tablet_id(), std::move(delta_writer));
532
256k
        }
533
256k
    }
534
30.1k
    _s_tablet_writer_count += _tablet_writers.size();
535
30.1k
    DCHECK_EQ(_tablet_writers.size(), tablet_cnt);
536
30.1k
    return Status::OK();
537
30.1k
}
538
539
132
Status BaseTabletsChannel::cancel() {
540
132
    std::lock_guard<std::mutex> l(_lock);
541
132
    if (_state == kFinished) {
542
97
        return _close_status;
543
97
    }
544
1.41k
    for (auto& it : _tablet_writers) {
545
1.41k
        static_cast<void>(it.second->cancel());
546
1.41k
    }
547
35
    _state = kFinished;
548
549
35
    return Status::OK();
550
132
}
551
552
0
Status TabletsChannel::cancel() {
553
0
    RETURN_IF_ERROR(BaseTabletsChannel::cancel());
554
0
    if (_write_single_replica) {
555
0
        _engine.txn_manager()->clear_txn_tablet_delta_writer(_txn_id);
556
0
    }
557
0
    return Status::OK();
558
0
}
559
560
30.1k
std::string TabletsChannelKey::to_string() const {
561
30.1k
    std::stringstream ss;
562
30.1k
    ss << *this;
563
30.1k
    return ss.str();
564
30.1k
}
565
566
84.6k
std::ostream& operator<<(std::ostream& os, const TabletsChannelKey& key) {
567
84.6k
    os << "(load_id=" << key.id << ", index_id=" << key.index_id << ")";
568
84.6k
    return os;
569
84.6k
}
570
571
Status BaseTabletsChannel::_write_block_data(
572
        const PTabletWriterAddBlockRequest& request, int64_t cur_seq,
573
        std::unordered_map<int64_t, DorisVector<uint32_t>>& tablet_to_rowidxs,
574
33.1k
        PTabletWriterAddBlockResult* response) {
575
33.1k
    Block send_data;
576
33.1k
    [[maybe_unused]] size_t uncompressed_size = 0;
577
33.1k
    [[maybe_unused]] int64_t uncompressed_time = 0;
578
33.1k
    RETURN_IF_ERROR(send_data.deserialize(request.block(), &uncompressed_size, &uncompressed_time));
579
18.4E
    CHECK(send_data.rows() == request.tablet_ids_size())
580
18.4E
            << "block rows: " << send_data.rows()
581
18.4E
            << ", tablet_ids_size: " << request.tablet_ids_size();
582
583
33.1k
    g_tablets_channel_send_data_allocated_size << send_data.allocated_bytes();
584
33.1k
    Defer defer {
585
33.1k
            [&]() { g_tablets_channel_send_data_allocated_size << -send_data.allocated_bytes(); }};
586
587
33.1k
    auto write_tablet_data = [&](int64_t tablet_id,
588
115k
                                 std::function<Status(BaseDeltaWriter * writer)> write_func) {
589
115k
        google::protobuf::RepeatedPtrField<PTabletError>* tablet_errors =
590
115k
                response->mutable_tablet_errors();
591
592
        // add_batch may concurrency with inc_open but not under _lock.
593
        // so need to protect it with _tablet_writers_lock.
594
115k
        decltype(_tablet_writers.find(tablet_id)) tablet_writer_it;
595
115k
        {
596
115k
            std::lock_guard<std::mutex> l(_tablet_writers_lock);
597
115k
            tablet_writer_it = _tablet_writers.find(tablet_id);
598
115k
            if (tablet_writer_it == _tablet_writers.end()) {
599
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
600
0
            }
601
115k
        }
602
603
115k
        Status st = write_func(tablet_writer_it->second.get());
604
115k
        if (!st.ok()) {
605
0
            auto err_msg =
606
0
                    fmt::format("tablet writer write failed, tablet_id={}, txn_id={}, err={}",
607
0
                                tablet_id, _txn_id, st.to_string());
608
0
            LOG(WARNING) << err_msg;
609
0
            PTabletError* error = tablet_errors->Add();
610
0
            error->set_tablet_id(tablet_id);
611
0
            error->set_msg(err_msg);
612
0
            static_cast<void>(tablet_writer_it->second->cancel_with_status(st));
613
0
            _add_broken_tablet(tablet_id);
614
            // continue write to other tablet.
615
            // the error will return back to sender.
616
0
        }
617
115k
        return Status::OK();
618
115k
    };
619
620
33.1k
    SCOPED_TIMER(_write_block_timer);
621
33.1k
    auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
622
115k
    for (const auto& tablet_to_rowidxs_it : tablet_to_rowidxs) {
623
115k
        RETURN_IF_ERROR(write_tablet_data(tablet_to_rowidxs_it.first, [&](BaseDeltaWriter* writer) {
624
115k
            return writer->write(&send_data, tablet_to_rowidxs_it.second);
625
115k
        }));
626
627
115k
        auto tablet_writer_it = _tablet_writers.find(tablet_to_rowidxs_it.first);
628
115k
        if (tablet_writer_it != _tablet_writers.end()) {
629
115k
            tablet_writer_it->second->set_tablet_load_rowset_num_info(tablet_load_infos);
630
115k
        }
631
115k
    }
632
633
33.1k
    {
634
33.1k
        std::lock_guard<std::mutex> l(_lock);
635
33.1k
        _next_seqs[request.sender_id()] = cur_seq + 1;
636
33.1k
    }
637
33.1k
    return Status::OK();
638
33.1k
}
639
640
Status TabletsChannel::add_batch(const PTabletWriterAddBlockRequest& request,
641
374
                                 PTabletWriterAddBlockResult* response) {
642
374
    SCOPED_TIMER(_add_batch_timer);
643
374
    int64_t cur_seq = 0;
644
374
    if (_add_batch_number_counter) {
645
0
        _add_batch_number_counter->update(1);
646
0
    }
647
648
374
    auto status = _get_current_seq(cur_seq, request);
649
374
    if (UNLIKELY(!status.ok())) {
650
0
        return status;
651
0
    }
652
653
374
    if (request.packet_seq() < cur_seq) {
654
0
        LOG(INFO) << "packet has already recept before, expect_seq=" << cur_seq
655
0
                  << ", recept_seq=" << request.packet_seq();
656
0
        return Status::OK();
657
0
    }
658
659
374
    std::unordered_map<int64_t /* tablet_id */, DorisVector<uint32_t> /* row index */>
660
374
            tablet_to_rowidxs;
661
374
    _build_tablet_to_rowidxs(request, &tablet_to_rowidxs);
662
663
374
    return _write_block_data(request, cur_seq, tablet_to_rowidxs, response);
664
374
}
665
666
0
void BaseTabletsChannel::_add_broken_tablet(int64_t tablet_id) {
667
0
    std::unique_lock<std::shared_mutex> wlock(_broken_tablets_lock);
668
0
    _broken_tablets.insert(tablet_id);
669
0
}
670
671
35.6M
bool BaseTabletsChannel::_is_broken_tablet(int64_t tablet_id) const {
672
35.6M
    return _broken_tablets.find(tablet_id) != _broken_tablets.end();
673
35.6M
}
674
675
void BaseTabletsChannel::_build_tablet_to_rowidxs(
676
        const PTabletWriterAddBlockRequest& request,
677
33.1k
        std::unordered_map<int64_t, DorisVector<uint32_t>>* tablet_to_rowidxs) {
678
    // just add a coarse-grained read lock here rather than each time when visiting _broken_tablets
679
    // tests show that a relatively coarse-grained read lock here performs better under multicore scenario
680
    // see: https://github.com/apache/doris/pull/28552
681
33.1k
    std::shared_lock<std::shared_mutex> rlock(_broken_tablets_lock);
682
33.1k
    if (request.is_single_tablet_block()) {
683
        // The cloud mode need the tablet ids to prepare rowsets.
684
0
        int64_t tablet_id = request.tablet_ids(0);
685
0
        tablet_to_rowidxs->emplace(tablet_id, std::initializer_list<uint32_t> {0});
686
0
        return;
687
0
    }
688
35.5M
    for (uint32_t i = 0; i < request.tablet_ids_size(); ++i) {
689
35.4M
        int64_t tablet_id = request.tablet_ids(i);
690
35.4M
        if (_is_broken_tablet(tablet_id)) {
691
            // skip broken tablets
692
0
            VLOG_PROGRESS << "skip broken tablet tablet=" << tablet_id;
693
0
            continue;
694
0
        }
695
35.4M
        auto it = tablet_to_rowidxs->find(tablet_id);
696
35.4M
        if (it == tablet_to_rowidxs->end()) {
697
115k
            tablet_to_rowidxs->emplace(tablet_id, std::initializer_list<uint32_t> {i});
698
35.3M
        } else {
699
35.3M
            it->second.emplace_back(i);
700
35.3M
        }
701
35.4M
    }
702
33.1k
}
703
704
} // namespace doris