Coverage Report

Created: 2026-04-16 20:39

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