Coverage Report

Created: 2026-03-14 13:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_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 "cloud/cloud_tablets_channel.h"
19
20
#include <mutex>
21
22
#include "cloud/cloud_delta_writer.h"
23
#include "cloud/cloud_meta_mgr.h"
24
#include "cloud/cloud_storage_engine.h"
25
#include "cloud/config.h"
26
#include "load/channel/tablets_channel.h"
27
#include "load/delta_writer/delta_writer.h"
28
29
namespace doris {
30
#include "common/compile_check_begin.h"
31
32
CloudTabletsChannel::CloudTabletsChannel(CloudStorageEngine& engine, const TabletsChannelKey& key,
33
                                         const UniqueId& load_id, bool is_high_priority,
34
                                         RuntimeProfile* profile)
35
29.1k
        : BaseTabletsChannel(key, load_id, is_high_priority, profile), _engine(engine) {}
36
37
29.1k
CloudTabletsChannel::~CloudTabletsChannel() = default;
38
39
std::unique_ptr<BaseDeltaWriter> CloudTabletsChannel::create_delta_writer(
40
275k
        const WriteRequest& request) {
41
275k
    return std::make_unique<CloudDeltaWriter>(_engine, request, _profile, _load_id);
42
275k
}
43
44
Status CloudTabletsChannel::add_batch(const PTabletWriterAddBlockRequest& request,
45
31.9k
                                      PTabletWriterAddBlockResult* response) {
46
    // FIXME(plat1ko): Too many duplicate code with `TabletsChannel`
47
31.9k
    SCOPED_TIMER(_add_batch_timer);
48
31.9k
    int64_t cur_seq = 0;
49
31.9k
    _add_batch_number_counter->update(1);
50
51
31.9k
    auto status = _get_current_seq(cur_seq, request);
52
31.9k
    if (UNLIKELY(!status.ok())) {
53
0
        return status;
54
0
    }
55
56
31.9k
    if (request.packet_seq() < cur_seq) {
57
0
        LOG(INFO) << "packet has already recept before, expect_seq=" << cur_seq
58
0
                  << ", recept_seq=" << request.packet_seq();
59
0
        return Status::OK();
60
0
    }
61
62
31.9k
    std::unordered_map<int64_t, DorisVector<uint32_t>> tablet_to_rowidxs;
63
31.9k
    _build_tablet_to_rowidxs(request, &tablet_to_rowidxs);
64
65
31.9k
    std::unordered_set<int64_t> partition_ids;
66
31.9k
    std::vector<CloudDeltaWriter*> writers;
67
31.9k
    {
68
        // add_batch may concurrency with inc_open but not under _lock.
69
        // so need to protect it with _tablet_writers_lock.
70
31.9k
        std::lock_guard<std::mutex> l(_tablet_writers_lock);
71
114k
        for (auto& [tablet_id, _] : tablet_to_rowidxs) {
72
114k
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
73
114k
            if (tablet_writer_it == _tablet_writers.end()) {
74
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
75
0
            }
76
114k
            partition_ids.insert(tablet_writer_it->second->partition_id());
77
114k
            writers.push_back(static_cast<CloudDeltaWriter*>(tablet_writer_it->second.get()));
78
114k
        }
79
31.9k
        if (config::skip_writing_empty_rowset_metadata && !writers.empty()) {
80
0
            RETURN_IF_ERROR(CloudDeltaWriter::batch_init(writers));
81
31.9k
        } else if (!partition_ids.empty()) {
82
31.9k
            RETURN_IF_ERROR(_init_writers_by_partition_ids(partition_ids));
83
31.9k
        }
84
31.9k
    }
85
86
31.9k
    return _write_block_data(request, cur_seq, tablet_to_rowidxs, response);
87
31.9k
}
88
89
Status CloudTabletsChannel::_init_writers_by_partition_ids(
90
31.9k
        const std::unordered_set<int64_t>& partition_ids) {
91
31.9k
    std::vector<CloudDeltaWriter*> writers;
92
328k
    for (auto&& [tablet_id, base_writer] : _tablet_writers) {
93
328k
        auto* writer = static_cast<CloudDeltaWriter*>(base_writer.get());
94
328k
        if (partition_ids.contains(writer->partition_id()) && !writer->is_init()) {
95
181k
            writers.push_back(writer);
96
181k
        }
97
328k
    }
98
31.9k
    if (!writers.empty()) {
99
26.9k
        RETURN_IF_ERROR(CloudDeltaWriter::batch_init(writers));
100
26.9k
    }
101
31.9k
    return Status::OK();
102
31.9k
}
103
104
Status CloudTabletsChannel::close(LoadChannel* parent, const PTabletWriterAddBlockRequest& req,
105
66.4k
                                  PTabletWriterAddBlockResult* res, bool* finished) {
106
    // FIXME(plat1ko): Too many duplicate code with `TabletsChannel`
107
66.4k
    std::lock_guard l(_lock);
108
66.4k
    if (_state == kFinished) {
109
0
        return _close_status;
110
0
    }
111
112
66.4k
    auto sender_id = req.sender_id();
113
66.4k
    if (_closed_senders.Get(sender_id)) {
114
        // Double close from one sender, just return OK
115
0
        *finished = (_num_remaining_senders == 0);
116
0
        return _close_status;
117
0
    }
118
119
66.4k
    for (auto pid : req.partition_ids()) {
120
32.6k
        _partition_ids.emplace(pid);
121
32.6k
    }
122
123
66.4k
    _closed_senders.Set(sender_id, true);
124
66.4k
    _num_remaining_senders--;
125
66.4k
    *finished = (_num_remaining_senders == 0);
126
127
66.4k
    LOG(INFO) << "close tablets channel: " << _key << ", sender id: " << sender_id
128
66.4k
              << ", backend id: " << req.backend_id()
129
66.4k
              << " remaining sender: " << _num_remaining_senders;
130
131
66.4k
    if (!*finished) {
132
37.2k
        return Status::OK();
133
37.2k
    }
134
135
29.1k
    auto* tablet_errors = res->mutable_tablet_errors();
136
29.1k
    auto* tablet_vec = res->mutable_tablet_vec();
137
29.1k
    _state = kFinished;
138
139
    // All senders are closed
140
    // 1. close all delta writers. under _lock.
141
29.1k
    std::vector<CloudDeltaWriter*> writers_to_commit;
142
29.1k
    writers_to_commit.reserve(_tablet_writers.size());
143
29.1k
    bool success = true;
144
145
274k
    for (auto&& [tablet_id, base_writer] : _tablet_writers) {
146
274k
        auto* writer = static_cast<CloudDeltaWriter*>(base_writer.get());
147
        // ATTN: the strict mode means strict filtering of column type conversions during import.
148
        // Sometimes all inputs are filtered, but the partition ID is still set, and the writer is
149
        // not initialized.
150
274k
        if (_partition_ids.contains(writer->partition_id())) {
151
182k
            if (!success) { // Already failed, cancel all remain writers
152
0
                static_cast<void>(writer->cancel());
153
0
                continue;
154
0
            }
155
156
182k
            if (writer->is_init()) {
157
181k
                auto st = writer->close();
158
181k
                if (!st.ok()) {
159
0
                    LOG(WARNING) << "close tablet writer failed, tablet_id=" << tablet_id
160
0
                                 << ", txn_id=" << _txn_id << ", err=" << st;
161
0
                    PTabletError* tablet_error = tablet_errors->Add();
162
0
                    tablet_error->set_tablet_id(tablet_id);
163
0
                    tablet_error->set_msg(st.to_string());
164
0
                    success = false;
165
0
                    _close_status = std::move(st);
166
0
                    continue;
167
0
                }
168
181k
            }
169
170
            // to make sure tablet writer in `_broken_tablets` won't call `close_wait` method.
171
182k
            if (_is_broken_tablet(writer->tablet_id())) {
172
0
                LOG(WARNING) << "SHOULD NOT HAPPEN, tablet writer is broken but not cancelled"
173
0
                             << ", tablet_id=" << tablet_id << ", transaction_id=" << _txn_id;
174
0
                continue;
175
0
            }
176
177
182k
            writers_to_commit.push_back(writer);
178
182k
        } else {
179
92.1k
            auto st = writer->cancel();
180
92.1k
            if (!st.ok()) {
181
0
                LOG(WARNING) << "cancel tablet writer failed, tablet_id=" << tablet_id
182
0
                             << ", txn_id=" << _txn_id;
183
                // just skip this tablet(writer) and continue to close others
184
0
                continue;
185
0
            }
186
92.1k
        }
187
274k
    }
188
189
29.1k
    if (!success) {
190
0
        return _close_status;
191
0
    }
192
193
    // 2. wait delta writers
194
29.1k
    using namespace std::chrono;
195
29.1k
    auto build_start = steady_clock::now();
196
181k
    for (auto* writer : writers_to_commit) {
197
181k
        if (!writer->is_init()) {
198
382
            continue;
199
382
        }
200
201
181k
        auto st = writer->build_rowset();
202
181k
        if (!st.ok()) {
203
48
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
204
48
                         << ", err=" << st;
205
48
            PTabletError* tablet_error = tablet_errors->Add();
206
48
            tablet_error->set_tablet_id(writer->tablet_id());
207
48
            tablet_error->set_msg(st.to_string());
208
48
            _close_status = std::move(st);
209
48
            return _close_status;
210
48
        }
211
181k
    }
212
29.1k
    int64_t build_latency = duration_cast<milliseconds>(steady_clock::now() - build_start).count();
213
214
    // 3. commit rowsets to meta-service
215
29.1k
    auto commit_start = steady_clock::now();
216
29.1k
    std::vector<std::function<Status()>> tasks;
217
29.1k
    tasks.reserve(writers_to_commit.size());
218
181k
    for (auto* writer : writers_to_commit) {
219
181k
        tasks.emplace_back([writer] { return writer->commit_rowset(); });
220
181k
    }
221
29.1k
    _close_status = cloud::bthread_fork_join(tasks, 10);
222
29.1k
    if (!_close_status.ok()) {
223
0
        return _close_status;
224
0
    }
225
226
29.1k
    int64_t commit_latency =
227
29.1k
            duration_cast<milliseconds>(steady_clock::now() - commit_start).count();
228
229
    // 4. calculate delete bitmap for Unique Key MoW tables
230
181k
    for (auto* writer : writers_to_commit) {
231
181k
        auto st = writer->submit_calc_delete_bitmap_task();
232
181k
        if (!st.ok()) {
233
0
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
234
0
                         << ", err=" << st;
235
0
            _add_error_tablet(tablet_errors, writer->tablet_id(), st);
236
0
            _close_status = std::move(st);
237
0
            return _close_status;
238
0
        }
239
181k
    }
240
241
    // 5. wait for delete bitmap calculation complete if necessary
242
181k
    for (auto* writer : writers_to_commit) {
243
181k
        auto st = writer->wait_calc_delete_bitmap();
244
181k
        if (!st.ok()) {
245
0
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
246
0
                         << ", err=" << st;
247
0
            _add_error_tablet(tablet_errors, writer->tablet_id(), st);
248
0
            _close_status = std::move(st);
249
0
            return _close_status;
250
0
        }
251
181k
    }
252
253
    // 6. set txn related delete bitmap if necessary
254
210k
    for (auto it = writers_to_commit.begin(); it != writers_to_commit.end();) {
255
181k
        auto st = (*it)->set_txn_related_delete_bitmap();
256
181k
        if (!st.ok()) {
257
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
258
0
            _close_status = std::move(st);
259
0
            return _close_status;
260
0
        }
261
181k
        it++;
262
181k
    }
263
264
29.1k
    tablet_vec->Reserve(static_cast<int>(writers_to_commit.size()));
265
181k
    for (auto* writer : writers_to_commit) {
266
181k
        PTabletInfo* tablet_info = tablet_vec->Add();
267
181k
        tablet_info->set_tablet_id(writer->tablet_id());
268
        // unused required field.
269
181k
        tablet_info->set_schema_hash(0);
270
181k
        tablet_info->set_received_rows(writer->total_received_rows());
271
181k
        tablet_info->set_num_rows_filtered(writer->num_rows_filtered());
272
        // These stats may be larger than the actual value if the txn is aborted
273
181k
        writer->update_tablet_stats();
274
181k
    }
275
29.1k
    res->set_build_rowset_latency_ms(build_latency);
276
29.1k
    res->set_commit_rowset_latency_ms(commit_latency);
277
29.1k
    return Status::OK();
278
29.1k
}
279
280
#include "common/compile_check_end.h"
281
} // namespace doris