Coverage Report

Created: 2026-04-25 11:24

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