Coverage Report

Created: 2025-10-29 17:09

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