Coverage Report

Created: 2026-05-20 16:40

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