Coverage Report

Created: 2026-05-19 05:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/delta_writer/delta_writer.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/delta_writer/delta_writer.h"
19
20
#include <brpc/controller.h>
21
#include <butil/errno.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/internal_service.pb.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <filesystem>
27
#include <ostream>
28
#include <string>
29
#include <utility>
30
31
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
32
#include "common/compiler_util.h" // IWYU pragma: keep
33
#include "common/config.h"
34
#include "common/logging.h"
35
#include "common/status.h"
36
#include "core/block/block.h"
37
#include "io/fs/file_writer.h" // IWYU pragma: keep
38
#include "load/memtable/memtable_flush_executor.h"
39
#include "runtime/exec_env.h"
40
#include "runtime/thread_context.h"
41
#include "service/backend_options.h"
42
#include "storage/index/inverted/inverted_index_desc.h"
43
#include "storage/olap_define.h"
44
#include "storage/rowset/beta_rowset.h"
45
#include "storage/rowset/beta_rowset_writer.h"
46
#include "storage/rowset/rowset_meta.h"
47
#include "storage/rowset_builder.h"
48
#include "storage/schema_change/schema_change.h"
49
#include "storage/storage_engine.h"
50
#include "storage/tablet/tablet_manager.h"
51
#include "storage/tablet_info.h"
52
#include "storage/txn/txn_manager.h"
53
#include "util/brpc_client_cache.h"
54
#include "util/brpc_closure.h"
55
#include "util/mem_info.h"
56
#include "util/stopwatch.hpp"
57
#include "util/time.h"
58
59
namespace doris {
60
using namespace ErrorCode;
61
62
BaseDeltaWriter::BaseDeltaWriter(const WriteRequest& req, RuntimeProfile* profile,
63
                                 const UniqueId& load_id)
64
264k
        : _req(req), _memtable_writer(new MemTableWriter(req)) {
65
264k
    if (profile != nullptr) {
66
129
        _init_profile(profile);
67
129
    }
68
264k
}
69
70
DeltaWriter::DeltaWriter(StorageEngine& engine, const WriteRequest& req, RuntimeProfile* profile,
71
                         const UniqueId& load_id)
72
3.73k
        : BaseDeltaWriter(req, profile, load_id), _engine(engine) {
73
3.73k
    DCHECK(req.write_req_type == WriteRequestType::DATA);
74
3.73k
    _rowset_builder = std::make_unique<RowsetBuilder>(_engine, req, profile);
75
3.73k
}
76
77
DeltaWriter::DeltaWriter(StorageEngine& engine, const WriteRequest& group_build_req,
78
                         const WriteRequest& sub_data_req, const WriteRequest& sub_row_binlog_req,
79
                         RuntimeProfile* profile, const UniqueId& load_id)
80
0
        : BaseDeltaWriter(group_build_req, profile, load_id), _engine(engine) {
81
0
    DCHECK(group_build_req.write_req_type == WriteRequestType::GROUP &&
82
0
           sub_data_req.write_req_type == WriteRequestType::DATA &&
83
0
           sub_row_binlog_req.write_req_type == WriteRequestType::ROW_BINLOG);
84
0
    _rowset_builder = std::make_unique<GroupRowsetBuilder>(_engine, group_build_req, sub_data_req,
85
0
                                                           sub_row_binlog_req, profile);
86
0
}
87
88
129
void BaseDeltaWriter::_init_profile(RuntimeProfile* profile) {
89
129
    DCHECK(profile != nullptr);
90
129
    _profile = profile->create_child(fmt::format("DeltaWriter {}", _req.tablet_id), true, true);
91
129
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
92
129
    _wait_flush_limit_timer = ADD_TIMER(_profile, "WaitFlushLimitTime");
93
129
}
94
95
0
void DeltaWriter::_init_profile(RuntimeProfile* profile) {
96
0
    DCHECK(profile != nullptr);
97
0
    BaseDeltaWriter::_init_profile(profile);
98
0
    _commit_txn_timer = ADD_TIMER(_profile, "CommitTxnTime");
99
0
}
100
101
264k
BaseDeltaWriter::~BaseDeltaWriter() {
102
264k
    if (!_is_init) {
103
208k
        return;
104
208k
    }
105
106
    // cancel and wait all memtables in flush queue to be finished
107
56.3k
    static_cast<void>(_memtable_writer->cancel());
108
109
56.3k
    if (_rowset_builder->tablet() != nullptr) {
110
56.3k
        const FlushStatistic& stat = _memtable_writer->get_flush_token_stats();
111
56.3k
        _rowset_builder->tablet()->flush_bytes->increment(stat.flush_size_bytes);
112
56.3k
        _rowset_builder->tablet()->flush_finish_count->increment(stat.flush_finish_count);
113
56.3k
    }
114
56.3k
}
115
116
void BaseDeltaWriter::collect_tablet_load_rowset_num_info(
117
        BaseTablet* tablet,
118
129k
        google::protobuf::RepeatedPtrField<PTabletLoadRowsetInfo>* tablet_infos) {
119
129k
    if (tablet == nullptr) {
120
0
        return;
121
0
    }
122
129k
    auto max_version_config = tablet->max_version_config();
123
129k
    if (auto version_cnt = tablet->tablet_meta()->version_count();
124
129k
        UNLIKELY(version_cnt >
125
129k
                 (max_version_config * config::load_back_pressure_version_threshold / 100))) {
126
0
        auto* load_info = tablet_infos->Add();
127
0
        load_info->set_current_rowset_nums(static_cast<int32_t>(version_cnt));
128
0
        load_info->set_max_config_rowset_nums(max_version_config);
129
0
    }
130
129k
}
131
132
void BaseDeltaWriter::set_tablet_load_rowset_num_info(
133
115k
        google::protobuf::RepeatedPtrField<PTabletLoadRowsetInfo>* tablet_infos) {
134
115k
    auto* tablet = _rowset_builder->tablet().get();
135
115k
    collect_tablet_load_rowset_num_info(tablet, tablet_infos);
136
115k
}
137
138
3.73k
DeltaWriter::~DeltaWriter() = default;
139
140
56.2k
Status BaseDeltaWriter::init() {
141
56.2k
    if (_is_init) {
142
0
        return Status::OK();
143
0
    }
144
56.2k
    std::shared_ptr<WorkloadGroup> wg_sptr = nullptr;
145
56.2k
    if (doris::thread_context()->is_attach_task()) {
146
56.1k
        wg_sptr = doris::thread_context()->resource_ctx()->workload_group();
147
56.1k
    }
148
56.2k
    RETURN_IF_ERROR(_rowset_builder->init());
149
56.2k
    RETURN_IF_ERROR(_memtable_writer->init(
150
56.2k
            _rowset_builder->rowset_writer(), _rowset_builder->tablet_schema(),
151
56.2k
            _rowset_builder->get_partial_update_info(), wg_sptr,
152
56.2k
            _rowset_builder->tablet_sptr()->enable_unique_key_merge_on_write()));
153
56.2k
    ExecEnv::GetInstance()->memtable_memory_limiter()->register_writer(_memtable_writer);
154
56.2k
    _is_init = true;
155
56.2k
    return Status::OK();
156
56.2k
}
157
158
838
Status DeltaWriter::write(const Block* block, const DorisVector<uint32_t>& row_idxs) {
159
838
    if (UNLIKELY(row_idxs.empty())) {
160
0
        return Status::OK();
161
0
    }
162
838
    _lock_watch.start();
163
838
    std::lock_guard<std::mutex> l(_lock);
164
838
    _lock_watch.stop();
165
838
    if (!_is_init && !_is_cancelled) {
166
830
        RETURN_IF_ERROR(init());
167
830
    }
168
838
    {
169
838
        SCOPED_TIMER(_wait_flush_limit_timer);
170
838
        while (_memtable_writer->flush_running_count() >=
171
838
               config::memtable_flush_running_count_limit) {
172
0
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
173
0
        }
174
838
    }
175
838
    return _memtable_writer->write(block, row_idxs);
176
838
}
177
178
2.62k
Status BaseDeltaWriter::wait_flush() {
179
2.62k
    return _memtable_writer->wait_flush();
180
2.62k
}
181
182
2.63k
Status DeltaWriter::close() {
183
2.63k
    _lock_watch.start();
184
2.63k
    std::lock_guard<std::mutex> l(_lock);
185
2.63k
    _lock_watch.stop();
186
2.63k
    if (!_is_init && !_is_cancelled) {
187
        // if this delta writer is not initialized, but close() is called.
188
        // which means this tablet has no data loaded, but at least one tablet
189
        // in same partition has data loaded.
190
        // so we have to also init this DeltaWriter, so that it can create an empty rowset
191
        // for this tablet when being closed.
192
1.80k
        RETURN_IF_ERROR(init());
193
1.80k
    }
194
2.63k
    return _memtable_writer->close();
195
2.63k
}
196
197
56.3k
Status BaseDeltaWriter::build_rowset() {
198
56.3k
    SCOPED_TIMER(_close_wait_timer);
199
56.3k
    RETURN_IF_ERROR(_memtable_writer->close_wait(_profile));
200
56.2k
    return _rowset_builder->build_rowset();
201
56.3k
}
202
203
2.63k
Status DeltaWriter::build_rowset() {
204
2.63k
    std::lock_guard<std::mutex> l(_lock);
205
2.63k
    DCHECK(_is_init)
206
0
            << "delta writer is supposed be to initialized before build_rowset() being called";
207
2.63k
    return BaseDeltaWriter::build_rowset();
208
2.63k
}
209
210
173k
Status BaseDeltaWriter::submit_calc_delete_bitmap_task() {
211
173k
    return _rowset_builder->submit_calc_delete_bitmap_task();
212
173k
}
213
214
173k
Status BaseDeltaWriter::wait_calc_delete_bitmap() {
215
173k
    return _rowset_builder->wait_calc_delete_bitmap();
216
173k
}
217
218
2.63k
Status DeltaWriter::commit_txn(const PSlaveTabletNodes& slave_tablet_nodes) {
219
2.63k
    std::lock_guard<std::mutex> l(_lock);
220
2.63k
    SCOPED_TIMER(_commit_txn_timer);
221
2.63k
    RETURN_IF_ERROR(_rowset_builder->commit_txn());
222
223
2.63k
    for (auto&& node_info : slave_tablet_nodes.slave_nodes()) {
224
0
        _request_slave_tablet_pull_rowset(node_info);
225
0
    }
226
2.63k
    return Status::OK();
227
2.63k
}
228
229
bool DeltaWriter::check_slave_replicas_done(
230
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
231
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
232
0
    if (_unfinished_slave_node.empty()) {
233
0
        success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
234
0
        return true;
235
0
    }
236
0
    return false;
237
0
}
238
239
void DeltaWriter::add_finished_slave_replicas(
240
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
241
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
242
0
    success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
243
0
}
244
245
90.8k
Status BaseDeltaWriter::cancel() {
246
90.8k
    return cancel_with_status(Status::Cancelled("already cancelled"));
247
90.8k
}
248
249
90.9k
Status BaseDeltaWriter::cancel_with_status(const Status& st) {
250
90.9k
    if (_is_cancelled) {
251
0
        return Status::OK();
252
0
    }
253
90.9k
    RETURN_IF_ERROR(_memtable_writer->cancel_with_status(st));
254
90.9k
    _is_cancelled = true;
255
90.9k
    return Status::OK();
256
90.9k
}
257
258
1.10k
Status DeltaWriter::cancel_with_status(const Status& st) {
259
1.10k
    std::lock_guard<std::mutex> l(_lock);
260
1.10k
    return BaseDeltaWriter::cancel_with_status(st);
261
1.10k
}
262
263
120
int64_t BaseDeltaWriter::mem_consumption(MemType mem) {
264
120
    return _memtable_writer->mem_consumption(mem);
265
120
}
266
267
0
void DeltaWriter::_request_slave_tablet_pull_rowset(const PNodeInfo& node_info) {
268
0
    std::shared_ptr<PBackendService_Stub> stub =
269
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
270
0
                    node_info.host(), node_info.async_internal_port());
271
0
    if (stub == nullptr) {
272
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica. get rpc stub failed, "
273
0
                        "slave host="
274
0
                     << node_info.host() << ", port=" << node_info.async_internal_port()
275
0
                     << ", tablet_id=" << _req.tablet_id << ", txn_id=" << _req.txn_id;
276
0
        return;
277
0
    }
278
279
0
    _engine.txn_manager()->add_txn_tablet_delta_writer(_req.txn_id, _req.tablet_id, this);
280
0
    {
281
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
282
0
        _unfinished_slave_node.insert(node_info.id());
283
0
    }
284
285
0
    std::vector<std::pair<int64_t, std::string>> indices_ids;
286
0
    auto cur_rowset = _rowset_builder->rowset();
287
0
    auto tablet_schema = cur_rowset->rowset_meta()->tablet_schema();
288
0
    if (!tablet_schema->skip_write_index_on_load()) {
289
0
        for (const auto& column : tablet_schema->columns()) {
290
0
            auto index_metas = tablet_schema->inverted_indexs(*column);
291
0
            for (const auto* index_meta : index_metas) {
292
0
                indices_ids.emplace_back(index_meta->index_id(), index_meta->get_index_suffix());
293
0
            }
294
0
        }
295
0
    }
296
297
0
    auto request = std::make_shared<PTabletWriteSlaveRequest>();
298
0
    auto* request_mutable_rs_meta = request->mutable_rowset_meta();
299
0
    *request_mutable_rs_meta = cur_rowset->rowset_meta()->get_rowset_pb();
300
0
    if (request_mutable_rs_meta != nullptr && request_mutable_rs_meta->has_partition_id() &&
301
0
        request_mutable_rs_meta->partition_id() == 0) {
302
        // TODO(dx): remove log after fix partition id eq 0 bug
303
0
        request_mutable_rs_meta->set_partition_id(_req.partition_id);
304
0
        LOG(WARNING) << "cant get partition id from local rs pb, get from _req, partition_id="
305
0
                     << _req.partition_id;
306
0
    }
307
0
    request->set_host(BackendOptions::get_localhost());
308
0
    request->set_http_port(config::webserver_port);
309
0
    const auto& tablet_path = cur_rowset->tablet_path();
310
0
    request->set_rowset_path(tablet_path);
311
0
    request->set_token(ExecEnv::GetInstance()->token());
312
0
    request->set_brpc_port(config::brpc_port);
313
0
    request->set_node_id(static_cast<int32_t>(node_info.id()));
314
0
    for (int segment_id = 0; segment_id < cur_rowset->rowset_meta()->num_segments(); segment_id++) {
315
0
        auto seg_path =
316
0
                local_segment_path(tablet_path, cur_rowset->rowset_id().to_string(), segment_id);
317
0
        int64_t segment_size = std::filesystem::file_size(seg_path);
318
0
        request->mutable_segments_size()->insert({segment_id, segment_size});
319
0
        auto index_path_prefix = InvertedIndexDescriptor::get_index_file_path_prefix(seg_path);
320
0
        if (!indices_ids.empty()) {
321
0
            if (tablet_schema->get_inverted_index_storage_format() ==
322
0
                InvertedIndexStorageFormatPB::V1) {
323
0
                for (auto index_meta : indices_ids) {
324
0
                    std::string inverted_index_file =
325
0
                            InvertedIndexDescriptor::get_index_file_path_v1(
326
0
                                    index_path_prefix, index_meta.first, index_meta.second);
327
0
                    int64_t size = std::filesystem::file_size(inverted_index_file);
328
0
                    PTabletWriteSlaveRequest::IndexSize index_size;
329
0
                    index_size.set_indexid(index_meta.first);
330
0
                    index_size.set_size(size);
331
0
                    index_size.set_suffix_path(index_meta.second);
332
                    // Fetch the map value for the current segment_id.
333
                    // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
334
0
                    auto& index_size_map_value =
335
0
                            (*(request->mutable_inverted_indices_size()))[segment_id];
336
                    // Add the new index size to the map value.
337
0
                    *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
338
0
                }
339
0
            } else {
340
0
                std::string inverted_index_file =
341
0
                        InvertedIndexDescriptor::get_index_file_path_v2(index_path_prefix);
342
0
                int64_t size = std::filesystem::file_size(inverted_index_file);
343
0
                PTabletWriteSlaveRequest::IndexSize index_size;
344
                // special id for non-V1 format
345
0
                index_size.set_indexid(0);
346
0
                index_size.set_size(size);
347
0
                index_size.set_suffix_path("");
348
                // Fetch the map value for the current segment_id.
349
                // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
350
0
                auto& index_size_map_value =
351
0
                        (*(request->mutable_inverted_indices_size()))[segment_id];
352
                // Add the new index size to the map value.
353
0
                *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
354
0
            }
355
0
        }
356
0
    }
357
358
0
    auto pull_callback = DummyBrpcCallback<PTabletWriteSlaveResult>::create_shared();
359
0
    auto closure = AutoReleaseClosure<
360
0
            PTabletWriteSlaveRequest,
361
0
            DummyBrpcCallback<PTabletWriteSlaveResult>>::create_unique(request, pull_callback);
362
0
    closure->cntl_->set_timeout_ms(config::slave_replica_writer_rpc_timeout_sec * 1000);
363
0
    closure->cntl_->ignore_eovercrowded();
364
0
    stub->request_slave_tablet_pull_rowset(closure->cntl_.get(), closure->request_.get(),
365
0
                                           closure->response_.get(), closure.get());
366
367
0
    closure.release();
368
0
    pull_callback->join();
369
0
    if (pull_callback->cntl_->Failed()) {
370
0
        if (!ExecEnv::GetInstance()->brpc_internal_client_cache()->available(
371
0
                    stub, node_info.host(), node_info.async_internal_port())) {
372
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
373
0
                    pull_callback->cntl_->remote_side());
374
0
        }
375
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica, error="
376
0
                     << berror(pull_callback->cntl_->ErrorCode())
377
0
                     << ", error_text=" << pull_callback->cntl_->ErrorText()
378
0
                     << ". slave host: " << node_info.host() << ", tablet_id=" << _req.tablet_id
379
0
                     << ", txn_id=" << _req.txn_id;
380
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
381
0
        _unfinished_slave_node.erase(node_info.id());
382
0
    }
383
0
}
384
385
0
void DeltaWriter::finish_slave_tablet_pull_rowset(int64_t node_id, bool is_succeed) {
386
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
387
0
    if (is_succeed) {
388
0
        _success_slave_node_ids.add_slave_node_ids(node_id);
389
0
        VLOG_CRITICAL << "record successful slave replica for txn [" << _req.txn_id
390
0
                      << "], tablet_id=" << _req.tablet_id << ", node_id=" << node_id;
391
0
    }
392
0
    _unfinished_slave_node.erase(node_id);
393
0
}
394
395
176k
int64_t BaseDeltaWriter::num_rows_filtered() const {
396
176k
    auto rowset_writer = _rowset_builder->rowset_writer();
397
176k
    return rowset_writer == nullptr ? 0 : rowset_writer->num_rows_filtered();
398
176k
}
399
400
} // namespace doris