Coverage Report

Created: 2025-07-23 16:39

/root/doris/be/src/olap/compaction.cpp
Line
Count
Source (jump to first uncovered line)
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/compaction.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <glog/logging.h>
23
24
#include <algorithm>
25
#include <atomic>
26
#include <cstdint>
27
#include <cstdlib>
28
#include <list>
29
#include <map>
30
#include <memory>
31
#include <mutex>
32
#include <nlohmann/json.hpp>
33
#include <numeric>
34
#include <ostream>
35
#include <set>
36
#include <shared_mutex>
37
#include <utility>
38
39
#include "cloud/cloud_meta_mgr.h"
40
#include "cloud/cloud_storage_engine.h"
41
#include "cloud/cloud_tablet.h"
42
#include "common/config.h"
43
#include "common/status.h"
44
#include "cpp/sync_point.h"
45
#include "io/cache/block_file_cache_factory.h"
46
#include "io/fs/file_system.h"
47
#include "io/fs/file_writer.h"
48
#include "io/fs/remote_file_system.h"
49
#include "io/io_common.h"
50
#include "olap/cumulative_compaction.h"
51
#include "olap/cumulative_compaction_policy.h"
52
#include "olap/cumulative_compaction_time_series_policy.h"
53
#include "olap/data_dir.h"
54
#include "olap/olap_common.h"
55
#include "olap/olap_define.h"
56
#include "olap/rowset/beta_rowset.h"
57
#include "olap/rowset/beta_rowset_reader.h"
58
#include "olap/rowset/beta_rowset_writer.h"
59
#include "olap/rowset/rowset.h"
60
#include "olap/rowset/rowset_fwd.h"
61
#include "olap/rowset/rowset_meta.h"
62
#include "olap/rowset/rowset_writer.h"
63
#include "olap/rowset/rowset_writer_context.h"
64
#include "olap/rowset/segment_v2/inverted_index_compaction.h"
65
#include "olap/rowset/segment_v2/inverted_index_desc.h"
66
#include "olap/rowset/segment_v2/inverted_index_file_reader.h"
67
#include "olap/rowset/segment_v2/inverted_index_file_writer.h"
68
#include "olap/rowset/segment_v2/inverted_index_fs_directory.h"
69
#include "olap/storage_engine.h"
70
#include "olap/storage_policy.h"
71
#include "olap/tablet.h"
72
#include "olap/tablet_meta.h"
73
#include "olap/tablet_meta_manager.h"
74
#include "olap/task/engine_checksum_task.h"
75
#include "olap/txn_manager.h"
76
#include "olap/utils.h"
77
#include "runtime/memory/mem_tracker_limiter.h"
78
#include "runtime/thread_context.h"
79
#include "util/doris_metrics.h"
80
#include "util/time.h"
81
#include "util/trace.h"
82
#include "vec/common/schema_util.h"
83
84
using std::vector;
85
86
namespace doris {
87
using namespace ErrorCode;
88
89
namespace {
90
91
bool is_rowset_tidy(std::string& pre_max_key, bool& pre_rs_key_bounds_truncated,
92
39
                    const RowsetSharedPtr& rhs) {
93
39
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
94
39
    if (rhs->num_segments() == 0) {
  Branch (94:9): [True: 0, False: 39]
95
0
        return true;
96
0
    }
97
39
    if (rhs->is_segments_overlapping()) {
  Branch (97:9): [True: 0, False: 39]
98
0
        return false;
99
0
    }
100
    // check segment size
101
39
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
102
39
    std::vector<size_t> segments_size;
103
39
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
104
46
    for (auto segment_size : segments_size) {
  Branch (104:28): [True: 46, False: 38]
105
        // is segment is too small, need to do compaction
106
46
        if (segment_size < min_tidy_size) {
  Branch (106:13): [True: 0, False: 46]
107
0
            return false;
108
0
        }
109
46
    }
110
38
    std::string min_key;
111
38
    auto ret = rhs->first_key(&min_key);
112
38
    if (!ret) {
  Branch (112:9): [True: 0, False: 38]
113
0
        return false;
114
0
    }
115
38
    bool cur_rs_key_bounds_truncated {rhs->is_segments_key_bounds_truncated()};
116
38
    if (!Slice::lhs_is_strictly_less_than_rhs(Slice {pre_max_key}, pre_rs_key_bounds_truncated,
  Branch (116:9): [True: 5, False: 33]
117
38
                                              Slice {min_key}, cur_rs_key_bounds_truncated)) {
118
5
        return false;
119
5
    }
120
33
    CHECK(rhs->last_key(&pre_max_key));
121
33
    pre_rs_key_bounds_truncated = cur_rs_key_bounds_truncated;
122
33
    return true;
123
38
}
124
125
} // namespace
126
127
Compaction::Compaction(BaseTabletSPtr tablet, const std::string& label)
128
        : _mem_tracker(
129
                  MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label)),
130
          _tablet(std::move(tablet)),
131
          _is_vertical(config::enable_vertical_compaction),
132
72
          _allow_delete_in_cumu_compaction(config::enable_delete_when_cumu_compaction) {
133
72
    ;
134
72
    init_profile(label);
135
72
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
Line
Count
Source
76
72
    auto VARNAME_LINENUM(scoped_tls_stmtl) = doris::ScopedInitThreadContext()
136
72
    _rowid_conversion = std::make_unique<RowIdConversion>();
137
72
}
138
139
72
Compaction::~Compaction() {
140
72
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
Line
Count
Source
76
72
    auto VARNAME_LINENUM(scoped_tls_stmtl) = doris::ScopedInitThreadContext()
141
72
    _output_rs_writer.reset();
142
72
    _tablet.reset();
143
72
    _input_rowsets.clear();
144
72
    _output_rowset.reset();
145
72
    _cur_tablet_schema.reset();
146
72
    _rowid_conversion.reset();
147
72
}
148
149
72
void Compaction::init_profile(const std::string& label) {
150
72
    _profile = std::make_unique<RuntimeProfile>(label);
151
152
72
    _input_rowsets_data_size_counter =
153
72
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
154
72
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
155
72
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
156
72
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
157
72
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
158
72
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
159
72
    _output_rowset_data_size_counter =
160
72
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
161
72
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
162
72
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
Line
Count
Source
57
72
#define ADD_COUNTER(profile, name, type) (profile)->add_counter(name, type)
163
72
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
Line
Count
Source
60
72
#define ADD_TIMER(profile, name) (profile)->add_counter(name, TUnit::TIME_NS)
164
72
}
165
166
0
int64_t Compaction::merge_way_num() {
167
0
    int64_t way_num = 0;
168
0
    for (auto&& rowset : _input_rowsets) {
  Branch (168:24): [True: 0, False: 0]
169
0
        way_num += rowset->rowset_meta()->get_merge_way_num();
170
0
    }
171
172
0
    return way_num;
173
0
}
174
175
0
Status Compaction::merge_input_rowsets() {
176
0
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
177
0
    input_rs_readers.reserve(_input_rowsets.size());
178
0
    for (auto& rowset : _input_rowsets) {
  Branch (178:23): [True: 0, False: 0]
179
0
        RowsetReaderSharedPtr rs_reader;
180
0
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
181
0
        input_rs_readers.push_back(std::move(rs_reader));
182
0
    }
183
184
0
    RowsetWriterContext ctx;
185
0
    ctx.input_rs_readers = input_rs_readers;
186
0
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
187
188
    // write merged rows to output rowset
189
    // The test results show that merger is low-memory-footprint, there is no need to tracker its mem pool
190
    // if ctx.columns_to_do_index_compaction.size() > 0, it means we need to do inverted index compaction.
191
    // the row ID conversion matrix needs to be used for inverted index compaction.
192
0
    if (!ctx.columns_to_do_index_compaction.empty() ||
  Branch (192:9): [True: 0, False: 0]
193
0
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (193:10): [True: 0, False: 0]
194
0
         _tablet->enable_unique_key_merge_on_write())) {
  Branch (194:10): [True: 0, False: 0]
195
0
        _stats.rowid_conversion = _rowid_conversion.get();
196
0
    }
197
198
0
    int64_t way_num = merge_way_num();
199
200
0
    Status res;
201
0
    {
202
0
        SCOPED_TIMER(_merge_rowsets_latency_timer);
Line
Count
Source
69
0
#define SCOPED_TIMER(c) ScopedTimer<MonotonicStopWatch> MACRO_CONCAT(SCOPED_TIMER, __COUNTER__)(c)
Line
Count
Source
52
0
#define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y)
Line
Count
Source
51
0
#define CONCAT_IMPL(x, y) x##y
203
        // 1. Merge segment files and write bkd inverted index
204
0
        if (_is_vertical) {
  Branch (204:13): [True: 0, False: 0]
205
0
            res = Merger::vertical_merge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
206
0
                                                 input_rs_readers, _output_rs_writer.get(),
207
0
                                                 get_avg_segment_rows(), way_num, &_stats);
208
0
        } else {
209
0
            res = Merger::vmerge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
210
0
                                         input_rs_readers, _output_rs_writer.get(), &_stats);
211
0
        }
212
213
0
        _tablet->last_compaction_status = res;
214
0
        if (!res.ok()) {
  Branch (214:13): [True: 0, False: 0]
215
0
            return res;
216
0
        }
217
        // 2. Merge the remaining inverted index files of the string type
218
0
        RETURN_IF_ERROR(do_inverted_index_compaction());
219
0
    }
220
221
0
    COUNTER_UPDATE(_merged_rows_counter, _stats.merged_rows);
Line
Count
Source
82
0
#define COUNTER_UPDATE(c, v) (c)->update(v)
222
0
    COUNTER_UPDATE(_filtered_rows_counter, _stats.filtered_rows);
Line
Count
Source
82
0
#define COUNTER_UPDATE(c, v) (c)->update(v)
223
224
    // 3. In the `build`, `_close_file_writers` is called to close the inverted index file writer and write the final compound index file.
225
0
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
226
0
                                   fmt::format("rowset writer build failed. output_version: {}",
227
0
                                               _output_version.to_string()));
228
229
    //RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get()));
230
231
    // Now we support delete in cumu compaction, to make all data in rowsets whose version
232
    // is below output_version to be delete in the future base compaction, we should carry
233
    // all delete predicate in the output rowset.
234
    // Output start version > 2 means we must set the delete predicate in the output rowset
235
0
    if (_allow_delete_in_cumu_compaction && _output_rowset->version().first > 2) {
  Branch (235:9): [True: 0, False: 0]
  Branch (235:9): [True: 0, False: 0]
  Branch (235:45): [True: 0, False: 0]
236
0
        DeletePredicatePB delete_predicate;
237
0
        std::accumulate(_input_rowsets.begin(), _input_rowsets.end(), &delete_predicate,
238
0
                        [](DeletePredicatePB* delete_predicate, const RowsetSharedPtr& rs) {
239
0
                            if (rs->rowset_meta()->has_delete_predicate()) {
  Branch (239:33): [True: 0, False: 0]
240
0
                                delete_predicate->MergeFrom(rs->rowset_meta()->delete_predicate());
241
0
                            }
242
0
                            return delete_predicate;
243
0
                        });
244
        // now version in delete_predicate is deprecated
245
0
        if (!delete_predicate.in_predicates().empty() ||
  Branch (245:13): [True: 0, False: 0]
246
0
            !delete_predicate.sub_predicates_v2().empty() ||
  Branch (246:13): [True: 0, False: 0]
247
0
            !delete_predicate.sub_predicates().empty()) {
  Branch (247:13): [True: 0, False: 0]
248
0
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
249
0
        }
250
0
    }
251
252
0
    _local_read_bytes_total = _stats.bytes_read_from_local;
253
0
    _remote_read_bytes_total = _stats.bytes_read_from_remote;
254
0
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(_local_read_bytes_total);
255
0
    DorisMetrics::instance()->remote_compaction_read_bytes_total->increment(
256
0
            _remote_read_bytes_total);
257
0
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
258
0
            _stats.cached_bytes_total);
259
260
0
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
Line
Count
Source
82
0
#define COUNTER_UPDATE(c, v) (c)->update(v)
261
0
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
Line
Count
Source
82
0
#define COUNTER_UPDATE(c, v) (c)->update(v)
262
0
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
Line
Count
Source
82
0
#define COUNTER_UPDATE(c, v) (c)->update(v)
263
264
0
    return check_correctness();
265
0
}
266
267
0
int64_t Compaction::get_avg_segment_rows() {
268
    // take care of empty rowset
269
    // input_rowsets_size is total disk_size of input_rowset, this size is the
270
    // final size after codec and compress, so expect dest segment file size
271
    // in disk is config::vertical_compaction_max_segment_size
272
0
    const auto& meta = _tablet->tablet_meta();
273
0
    if (meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
  Branch (273:9): [True: 0, False: 0]
274
0
        int64_t compaction_goal_size_mbytes = meta->time_series_compaction_goal_size_mbytes();
275
0
        return (compaction_goal_size_mbytes * 1024 * 1024 * 2) /
276
0
               (_input_rowsets_data_size / (_input_row_num + 1) + 1);
277
0
    }
278
0
    return config::vertical_compaction_max_segment_size /
279
0
           (_input_rowsets_data_size / (_input_row_num + 1) + 1);
280
0
}
281
282
CompactionMixin::CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet,
283
                                 const std::string& label)
284
72
        : Compaction(tablet, label), _engine(engine) {}
285
286
72
CompactionMixin::~CompactionMixin() {
287
72
    if (_state != CompactionState::SUCCESS && _output_rowset != nullptr) {
  Branch (287:9): [True: 72, False: 0]
  Branch (287:47): [True: 8, False: 64]
288
8
        if (!_output_rowset->is_local()) {
  Branch (288:13): [True: 0, False: 8]
289
0
            tablet()->record_unused_remote_rowset(_output_rowset->rowset_id(),
290
0
                                                  _output_rowset->rowset_meta()->resource_id(),
291
0
                                                  _output_rowset->num_segments());
292
0
            return;
293
0
        }
294
8
        _engine.add_unused_rowset(_output_rowset);
295
8
    }
296
72
}
297
298
186
Tablet* CompactionMixin::tablet() {
299
186
    return static_cast<Tablet*>(_tablet.get());
300
186
}
301
302
6
Status CompactionMixin::do_compact_ordered_rowsets() {
303
6
    RETURN_IF_ERROR(build_basic_info());
304
6
    RowsetWriterContext ctx;
305
6
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
306
307
6
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
308
6
              << ", output_version=" << _output_version;
309
    // link data to new rowset
310
6
    auto seg_id = 0;
311
6
    bool segments_key_bounds_truncated {false};
312
6
    std::vector<KeyBoundsPB> segment_key_bounds;
313
28
    for (auto rowset : _input_rowsets) {
  Branch (313:22): [True: 28, False: 6]
314
28
        RETURN_IF_ERROR(rowset->link_files_to(tablet()->tablet_path(),
315
28
                                              _output_rs_writer->rowset_id(), seg_id));
316
28
        seg_id += rowset->num_segments();
317
28
        segments_key_bounds_truncated |= rowset->is_segments_key_bounds_truncated();
318
28
        std::vector<KeyBoundsPB> key_bounds;
319
28
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
320
28
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
321
28
    }
322
    // build output rowset
323
6
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
324
6
    rowset_meta->set_num_rows(_input_row_num);
325
6
    rowset_meta->set_total_disk_size(_input_rowsets_data_size + _input_rowsets_index_size);
326
6
    rowset_meta->set_data_disk_size(_input_rowsets_data_size);
327
6
    rowset_meta->set_index_disk_size(_input_rowsets_index_size);
328
6
    rowset_meta->set_empty(_input_row_num == 0);
329
6
    rowset_meta->set_num_segments(_input_num_segments);
330
6
    rowset_meta->set_segments_overlap(NONOVERLAPPING);
331
6
    rowset_meta->set_rowset_state(VISIBLE);
332
6
    rowset_meta->set_segments_key_bounds_truncated(segments_key_bounds_truncated);
333
6
    rowset_meta->set_segments_key_bounds(segment_key_bounds);
334
6
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
335
6
    return Status::OK();
336
6
}
337
338
43
Status CompactionMixin::build_basic_info() {
339
164
    for (auto& rowset : _input_rowsets) {
  Branch (339:23): [True: 164, False: 43]
340
164
        const auto& rowset_meta = rowset->rowset_meta();
341
164
        auto index_size = rowset_meta->index_disk_size();
342
164
        auto total_size = rowset_meta->total_disk_size();
343
164
        auto data_size = rowset_meta->data_disk_size();
344
        // corrupted index size caused by bug before 2.1.5 or 3.0.0 version
345
        // try to get real index size from disk.
346
164
        if (index_size < 0 || index_size > total_size * 2) {
  Branch (346:13): [True: 0, False: 164]
  Branch (346:31): [True: 3, False: 161]
347
3
            LOG(ERROR) << "invalid index size:" << index_size << " total size:" << total_size
348
3
                       << " data size:" << data_size << " tablet:" << rowset_meta->tablet_id()
349
3
                       << " rowset:" << rowset_meta->rowset_id();
350
3
            index_size = 0;
351
3
            auto st = rowset->get_inverted_index_size(&index_size);
352
3
            if (!st.ok()) {
  Branch (352:17): [True: 0, False: 3]
353
0
                LOG(ERROR) << "failed to get inverted index size. res=" << st;
354
0
            }
355
3
        }
356
164
        _input_rowsets_data_size += data_size;
357
164
        _input_rowsets_index_size += index_size;
358
164
        _input_rowsets_total_size += total_size;
359
164
        _input_row_num += rowset->num_rows();
360
164
        _input_num_segments += rowset->num_segments();
361
164
    }
362
43
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_data_size);
Line
Count
Source
82
43
#define COUNTER_UPDATE(c, v) (c)->update(v)
363
43
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
Line
Count
Source
82
43
#define COUNTER_UPDATE(c, v) (c)->update(v)
364
43
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
Line
Count
Source
82
43
#define COUNTER_UPDATE(c, v) (c)->update(v)
365
366
43
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::build_basic_info",
367
42
                                      Status::OK());
368
369
42
    _output_version =
370
42
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
371
372
42
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
373
374
42
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
375
42
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
376
136
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
377
42
    _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
378
42
    if (!_cur_tablet_schema->need_record_variant_extended_schema()) {
  Branch (378:9): [True: 2, False: 40]
379
2
        RETURN_IF_ERROR(_tablet->get_compaction_schema(rowset_metas, _cur_tablet_schema));
380
2
    }
381
42
    return Status::OK();
382
42
}
383
384
12
bool CompactionMixin::handle_ordered_data_compaction() {
385
12
    if (!config::enable_ordered_data_compaction) {
  Branch (385:9): [True: 0, False: 12]
386
0
        return false;
387
0
    }
388
12
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
  Branch (388:9): [True: 0, False: 12]
389
12
        compaction_type() == ReaderType::READER_FULL_COMPACTION) {
  Branch (389:9): [True: 0, False: 12]
390
        // The remote file system and full compaction does not support to link files.
391
0
        return false;
392
0
    }
393
12
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (393:9): [True: 0, False: 12]
394
12
        _tablet->enable_unique_key_merge_on_write()) {
  Branch (394:9): [True: 0, False: 0]
395
0
        return false;
396
0
    }
397
398
12
    if (_tablet->tablet_meta()->tablet_schema()->skip_write_index_on_load()) {
  Branch (398:9): [True: 0, False: 12]
399
        // Expected to create index through normal compaction
400
0
        return false;
401
0
    }
402
403
    // check delete version: if compaction type is base compaction and
404
    // has a delete version, use original compaction
405
12
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION ||
  Branch (405:9): [True: 0, False: 12]
406
12
        (_allow_delete_in_cumu_compaction &&
  Branch (406:10): [True: 0, False: 12]
407
12
         compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION)) {
  Branch (407:10): [True: 0, False: 0]
408
0
        for (auto& rowset : _input_rowsets) {
  Branch (408:27): [True: 0, False: 0]
409
0
            if (rowset->rowset_meta()->has_delete_predicate()) {
  Branch (409:17): [True: 0, False: 0]
410
0
                return false;
411
0
            }
412
0
        }
413
0
    }
414
415
    // check if rowsets are tidy so we can just modify meta and do link
416
    // files to handle compaction
417
12
    auto input_size = _input_rowsets.size();
418
12
    std::string pre_max_key;
419
12
    bool pre_rs_key_bounds_truncated {false};
420
45
    for (auto i = 0; i < input_size; ++i) {
  Branch (420:22): [True: 39, False: 6]
421
39
        if (!is_rowset_tidy(pre_max_key, pre_rs_key_bounds_truncated, _input_rowsets[i])) {
  Branch (421:13): [True: 6, False: 33]
422
6
            if (i <= input_size / 2) {
  Branch (422:17): [True: 6, False: 0]
423
6
                return false;
424
6
            } else {
425
0
                _input_rowsets.resize(i);
426
0
                break;
427
0
            }
428
6
        }
429
39
    }
430
    // most rowset of current compaction is nonoverlapping
431
    // just handle nonoverlappint rowsets
432
6
    auto st = do_compact_ordered_rowsets();
433
6
    if (!st.ok()) {
  Branch (433:9): [True: 0, False: 6]
434
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
435
0
        _pending_rs_guard.drop();
436
0
    }
437
438
6
    return st.ok();
439
12
}
440
441
1
Status CompactionMixin::execute_compact() {
442
1
    uint32_t checksum_before;
443
1
    uint32_t checksum_after;
444
1
    bool enable_compaction_checksum = config::enable_compaction_checksum;
445
1
    if (enable_compaction_checksum) {
  Branch (445:9): [True: 0, False: 1]
446
0
        EngineChecksumTask checksum_task(_engine, _tablet->tablet_id(), _tablet->schema_hash(),
447
0
                                         _input_rowsets.back()->end_version(), &checksum_before);
448
0
        RETURN_IF_ERROR(checksum_task.execute());
449
0
    }
450
451
1
    auto* data_dir = tablet()->data_dir();
452
1
    int64_t permits = get_compaction_permits();
453
1
    data_dir->disks_compaction_score_increment(permits);
454
1
    data_dir->disks_compaction_num_increment(1);
455
456
1
    auto record_compaction_stats = [&](const doris::Exception& ex) {
457
1
        _tablet->compaction_count.fetch_add(1, std::memory_order_relaxed);
458
1
        data_dir->disks_compaction_score_increment(-permits);
459
1
        data_dir->disks_compaction_num_increment(-1);
460
1
    };
461
462
1
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(execute_compact_impl(permits), record_compaction_stats);
Line
Count
Source
134
1
    do {                                                                                         \
135
1
        try {                                                                                    \
136
1
            doris::enable_thread_catch_bad_alloc++;                                              \
137
1
            Defer defer {[&]() { doris::enable_thread_catch_bad_alloc--; }};                     \
138
1
            {                                                                                    \
139
1
                Status _status_ = (stmt);                                                        \
140
1
                if (UNLIKELY(!_status_.ok())) {                                                  \
141
0
                    exception_handler(doris::Exception());                                       \
142
0
                    return _status_;                                                             \
143
0
                }                                                                                \
144
1
            }                                                                                    \
145
1
        } catch (const doris::Exception& e) {                                                    \
146
0
            exception_handler(e);                                                                \
147
0
            if (e.code() == doris::ErrorCode::MEM_ALLOC_FAILED) {                                \
  Branch (147:17): [True: 0, False: 0]
148
0
                return Status::MemoryLimitExceeded(fmt::format(                                  \
149
0
                        "PreCatch error code:{}, {}, __FILE__:{}, __LINE__:{}, __FUNCTION__:{}", \
150
0
                        e.code(), e.to_string(), __FILE__, __LINE__, __PRETTY_FUNCTION__));      \
151
0
            }                                                                                    \
152
0
            return Status::Error<false>(e.code(), e.to_string());                                \
153
0
        }                                                                                        \
154
1
    } while (0);
  Branch (154:14): [Folded - Ignored]
463
1
    record_compaction_stats(doris::Exception());
464
465
1
    if (enable_compaction_checksum) {
  Branch (465:9): [True: 0, False: 1]
466
0
        EngineChecksumTask checksum_task(_engine, _tablet->tablet_id(), _tablet->schema_hash(),
467
0
                                         _input_rowsets.back()->end_version(), &checksum_after);
468
0
        RETURN_IF_ERROR(checksum_task.execute());
469
0
        if (checksum_before != checksum_after) {
  Branch (469:13): [True: 0, False: 0]
470
0
            return Status::InternalError(
471
0
                    "compaction tablet checksum not consistent, before={}, after={}, tablet_id={}",
472
0
                    checksum_before, checksum_after, _tablet->tablet_id());
473
0
        }
474
0
    }
475
476
1
    DorisMetrics::instance()->local_compaction_read_rows_total->increment(_input_row_num);
477
1
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(
478
1
            _input_rowsets_total_size);
479
480
1
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact", Status::OK());
481
482
0
    DorisMetrics::instance()->local_compaction_write_rows_total->increment(
483
0
            _output_rowset->num_rows());
484
0
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
485
0
            _output_rowset->total_disk_size());
486
487
0
    _load_segment_to_cache();
488
0
    return Status::OK();
489
1
}
490
491
1
Status CompactionMixin::execute_compact_impl(int64_t permits) {
492
1
    OlapStopWatch watch;
493
494
1
    if (handle_ordered_data_compaction()) {
  Branch (494:9): [True: 0, False: 1]
495
0
        RETURN_IF_ERROR(modify_rowsets());
496
0
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
497
0
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
498
0
                  << ", disk=" << tablet()->data_dir()->path()
499
0
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
500
0
                  << ", output_row_num=" << _output_rowset->num_rows()
501
0
                  << ", input_rowsets_data_size=" << _input_rowsets_data_size
502
0
                  << ", input_rowsets_index_size=" << _input_rowsets_index_size
503
0
                  << ", input_rowsets_total_size=" << _input_rowsets_total_size
504
0
                  << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
505
0
                  << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
506
0
                  << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
507
0
                  << ". elapsed time=" << watch.get_elapse_second() << "s.";
508
0
        _state = CompactionState::SUCCESS;
509
0
        return Status::OK();
510
0
    }
511
1
    RETURN_IF_ERROR(build_basic_info());
512
513
1
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact_impl",
514
0
                                      Status::OK());
515
516
0
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
Line
Count
Source
41
0
#define VLOG_DEBUG VLOG(7)
517
518
0
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
519
0
              << ", output_version=" << _output_version << ", permits: " << permits;
520
521
0
    RETURN_IF_ERROR(merge_input_rowsets());
522
523
0
    RETURN_IF_ERROR(modify_rowsets());
524
525
0
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
526
0
    DCHECK(cumu_policy);
527
0
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << _is_vertical
528
0
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
529
0
              << ", current_max_version=" << tablet()->max_version().second
530
0
              << ", disk=" << tablet()->data_dir()->path() << ", segments=" << _input_num_segments
531
0
              << ", input_rowsets_data_size=" << _input_rowsets_data_size
532
0
              << ", input_rowsets_index_size=" << _input_rowsets_index_size
533
0
              << ", input_rowsets_total_size=" << _input_rowsets_total_size
534
0
              << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
535
0
              << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
536
0
              << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
537
0
              << ", input_row_num=" << _input_row_num
538
0
              << ", output_row_num=" << _output_rowset->num_rows()
539
0
              << ", filtered_row_num=" << _stats.filtered_rows
540
0
              << ", merged_row_num=" << _stats.merged_rows
541
0
              << ". elapsed time=" << watch.get_elapse_second()
542
0
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
543
0
              << ", compact_row_per_second=" << int(_input_row_num / watch.get_elapse_second());
544
545
0
    _state = CompactionState::SUCCESS;
546
547
0
    return Status::OK();
548
0
}
549
550
33
Status Compaction::do_inverted_index_compaction() {
551
33
    const auto& ctx = _output_rs_writer->context();
552
33
    if (!config::inverted_index_compaction_enable || _input_row_num <= 0 ||
  Branch (552:9): [True: 12, False: 21]
  Branch (552:54): [True: 1, False: 20]
553
33
        ctx.columns_to_do_index_compaction.empty()) {
  Branch (553:9): [True: 1, False: 19]
554
14
        return Status::OK();
555
14
    }
556
557
19
    auto error_handler = [this](int64_t index_id, int64_t column_uniq_id) {
558
0
        LOG(WARNING) << "failed to do index compaction"
559
0
                     << ". tablet=" << _tablet->tablet_id() << ". column uniq id=" << column_uniq_id
560
0
                     << ". index_id=" << index_id;
561
0
        for (auto& rowset : _input_rowsets) {
  Branch (561:27): [True: 0, False: 0]
562
0
            rowset->set_skip_index_compaction(column_uniq_id);
563
0
            LOG(INFO) << "mark skipping inverted index compaction next time"
564
0
                      << ". tablet=" << _tablet->tablet_id() << ", rowset=" << rowset->rowset_id()
565
0
                      << ", column uniq id=" << column_uniq_id << ", index_id=" << index_id;
566
0
        }
567
0
    };
568
569
19
    DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_rowid_conversion_null",
Line
Count
Source
37
19
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
570
19
                    { _stats.rowid_conversion = nullptr; })
571
19
    if (!_stats.rowid_conversion) {
  Branch (571:9): [True: 0, False: 19]
572
0
        LOG(WARNING) << "failed to do index compaction, rowid conversion is null"
573
0
                     << ". tablet=" << _tablet->tablet_id()
574
0
                     << ", input row number=" << _input_row_num;
575
0
        mark_skip_index_compaction(ctx, error_handler);
576
577
0
        return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
578
0
                "failed to do index compaction, rowid conversion is null. tablet={}",
579
0
                _tablet->tablet_id());
580
0
    }
581
582
19
    OlapStopWatch inverted_watch;
583
584
    // translation vec
585
    // <<dest_idx_num, dest_docId>>
586
    // the first level vector: index indicates src segment.
587
    // the second level vector: index indicates row id of source segment,
588
    // value indicates row id of destination segment.
589
    // <UINT32_MAX, UINT32_MAX> indicates current row not exist.
590
19
    const auto& trans_vec = _stats.rowid_conversion->get_rowid_conversion_map();
591
592
    // source rowset,segment -> index_id
593
19
    const auto& src_seg_to_id_map = _stats.rowid_conversion->get_src_segment_to_id_map();
594
595
    // dest rowset id
596
19
    RowsetId dest_rowset_id = _stats.rowid_conversion->get_dst_rowset_id();
597
    // dest segment id -> num rows
598
19
    std::vector<uint32_t> dest_segment_num_rows;
599
19
    RETURN_IF_ERROR(_output_rs_writer->get_segment_num_rows(&dest_segment_num_rows));
600
601
19
    auto src_segment_num = src_seg_to_id_map.size();
602
19
    auto dest_segment_num = dest_segment_num_rows.size();
603
604
    // when all the input rowsets are deleted, the output rowset will be empty and dest_segment_num will be 0.
605
19
    if (dest_segment_num <= 0) {
  Branch (605:9): [True: 2, False: 17]
606
2
        LOG(INFO) << "skip doing index compaction due to no output segments"
607
2
                  << ". tablet=" << _tablet->tablet_id() << ", input row number=" << _input_row_num
608
2
                  << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
609
2
        return Status::OK();
610
2
    }
611
612
    // Only write info files when debug index compaction is enabled.
613
    // The files are used to debug index compaction and works with index_tool.
614
17
    if (config::debug_inverted_index_compaction) {
  Branch (614:9): [True: 0, False: 17]
615
        // src index files
616
        // format: rowsetId_segmentId
617
0
        std::vector<std::string> src_index_files(src_segment_num);
618
0
        for (const auto& m : src_seg_to_id_map) {
  Branch (618:28): [True: 0, False: 0]
619
0
            std::pair<RowsetId, uint32_t> p = m.first;
620
0
            src_index_files[m.second] = p.first.to_string() + "_" + std::to_string(p.second);
621
0
        }
622
623
        // dest index files
624
        // format: rowsetId_segmentId
625
0
        std::vector<std::string> dest_index_files(dest_segment_num);
626
0
        for (int i = 0; i < dest_segment_num; ++i) {
  Branch (626:25): [True: 0, False: 0]
627
0
            auto prefix = dest_rowset_id.to_string() + "_" + std::to_string(i);
628
0
            dest_index_files[i] = prefix;
629
0
        }
630
631
0
        auto write_json_to_file = [&](const nlohmann::json& json_obj,
632
0
                                      const std::string& file_name) {
633
0
            io::FileWriterPtr file_writer;
634
0
            std::string file_path =
635
0
                    fmt::format("{}/{}.json", std::string(getenv("LOG_DIR")), file_name);
636
0
            RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &file_writer));
637
0
            RETURN_IF_ERROR(file_writer->append(json_obj.dump()));
638
0
            RETURN_IF_ERROR(file_writer->append("\n"));
639
0
            return file_writer->close();
640
0
        };
641
642
        // Convert trans_vec to JSON and print it
643
0
        nlohmann::json trans_vec_json = trans_vec;
644
0
        auto output_version =
645
0
                _output_version.to_string().substr(1, _output_version.to_string().size() - 2);
646
0
        RETURN_IF_ERROR(write_json_to_file(
647
0
                trans_vec_json,
648
0
                fmt::format("trans_vec_{}_{}", _tablet->tablet_id(), output_version)));
649
650
0
        nlohmann::json src_index_files_json = src_index_files;
651
0
        RETURN_IF_ERROR(write_json_to_file(
652
0
                src_index_files_json,
653
0
                fmt::format("src_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
654
655
0
        nlohmann::json dest_index_files_json = dest_index_files;
656
0
        RETURN_IF_ERROR(write_json_to_file(
657
0
                dest_index_files_json,
658
0
                fmt::format("dest_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
659
660
0
        nlohmann::json dest_segment_num_rows_json = dest_segment_num_rows;
661
0
        RETURN_IF_ERROR(write_json_to_file(
662
0
                dest_segment_num_rows_json,
663
0
                fmt::format("dest_seg_num_rows_{}_{}", _tablet->tablet_id(), output_version)));
664
0
    }
665
666
    // create index_writer to compaction indexes
667
17
    std::unordered_map<RowsetId, Rowset*> rs_id_to_rowset_map;
668
45
    for (auto&& rs : _input_rowsets) {
  Branch (668:20): [True: 45, False: 17]
669
45
        rs_id_to_rowset_map.emplace(rs->rowset_id(), rs.get());
670
45
    }
671
672
    // src index dirs
673
17
    std::vector<std::unique_ptr<InvertedIndexFileReader>> inverted_index_file_readers(
674
17
            src_segment_num);
675
114
    for (const auto& m : src_seg_to_id_map) {
  Branch (675:24): [True: 114, False: 17]
676
114
        const auto& [rowset_id, seg_id] = m.first;
677
678
114
        auto find_it = rs_id_to_rowset_map.find(rowset_id);
679
114
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_find_rowset_error",
Line
Count
Source
37
114
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
680
114
                        { find_it = rs_id_to_rowset_map.end(); })
681
114
        if (find_it == rs_id_to_rowset_map.end()) [[unlikely]] {
  Branch (681:13): [True: 0, False: 114]
682
0
            LOG(WARNING) << "failed to do index compaction, cannot find rowset. tablet_id="
683
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string();
684
0
            mark_skip_index_compaction(ctx, error_handler);
685
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
686
0
                    "failed to do index compaction, cannot find rowset. tablet_id={} rowset_id={}",
687
0
                    _tablet->tablet_id(), rowset_id.to_string());
688
0
        }
689
690
114
        auto* rowset = find_it->second;
691
114
        auto fs = rowset->rowset_meta()->fs();
692
114
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_get_fs_error", { fs = nullptr; })
Line
Count
Source
37
114
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
693
114
        if (!fs) {
  Branch (693:13): [True: 0, False: 114]
694
0
            LOG(WARNING) << "failed to do index compaction, get fs failed. resource_id="
695
0
                         << rowset->rowset_meta()->resource_id();
696
0
            mark_skip_index_compaction(ctx, error_handler);
697
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
698
0
                    "get fs failed, resource_id={}", rowset->rowset_meta()->resource_id());
699
0
        }
700
701
114
        auto seg_path = rowset->segment_path(seg_id);
702
114
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_seg_path_nullptr", {
Line
Count
Source
37
114
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
703
114
            seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
704
114
                    "do_inverted_index_compaction_seg_path_nullptr"));
705
114
        })
706
114
        if (!seg_path.has_value()) {
  Branch (706:13): [True: 0, False: 114]
707
0
            LOG(WARNING) << "failed to do index compaction, get segment path failed. tablet_id="
708
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string()
709
0
                         << " seg_id=" << seg_id;
710
0
            mark_skip_index_compaction(ctx, error_handler);
711
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
712
0
                    "get segment path failed. tablet_id={} rowset_id={} seg_id={}",
713
0
                    _tablet->tablet_id(), rowset_id.to_string(), seg_id);
714
0
        }
715
114
        auto inverted_index_file_reader = std::make_unique<InvertedIndexFileReader>(
716
114
                fs,
717
114
                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path.value())},
718
114
                _cur_tablet_schema->get_inverted_index_storage_format(),
719
114
                rowset->rowset_meta()->inverted_index_file_info(seg_id));
720
114
        auto st = inverted_index_file_reader->init(config::inverted_index_read_buffer_size);
721
114
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_init_inverted_index_file_reader",
Line
Count
Source
37
114
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
722
114
                        {
723
114
                            st = Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
724
114
                                    "debug point: "
725
114
                                    "Compaction::do_inverted_index_compaction_init_inverted_index_"
726
114
                                    "file_reader error");
727
114
                        })
728
114
        if (!st.ok()) {
  Branch (728:13): [True: 0, False: 114]
729
0
            LOG(WARNING) << "failed to do index compaction, init inverted index file reader "
730
0
                            "failed. tablet_id="
731
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string()
732
0
                         << " seg_id=" << seg_id;
733
0
            mark_skip_index_compaction(ctx, error_handler);
734
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
735
0
                    "init inverted index file reader failed. tablet_id={} rowset_id={} seg_id={}",
736
0
                    _tablet->tablet_id(), rowset_id.to_string(), seg_id);
737
0
        }
738
114
        inverted_index_file_readers[m.second] = std::move(inverted_index_file_reader);
739
114
    }
740
741
    // dest index files
742
    // format: rowsetId_segmentId
743
17
    auto& inverted_index_file_writers = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get())
744
17
                                                ->inverted_index_file_writers();
745
17
    DBUG_EXECUTE_IF(
Line
Count
Source
37
17
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
746
17
            "Compaction::do_inverted_index_compaction_inverted_index_file_writers_size_error",
747
17
            { inverted_index_file_writers.clear(); })
748
17
    if (inverted_index_file_writers.size() != dest_segment_num) {
  Branch (748:9): [True: 0, False: 17]
749
0
        LOG(WARNING) << "failed to do index compaction, dest segment num not match. tablet_id="
750
0
                     << _tablet->tablet_id() << " dest_segment_num=" << dest_segment_num
751
0
                     << " inverted_index_file_writers.size()="
752
0
                     << inverted_index_file_writers.size();
753
0
        mark_skip_index_compaction(ctx, error_handler);
754
0
        return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
755
0
                "dest segment num not match. tablet_id={} dest_segment_num={} "
756
0
                "inverted_index_file_writers.size()={}",
757
0
                _tablet->tablet_id(), dest_segment_num, inverted_index_file_writers.size());
758
0
    }
759
760
    // use tmp file dir to store index files
761
17
    auto tmp_file_dir = ExecEnv::GetInstance()->get_tmp_file_dirs()->get_tmp_file_dir();
762
17
    auto index_tmp_path = tmp_file_dir / dest_rowset_id.to_string();
763
17
    LOG(INFO) << "start index compaction"
764
17
              << ". tablet=" << _tablet->tablet_id() << ", source index size=" << src_segment_num
765
17
              << ", destination index size=" << dest_segment_num << ".";
766
767
17
    Status status = Status::OK();
768
308
    for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
  Branch (768:32): [True: 308, False: 17]
769
308
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
770
308
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
771
308
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_can_not_find_index_meta",
Line
Count
Source
37
308
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
772
308
                        { index_metas.clear(); })
773
308
        if (index_metas.empty()) {
  Branch (773:13): [True: 0, False: 308]
774
0
            status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
775
0
                    fmt::format("Can not find index_meta for col {}", col.name()));
776
0
            LOG(WARNING) << "failed to do index compaction, can not find index_meta for column"
777
0
                         << ". tablet=" << _tablet->tablet_id()
778
0
                         << ", column uniq id=" << column_uniq_id;
779
0
            error_handler(-1, column_uniq_id);
780
0
            break;
781
0
        }
782
310
        for (const auto& index_meta : index_metas) {
  Branch (782:37): [True: 310, False: 308]
783
310
            std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
784
310
            try {
785
310
                std::vector<std::unique_ptr<DorisCompoundReader>> src_idx_dirs(src_segment_num);
786
1.33k
                for (int src_segment_id = 0; src_segment_id < src_segment_num; src_segment_id++) {
  Branch (786:46): [True: 1.02k, False: 310]
787
1.02k
                    auto res = inverted_index_file_readers[src_segment_id]->open(index_meta);
788
1.02k
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
Line
Count
Source
37
1.02k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
789
1.02k
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
790
1.02k
                                "debug point: Compaction::open_index_file_reader error"));
791
1.02k
                    })
792
1.02k
                    if (!res.has_value()) {
  Branch (792:25): [True: 0, False: 1.02k]
793
0
                        LOG(WARNING) << "failed to do index compaction, open inverted index file "
794
0
                                        "reader failed"
795
0
                                     << ". tablet=" << _tablet->tablet_id()
796
0
                                     << ", column uniq id=" << column_uniq_id
797
0
                                     << ", src_segment_id=" << src_segment_id;
798
0
                        throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
799
0
                                        res.error().msg());
800
0
                    }
801
1.02k
                    src_idx_dirs[src_segment_id] = std::move(res.value());
802
1.02k
                }
803
731
                for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
  Branch (803:47): [True: 421, False: 310]
804
421
                     dest_segment_id++) {
805
421
                    auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
806
421
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
Line
Count
Source
37
421
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
807
421
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
808
421
                                "debug point: Compaction::open_inverted_index_file_writer error"));
809
421
                    })
810
421
                    if (!res.has_value()) {
  Branch (810:25): [True: 0, False: 421]
811
0
                        LOG(WARNING) << "failed to do index compaction, open inverted index file "
812
0
                                        "writer failed"
813
0
                                     << ". tablet=" << _tablet->tablet_id()
814
0
                                     << ", column uniq id=" << column_uniq_id
815
0
                                     << ", dest_segment_id=" << dest_segment_id;
816
0
                        throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
817
0
                                        res.error().msg());
818
0
                    }
819
                    // Destination directories in dest_index_dirs do not need to be deconstructed,
820
                    // but their lifecycle must be managed by inverted_index_file_writers.
821
421
                    dest_index_dirs[dest_segment_id] = res.value().get();
822
421
                }
823
310
                auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
824
310
                                         index_tmp_path.native(), trans_vec, dest_segment_num_rows);
825
310
                if (!st.ok()) {
  Branch (825:21): [True: 0, False: 310]
826
0
                    error_handler(index_meta->index_id(), column_uniq_id);
827
0
                    status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(st.msg());
828
0
                }
829
310
            } catch (CLuceneError& e) {
830
0
                error_handler(index_meta->index_id(), column_uniq_id);
831
0
                status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
832
0
            } catch (const Exception& e) {
833
0
                error_handler(index_meta->index_id(), column_uniq_id);
834
0
                status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
835
0
            }
836
310
        }
837
308
    }
838
839
    // check index compaction status. If status is not ok, we should return error and end this compaction round.
840
17
    if (!status.ok()) {
  Branch (840:9): [True: 0, False: 17]
841
0
        return status;
842
0
    }
843
17
    LOG(INFO) << "succeed to do index compaction"
844
17
              << ". tablet=" << _tablet->tablet_id()
845
17
              << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
846
847
17
    return Status::OK();
848
17
}
849
850
void Compaction::mark_skip_index_compaction(
851
        const RowsetWriterContext& context,
852
0
        const std::function<void(int64_t, int64_t)>& error_handler) {
853
0
    for (auto&& column_uniq_id : context.columns_to_do_index_compaction) {
  Branch (853:32): [True: 0, False: 0]
854
0
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
855
0
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
856
0
        DBUG_EXECUTE_IF("Compaction::mark_skip_index_compaction_can_not_find_index_meta",
Line
Count
Source
37
0
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
857
0
                        { index_metas.clear(); })
858
0
        if (index_metas.empty()) {
  Branch (858:13): [True: 0, False: 0]
859
0
            LOG(WARNING) << "mark skip index compaction, can not find index_meta for column"
860
0
                         << ". tablet=" << _tablet->tablet_id()
861
0
                         << ", column uniq id=" << column_uniq_id;
862
0
            error_handler(-1, column_uniq_id);
863
0
            continue;
864
0
        }
865
0
        for (const auto& index_meta : index_metas) {
  Branch (865:37): [True: 0, False: 0]
866
0
            error_handler(index_meta->index_id(), column_uniq_id);
867
0
        }
868
0
    }
869
0
}
870
871
22
void Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
872
419
    for (const auto& index : _cur_tablet_schema->inverted_indexes()) {
  Branch (872:28): [True: 419, False: 22]
873
419
        auto col_unique_ids = index->col_unique_ids();
874
        // check if column unique ids is empty to avoid crash
875
419
        if (col_unique_ids.empty()) {
  Branch (875:13): [True: 1, False: 418]
876
1
            LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] index[" << index->index_id()
877
1
                         << "] has no column unique id, will skip index compaction."
878
1
                         << " tablet_schema=" << _cur_tablet_schema->dump_full_schema();
879
1
            continue;
880
1
        }
881
418
        auto col_unique_id = col_unique_ids[0];
882
418
        if (!_cur_tablet_schema->has_column_unique_id(col_unique_id)) {
  Branch (882:13): [True: 0, False: 418]
883
0
            LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] column_unique_id["
884
0
                         << col_unique_id << "] not found, will skip index compaction";
885
0
            continue;
886
0
        }
887
        // Avoid doing inverted index compaction on non-slice type columns
888
418
        if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
  Branch (888:13): [True: 24, False: 394]
889
24
            continue;
890
24
        }
891
892
        // if index properties are different, index compaction maybe needs to be skipped.
893
394
        bool is_continue = false;
894
394
        std::optional<std::map<std::string, std::string>> first_properties;
895
1.30k
        for (const auto& rowset : _input_rowsets) {
  Branch (895:33): [True: 1.30k, False: 389]
896
1.30k
            auto tablet_indexs = rowset->tablet_schema()->inverted_indexs(col_unique_id);
897
            // no inverted index or index id is different from current index id
898
1.30k
            auto it = std::find_if(tablet_indexs.begin(), tablet_indexs.end(),
899
1.30k
                                   [&index](const auto& tablet_index) {
900
1.30k
                                       return tablet_index->index_id() == index->index_id();
901
1.30k
                                   });
902
1.30k
            if (it != tablet_indexs.end()) {
  Branch (902:17): [True: 1.30k, False: 2]
903
1.30k
                const auto* tablet_index = *it;
904
1.30k
                auto properties = tablet_index->properties();
905
1.30k
                if (!first_properties.has_value()) {
  Branch (905:21): [True: 392, False: 912]
906
392
                    first_properties = properties;
907
912
                } else {
908
912
                    DBUG_EXECUTE_IF(
Line
Count
Source
37
912
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
909
912
                            "Compaction::do_inverted_index_compaction_index_properties_different",
910
912
                            { properties.emplace("dummy_key", "dummy_value"); })
911
912
                    if (properties != first_properties.value()) {
  Branch (911:25): [True: 3, False: 909]
912
3
                        is_continue = true;
913
3
                        break;
914
3
                    }
915
912
                }
916
1.30k
            } else {
917
2
                is_continue = true;
918
2
                break;
919
2
            }
920
1.30k
        }
921
394
        if (is_continue) {
  Branch (921:13): [True: 5, False: 389]
922
5
            continue;
923
5
        }
924
1.29k
        auto has_inverted_index = [&](const RowsetSharedPtr& src_rs) {
925
1.29k
            auto* rowset = static_cast<BetaRowset*>(src_rs.get());
926
1.29k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_is_skip_index_compaction",
Line
Count
Source
37
1.29k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
927
1.29k
                            { rowset->set_skip_index_compaction(col_unique_id); })
928
1.29k
            if (rowset->is_skip_index_compaction(col_unique_id)) {
  Branch (928:17): [True: 1, False: 1.29k]
929
1
                LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] rowset["
930
1
                             << rowset->rowset_id() << "] column_unique_id[" << col_unique_id
931
1
                             << "] skip inverted index compaction due to last failure";
932
1
                return false;
933
1
            }
934
935
1.29k
            auto fs = rowset->rowset_meta()->fs();
936
1.29k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_get_fs_error",
Line
Count
Source
37
1.29k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
937
1.29k
                            { fs = nullptr; })
938
1.29k
            if (!fs) {
  Branch (938:17): [True: 2, False: 1.29k]
939
2
                LOG(WARNING) << "get fs failed, resource_id="
940
2
                             << rowset->rowset_meta()->resource_id();
941
2
                return false;
942
2
            }
943
944
1.29k
            auto index_metas = rowset->tablet_schema()->inverted_indexs(col_unique_id);
945
1.29k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_meta_nullptr",
Line
Count
Source
37
1.29k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
946
1.29k
                            { index_metas.clear(); })
947
1.29k
            if (index_metas.empty()) {
  Branch (947:17): [True: 0, False: 1.29k]
948
0
                LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] column_unique_id["
949
0
                             << col_unique_id << "] index meta is null, will skip index compaction";
950
0
                return false;
951
0
            }
952
1.30k
            for (const auto& index_meta : index_metas) {
  Branch (952:41): [True: 1.30k, False: 1.29k]
953
2.61k
                for (auto i = 0; i < rowset->num_segments(); i++) {
  Branch (953:34): [True: 1.31k, False: 1.30k]
954
                    // TODO: inverted_index_path
955
1.31k
                    auto seg_path = rowset->segment_path(i);
956
1.31k
                    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_seg_path_nullptr", {
Line
Count
Source
37
1.31k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
957
1.31k
                        seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
958
1.31k
                                "construct_skip_inverted_index_seg_path_nullptr"));
959
1.31k
                    })
960
1.31k
                    if (!seg_path) {
  Branch (960:25): [True: 0, False: 1.31k]
961
0
                        LOG(WARNING) << seg_path.error();
962
0
                        return false;
963
0
                    }
964
965
1.31k
                    std::string index_file_path;
966
1.31k
                    try {
967
1.31k
                        auto inverted_index_file_reader = std::make_unique<InvertedIndexFileReader>(
968
1.31k
                                fs,
969
1.31k
                                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
970
1.31k
                                        seg_path.value())},
971
1.31k
                                _cur_tablet_schema->get_inverted_index_storage_format(),
972
1.31k
                                rowset->rowset_meta()->inverted_index_file_info(i));
973
1.31k
                        auto st = inverted_index_file_reader->init(
974
1.31k
                                config::inverted_index_read_buffer_size);
975
1.31k
                        index_file_path =
976
1.31k
                                inverted_index_file_reader->get_index_file_path(index_meta);
977
1.31k
                        DBUG_EXECUTE_IF(
Line
Count
Source
37
1.31k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
978
1.31k
                                "Compaction::construct_skip_inverted_index_index_file_reader_init_"
979
1.31k
                                "status_not_ok",
980
1.31k
                                {
981
1.31k
                                    st = Status::Error<ErrorCode::INTERNAL_ERROR>(
982
1.31k
                                            "debug point: "
983
1.31k
                                            "construct_skip_inverted_index_index_file_reader_init_"
984
1.31k
                                            "status_"
985
1.31k
                                            "not_ok");
986
1.31k
                                })
987
1.31k
                        if (!st.ok()) {
  Branch (987:29): [True: 0, False: 1.31k]
988
0
                            LOG(WARNING) << "init index " << index_file_path << " error:" << st;
989
0
                            return false;
990
0
                        }
991
992
                        // check index meta
993
1.31k
                        auto result = inverted_index_file_reader->open(index_meta);
994
1.31k
                        DBUG_EXECUTE_IF(
Line
Count
Source
37
1.31k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
995
1.31k
                                "Compaction::construct_skip_inverted_index_index_file_reader_open_"
996
1.31k
                                "error",
997
1.31k
                                {
998
1.31k
                                    result = ResultError(
999
1.31k
                                            Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1000
1.31k
                                                    "CLuceneError occur when open idx file"));
1001
1.31k
                                })
1002
1.31k
                        if (!result.has_value()) {
  Branch (1002:29): [True: 0, False: 1.31k]
1003
0
                            LOG(WARNING) << "open index " << index_file_path
1004
0
                                         << " error:" << result.error();
1005
0
                            return false;
1006
0
                        }
1007
1.31k
                        auto reader = std::move(result.value());
1008
1.31k
                        std::vector<std::string> files;
1009
1.31k
                        reader->list(&files);
1010
1.31k
                        reader->close();
1011
1.31k
                        DBUG_EXECUTE_IF(
Line
Count
Source
37
1.31k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
1012
1.31k
                                "Compaction::construct_skip_inverted_index_index_reader_close_"
1013
1.31k
                                "error",
1014
1.31k
                                { _CLTHROWA(CL_ERR_IO, "debug point: reader close error"); })
1015
1016
1.31k
                        DBUG_EXECUTE_IF(
Line
Count
Source
37
1.31k
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
1017
1.31k
                                "Compaction::construct_skip_inverted_index_index_files_count",
1018
1.31k
                                { files.clear(); })
1019
1020
                        // why is 3?
1021
                        // slice type index file at least has 3 files: null_bitmap, segments_N, segments.gen
1022
1.31k
                        if (files.size() < 3) {
  Branch (1022:29): [True: 0, False: 1.31k]
1023
0
                            LOG(WARNING)
1024
0
                                    << "tablet[" << _tablet->tablet_id() << "] column_unique_id["
1025
0
                                    << col_unique_id << "]," << index_file_path
1026
0
                                    << " is corrupted, will skip index compaction";
1027
0
                            return false;
1028
0
                        }
1029
1.31k
                    } catch (CLuceneError& err) {
1030
0
                        LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] column_unique_id["
1031
0
                                     << col_unique_id << "] open index[" << index_file_path
1032
0
                                     << "], will skip index compaction, error:" << err.what();
1033
0
                        return false;
1034
0
                    }
1035
1.31k
                }
1036
1.30k
            }
1037
1038
1.29k
            return true;
1039
1.29k
        };
1040
1041
389
        bool all_have_inverted_index = std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1042
389
                                                   std::move(has_inverted_index));
1043
1044
389
        if (all_have_inverted_index) {
  Branch (1044:13): [True: 386, False: 3]
1045
386
            ctx.columns_to_do_index_compaction.insert(col_unique_id);
1046
386
        }
1047
389
    }
1048
22
}
1049
1050
42
Status CompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1051
    // only do index compaction for dup_keys and unique_keys with mow enabled
1052
42
    if (config::inverted_index_compaction_enable &&
  Branch (1052:9): [True: 22, False: 20]
1053
42
        (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (1053:12): [True: 5, False: 17]
1054
22
           _tablet->enable_unique_key_merge_on_write()) ||
  Branch (1054:12): [True: 5, False: 0]
1055
22
          _tablet->keys_type() == KeysType::DUP_KEYS))) {
  Branch (1055:11): [True: 17, False: 0]
1056
22
        construct_index_compaction_columns(ctx);
1057
22
    }
1058
42
    ctx.version = _output_version;
1059
42
    ctx.rowset_state = VISIBLE;
1060
42
    ctx.segments_overlap = NONOVERLAPPING;
1061
42
    ctx.tablet_schema = _cur_tablet_schema;
1062
42
    ctx.newest_write_timestamp = _newest_write_timestamp;
1063
42
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1064
42
    ctx.compaction_type = compaction_type();
1065
42
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1066
42
    _pending_rs_guard = _engine.add_pending_rowset(ctx);
1067
42
    return Status::OK();
1068
42
}
1069
1070
0
Status CompactionMixin::modify_rowsets() {
1071
0
    std::vector<RowsetSharedPtr> output_rowsets;
1072
0
    output_rowsets.push_back(_output_rowset);
1073
1074
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (1074:9): [True: 0, False: 0]
1075
0
        _tablet->enable_unique_key_merge_on_write()) {
  Branch (1075:9): [True: 0, False: 0]
1076
0
        Version version = tablet()->max_version();
1077
0
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
1078
0
        std::unique_ptr<RowLocationSet> missed_rows;
1079
0
        if ((config::enable_missing_rows_correctness_check ||
  Branch (1079:14): [True: 0, False: 0]
1080
0
             config::enable_mow_compaction_correctness_check_core) &&
  Branch (1080:14): [True: 0, False: 0]
1081
0
            !_allow_delete_in_cumu_compaction &&
  Branch (1081:13): [True: 0, False: 0]
1082
0
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
  Branch (1082:13): [True: 0, False: 0]
1083
0
            missed_rows = std::make_unique<RowLocationSet>();
1084
0
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
1085
0
        }
1086
0
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1087
0
        if (config::enable_rowid_conversion_correctness_check) {
  Branch (1087:13): [True: 0, False: 0]
1088
0
            location_map = std::make_unique<std::map<RowsetSharedPtr, RowLocationPairList>>();
1089
0
            LOG(INFO) << "Location Map inited succ for tablet:" << _tablet->tablet_id();
1090
0
        }
1091
        // Convert the delete bitmap of the input rowsets to output rowset.
1092
        // New loads are not blocked, so some keys of input rowsets might
1093
        // be deleted during the time. We need to deal with delete bitmap
1094
        // of incremental data later.
1095
        // TODO(LiaoXin): check if there are duplicate keys
1096
0
        std::size_t missed_rows_size = 0;
1097
0
        tablet()->calc_compaction_output_rowset_delete_bitmap(
1098
0
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1099
0
                location_map.get(), *_tablet->tablet_meta()->delete_bitmap(),
1100
0
                &output_rowset_delete_bitmap);
1101
0
        if (missed_rows) {
  Branch (1101:13): [True: 0, False: 0]
1102
0
            missed_rows_size = missed_rows->size();
1103
0
            std::size_t merged_missed_rows_size = _stats.merged_rows;
1104
0
            if (!_tablet->tablet_meta()->tablet_schema()->cluster_key_idxes().empty()) {
  Branch (1104:17): [True: 0, False: 0]
1105
0
                merged_missed_rows_size += _stats.filtered_rows;
1106
0
            }
1107
1108
            // Suppose a heavy schema change process on BE converting tablet A to tablet B.
1109
            // 1. during schema change double write, new loads write [X-Y] on tablet B.
1110
            // 2. rowsets with version [a],[a+1],...,[b-1],[b] on tablet B are picked for cumu compaction(X<=a<b<=Y).(cumu compaction
1111
            //    on new tablet during schema change double write is allowed after https://github.com/apache/doris/pull/16470)
1112
            // 3. schema change remove all rowsets on tablet B before version Z(b<=Z<=Y) before it begins to convert historical rowsets.
1113
            // 4. schema change finishes.
1114
            // 5. cumu compation begins on new tablet with version [a],...,[b]. If there are duplicate keys between these rowsets,
1115
            //    the compaction check will fail because these rowsets have skipped to calculate delete bitmap in commit phase and
1116
            //    publish phase because tablet B is in NOT_READY state when writing.
1117
1118
            // Considering that the cumu compaction will fail finally in this situation because `Tablet::modify_rowsets` will check if rowsets in
1119
            // `to_delete`(_input_rowsets) still exist in tablet's `_rs_version_map`, we can just skip to check missed rows here.
1120
0
            bool need_to_check_missed_rows = true;
1121
0
            {
1122
0
                std::shared_lock rlock(_tablet->get_header_lock());
1123
0
                need_to_check_missed_rows =
1124
0
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1125
0
                                    [&](const RowsetSharedPtr& rowset) {
1126
0
                                        return tablet()->rowset_exists_unlocked(rowset);
1127
0
                                    });
1128
0
            }
1129
1130
0
            if (_tablet->tablet_state() == TABLET_RUNNING &&
  Branch (1130:17): [True: 0, False: 0]
1131
0
                merged_missed_rows_size != missed_rows_size && need_to_check_missed_rows) {
  Branch (1131:17): [True: 0, False: 0]
  Branch (1131:64): [True: 0, False: 0]
1132
0
                std::stringstream ss;
1133
0
                ss << "cumulative compaction: the merged rows(" << _stats.merged_rows
1134
0
                   << "), filtered rows(" << _stats.filtered_rows
1135
0
                   << ") is not equal to missed rows(" << missed_rows_size
1136
0
                   << ") in rowid conversion, tablet_id: " << _tablet->tablet_id()
1137
0
                   << ", table_id:" << _tablet->table_id();
1138
0
                if (missed_rows_size == 0) {
  Branch (1138:21): [True: 0, False: 0]
1139
0
                    ss << ", debug info: ";
1140
0
                    DeleteBitmap subset_map(_tablet->tablet_id());
1141
0
                    for (auto rs : _input_rowsets) {
  Branch (1141:34): [True: 0, False: 0]
1142
0
                        _tablet->tablet_meta()->delete_bitmap()->subset(
1143
0
                                {rs->rowset_id(), 0, 0},
1144
0
                                {rs->rowset_id(), rs->num_segments(), version.second + 1},
1145
0
                                &subset_map);
1146
0
                        ss << "(rowset id: " << rs->rowset_id()
1147
0
                           << ", delete bitmap cardinality: " << subset_map.cardinality() << ")";
1148
0
                    }
1149
0
                    ss << ", version[0-" << version.second + 1 << "]";
1150
0
                }
1151
0
                std::string err_msg = fmt::format(
1152
0
                        "cumulative compaction: the merged rows({}), filtered rows({})"
1153
0
                        " is not equal to missed rows({}) in rowid conversion,"
1154
0
                        " tablet_id: {}, table_id:{}",
1155
0
                        _stats.merged_rows, _stats.filtered_rows, missed_rows_size,
1156
0
                        _tablet->tablet_id(), _tablet->table_id());
1157
0
                if (config::enable_mow_compaction_correctness_check_core) {
  Branch (1157:21): [True: 0, False: 0]
1158
0
                    CHECK(false) << err_msg;
1159
0
                } else {
1160
0
                    DCHECK(false) << err_msg;
1161
0
                }
1162
0
                LOG(WARNING) << err_msg;
1163
0
            }
1164
0
        }
1165
1166
0
        if (location_map) {
  Branch (1166:13): [True: 0, False: 0]
1167
0
            RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1168
0
            location_map->clear();
1169
0
        }
1170
1171
0
        {
1172
0
            std::lock_guard<std::mutex> wrlock_(tablet()->get_rowset_update_lock());
1173
0
            std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1174
0
            SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
0
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
0
    using namespace std::chrono_literals;                                               \
42
0
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
0
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
0
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
0
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
0
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
0
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
0
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
0
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
0
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
0
        }                                                                               \
51
0
    })
1175
1176
            // Here we will calculate all the rowsets delete bitmaps which are committed but not published to reduce the calculation pressure
1177
            // of publish phase.
1178
            // All rowsets which need to recalculate have been published so we don't need to acquire lock.
1179
            // Step1: collect this tablet's all committed rowsets' delete bitmaps
1180
0
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1181
0
            _engine.txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1182
0
                    *tablet(), &commit_tablet_txn_info_vec);
1183
1184
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1185
0
            for (auto& it : commit_tablet_txn_info_vec) {
  Branch (1185:27): [True: 0, False: 0]
1186
0
                if (!_check_if_includes_input_rowsets(it.rowset_ids)) {
  Branch (1186:21): [True: 0, False: 0]
1187
                    // When calculating the delete bitmap of all committed rowsets relative to the compaction,
1188
                    // there may be cases where the compacted rowsets are newer than the committed rowsets.
1189
                    // At this time, row number conversion cannot be performed, otherwise data will be missing.
1190
                    // Therefore, we need to check if every committed rowset has calculated delete bitmap for
1191
                    // all compaction input rowsets.
1192
0
                    continue;
1193
0
                }
1194
0
                DeleteBitmap txn_output_delete_bitmap(_tablet->tablet_id());
1195
0
                tablet()->calc_compaction_output_rowset_delete_bitmap(
1196
0
                        _input_rowsets, *_rowid_conversion, 0, UINT64_MAX, missed_rows.get(),
1197
0
                        location_map.get(), *it.delete_bitmap.get(), &txn_output_delete_bitmap);
1198
0
                if (config::enable_merge_on_write_correctness_check) {
  Branch (1198:21): [True: 0, False: 0]
1199
0
                    RowsetIdUnorderedSet rowsetids;
1200
0
                    rowsetids.insert(_output_rowset->rowset_id());
1201
0
                    _tablet->add_sentinel_mark_to_delete_bitmap(&txn_output_delete_bitmap,
1202
0
                                                                rowsetids);
1203
0
                }
1204
0
                it.delete_bitmap->merge(txn_output_delete_bitmap);
1205
                // Step3: write back updated delete bitmap and tablet info.
1206
0
                it.rowset_ids.insert(_output_rowset->rowset_id());
1207
0
                _engine.txn_manager()->set_txn_related_delete_bitmap(
1208
0
                        it.partition_id, it.transaction_id, _tablet->tablet_id(),
1209
0
                        tablet()->tablet_uid(), true, it.delete_bitmap, it.rowset_ids,
1210
0
                        it.partial_update_info);
1211
0
            }
1212
1213
            // Convert the delete bitmap of the input rowsets to output rowset for
1214
            // incremental data.
1215
0
            tablet()->calc_compaction_output_rowset_delete_bitmap(
1216
0
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1217
0
                    missed_rows.get(), location_map.get(), *_tablet->tablet_meta()->delete_bitmap(),
1218
0
                    &output_rowset_delete_bitmap);
1219
1220
0
            if (missed_rows) {
  Branch (1220:17): [True: 0, False: 0]
1221
0
                DCHECK_EQ(missed_rows->size(), missed_rows_size);
1222
0
                if (missed_rows->size() != missed_rows_size) {
  Branch (1222:21): [True: 0, False: 0]
1223
0
                    LOG(WARNING) << "missed rows don't match, before: " << missed_rows_size
1224
0
                                 << " after: " << missed_rows->size();
1225
0
                }
1226
0
            }
1227
1228
0
            if (location_map) {
  Branch (1228:17): [True: 0, False: 0]
1229
0
                RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1230
0
            }
1231
1232
0
            tablet()->merge_delete_bitmap(output_rowset_delete_bitmap);
1233
0
            RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1234
0
        }
1235
0
    } else {
1236
0
        std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1237
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
Line
Count
Source
31
0
    SCOPED_SIMPLE_TRACE_TO_STREAM_IF_TIMEOUT(timeout, LOG(WARNING))
Line
Count
Source
41
0
    using namespace std::chrono_literals;                                               \
42
0
    auto VARNAME_LINENUM(scoped_simple_trace) = doris::MonotonicMicros();               \
43
0
    SCOPED_CLEANUP({                                                                    \
Line
Count
Source
34
0
    auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body });
44
0
        auto VARNAME_LINENUM(timeout_us) =                                              \
45
0
                std::chrono::duration_cast<std::chrono::microseconds>(timeout).count(); \
46
0
        auto VARNAME_LINENUM(cost_us) =                                                 \
47
0
                doris::MonotonicMicros() - VARNAME_LINENUM(scoped_simple_trace);        \
48
0
        if (VARNAME_LINENUM(cost_us) >= VARNAME_LINENUM(timeout_us)) {                  \
49
0
            stream << "Simple trace cost(us): " << VARNAME_LINENUM(cost_us);            \
50
0
        }                                                                               \
51
0
    })
1238
0
        RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1239
0
    }
1240
1241
0
    if (config::tablet_rowset_stale_sweep_by_size &&
  Branch (1241:9): [True: 0, False: 0]
1242
0
        _tablet->tablet_meta()->all_stale_rs_metas().size() >=
  Branch (1242:9): [True: 0, False: 0]
1243
0
                config::tablet_rowset_stale_sweep_threshold_size) {
1244
0
        tablet()->delete_expired_stale_rowset();
1245
0
    }
1246
1247
0
    int64_t cur_max_version = 0;
1248
0
    {
1249
0
        std::shared_lock rlock(_tablet->get_header_lock());
1250
0
        cur_max_version = _tablet->max_version_unlocked();
1251
0
        tablet()->save_meta();
1252
0
    }
1253
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (1253:9): [True: 0, False: 0]
1254
0
        _tablet->enable_unique_key_merge_on_write()) {
  Branch (1254:9): [True: 0, False: 0]
1255
0
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1256
0
                tablet()->data_dir(), _tablet->tablet_id(), cur_max_version);
1257
0
        if (!st.ok()) {
  Branch (1257:13): [True: 0, False: 0]
1258
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1259
0
        }
1260
0
    }
1261
0
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset",
Line
Count
Source
37
0
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
42
0
        }                                                                     \
43
0
    }
1262
0
                    { tablet()->delete_expired_stale_rowset(); });
1263
0
    return Status::OK();
1264
0
}
1265
1266
bool CompactionMixin::_check_if_includes_input_rowsets(
1267
0
        const RowsetIdUnorderedSet& commit_rowset_ids_set) const {
1268
0
    std::vector<RowsetId> commit_rowset_ids {};
1269
0
    commit_rowset_ids.insert(commit_rowset_ids.end(), commit_rowset_ids_set.begin(),
1270
0
                             commit_rowset_ids_set.end());
1271
0
    std::sort(commit_rowset_ids.begin(), commit_rowset_ids.end());
1272
0
    std::vector<RowsetId> input_rowset_ids {};
1273
0
    for (const auto& rowset : _input_rowsets) {
  Branch (1273:29): [True: 0, False: 0]
1274
0
        input_rowset_ids.emplace_back(rowset->rowset_meta()->rowset_id());
1275
0
    }
1276
0
    std::sort(input_rowset_ids.begin(), input_rowset_ids.end());
1277
0
    return std::includes(commit_rowset_ids.begin(), commit_rowset_ids.end(),
1278
0
                         input_rowset_ids.begin(), input_rowset_ids.end());
1279
0
}
1280
1281
0
Status Compaction::check_correctness() {
1282
    // 1. check row number
1283
0
    if (_input_row_num != _output_rowset->num_rows() + _stats.merged_rows + _stats.filtered_rows) {
  Branch (1283:9): [True: 0, False: 0]
1284
0
        return Status::Error<CHECK_LINES_ERROR>(
1285
0
                "row_num does not match between cumulative input and output! tablet={}, "
1286
0
                "input_row_num={}, merged_row_num={}, filtered_row_num={}, output_row_num={}",
1287
0
                _tablet->tablet_id(), _input_row_num, _stats.merged_rows, _stats.filtered_rows,
1288
0
                _output_rowset->num_rows());
1289
0
    }
1290
    // check variant column path stats
1291
0
    RETURN_IF_ERROR(
1292
0
            vectorized::schema_util::check_path_stats(_input_rowsets, _output_rowset, _tablet));
1293
0
    return Status::OK();
1294
0
}
1295
1296
22
int64_t CompactionMixin::get_compaction_permits() {
1297
22
    int64_t permits = 0;
1298
616
    for (auto&& rowset : _input_rowsets) {
  Branch (1298:24): [True: 616, False: 22]
1299
616
        permits += rowset->rowset_meta()->get_compaction_score();
1300
616
    }
1301
22
    return permits;
1302
22
}
1303
1304
0
int64_t CompactionMixin::calc_input_rowsets_total_size() const {
1305
0
    int64_t input_rowsets_total_size = 0;
1306
0
    for (const auto& rowset : _input_rowsets) {
  Branch (1306:29): [True: 0, False: 0]
1307
0
        const auto& rowset_meta = rowset->rowset_meta();
1308
0
        auto total_size = rowset_meta->total_disk_size();
1309
0
        input_rowsets_total_size += total_size;
1310
0
    }
1311
0
    return input_rowsets_total_size;
1312
0
}
1313
1314
0
int64_t CompactionMixin::calc_input_rowsets_row_num() const {
1315
0
    int64_t input_rowsets_row_num = 0;
1316
0
    for (const auto& rowset : _input_rowsets) {
  Branch (1316:29): [True: 0, False: 0]
1317
0
        const auto& rowset_meta = rowset->rowset_meta();
1318
0
        auto total_size = rowset_meta->total_disk_size();
1319
0
        input_rowsets_row_num += total_size;
1320
0
    }
1321
0
    return input_rowsets_row_num;
1322
0
}
1323
1324
0
void Compaction::_load_segment_to_cache() {
1325
    // Load new rowset's segments to cache.
1326
0
    SegmentCacheHandle handle;
1327
0
    auto st = SegmentLoader::instance()->load_segments(
1328
0
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1329
0
    if (!st.ok()) {
  Branch (1329:9): [True: 0, False: 0]
1330
0
        LOG(WARNING) << "failed to load segment to cache! output rowset version="
1331
0
                     << _output_rowset->start_version() << "-" << _output_rowset->end_version()
1332
0
                     << ".";
1333
0
    }
1334
0
}
1335
1336
0
Status CloudCompactionMixin::build_basic_info() {
1337
0
    _output_version =
1338
0
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
1339
1340
0
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
1341
1342
0
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
1343
0
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
1344
0
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
1345
0
    _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
1346
0
    if (!_cur_tablet_schema->need_record_variant_extended_schema()) {
  Branch (1346:9): [True: 0, False: 0]
1347
0
        RETURN_IF_ERROR(_tablet->get_compaction_schema(rowset_metas, _cur_tablet_schema));
1348
0
    }
1349
0
    return Status::OK();
1350
0
}
1351
1352
0
int64_t CloudCompactionMixin::get_compaction_permits() {
1353
0
    int64_t permits = 0;
1354
0
    for (auto&& rowset : _input_rowsets) {
  Branch (1354:24): [True: 0, False: 0]
1355
0
        permits += rowset->rowset_meta()->get_compaction_score();
1356
0
    }
1357
0
    return permits;
1358
0
}
1359
1360
CloudCompactionMixin::CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
1361
                                           const std::string& label)
1362
0
        : Compaction(tablet, label), _engine(engine) {
1363
0
    auto uuid = UUIDGenerator::instance()->next_uuid();
1364
0
    std::stringstream ss;
1365
0
    ss << uuid;
1366
0
    _uuid = ss.str();
1367
0
}
1368
1369
0
Status CloudCompactionMixin::execute_compact_impl(int64_t permits) {
1370
0
    OlapStopWatch watch;
1371
1372
0
    RETURN_IF_ERROR(build_basic_info());
1373
1374
0
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
1375
0
              << ", output_version=" << _output_version << ", permits: " << permits;
1376
1377
0
    RETURN_IF_ERROR(merge_input_rowsets());
1378
1379
0
    DBUG_EXECUTE_IF("CloudFullCompaction::modify_rowsets.wrong_rowset_id", {
Line
Count
Source
37
0
    if (UNLIKELY(config::enable_debug_points)) {                              \
38
0
        auto dp = DebugPoints::instance()->get_debug_point(debug_point_name); \
39
0
        if (dp) {                                                             \
  Branch (39:13): [True: 0, False: 0]
40
0
            [[maybe_unused]] auto DP_NAME = debug_point_name;                 \
41
0
            { code; }                                                         \
  Branch (41:15): [True: 0, False: 0]
42
0
        }                                                                     \
43
0
    }
1380
0
        DCHECK(compaction_type() == ReaderType::READER_FULL_COMPACTION);
1381
0
        RowsetId id;
1382
0
        id.version = 2;
1383
0
        id.hi = _output_rowset->rowset_meta()->rowset_id().hi + ((int64_t)(1) << 56);
1384
0
        id.mi = _output_rowset->rowset_meta()->rowset_id().mi;
1385
0
        id.lo = _output_rowset->rowset_meta()->rowset_id().lo;
1386
0
        _output_rowset->rowset_meta()->set_rowset_id(id);
1387
0
        LOG(INFO) << "[Debug wrong rowset id]:"
1388
0
                  << _output_rowset->rowset_meta()->rowset_id().to_string();
1389
0
    })
1390
1391
0
    RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get(), _uuid));
1392
1393
    // 4. modify rowsets in memory
1394
0
    RETURN_IF_ERROR(modify_rowsets());
1395
1396
    // update compaction status data
1397
0
    auto tablet = std::static_pointer_cast<CloudTablet>(_tablet);
1398
0
    tablet->local_read_time_us.fetch_add(_stats.cloud_local_read_time);
1399
0
    tablet->remote_read_time_us.fetch_add(_stats.cloud_remote_read_time);
1400
0
    tablet->exec_compaction_time_us.fetch_add(watch.get_elapse_time_us());
1401
1402
0
    return Status::OK();
1403
0
}
1404
1405
0
int64_t CloudCompactionMixin::initiator() const {
1406
0
    return HashUtil::hash64(_uuid.data(), _uuid.size(), 0) & std::numeric_limits<int64_t>::max();
1407
0
}
1408
1409
0
Status CloudCompactionMixin::execute_compact() {
1410
0
    TEST_INJECTION_POINT("Compaction::do_compaction");
1411
0
    int64_t permits = get_compaction_permits();
1412
0
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
Line
Count
Source
134
0
    do {                                                                                         \
135
0
        try {                                                                                    \
136
0
            doris::enable_thread_catch_bad_alloc++;                                              \
137
0
            Defer defer {[&]() { doris::enable_thread_catch_bad_alloc--; }};                     \
138
0
            {                                                                                    \
139
0
                Status _status_ = (stmt);                                                        \
140
0
                if (UNLIKELY(!_status_.ok())) {                                                  \
141
0
                    exception_handler(doris::Exception());                                       \
142
0
                    return _status_;                                                             \
143
0
                }                                                                                \
144
0
            }                                                                                    \
145
0
        } catch (const doris::Exception& e) {                                                    \
146
0
            exception_handler(e);                                                                \
147
0
            if (e.code() == doris::ErrorCode::MEM_ALLOC_FAILED) {                                \
  Branch (147:17): [True: 0, False: 0]
148
0
                return Status::MemoryLimitExceeded(fmt::format(                                  \
149
0
                        "PreCatch error code:{}, {}, __FILE__:{}, __LINE__:{}, __FUNCTION__:{}", \
150
0
                        e.code(), e.to_string(), __FILE__, __LINE__, __PRETTY_FUNCTION__));      \
151
0
            }                                                                                    \
152
0
            return Status::Error<false>(e.code(), e.to_string());                                \
153
0
        }                                                                                        \
154
0
    } while (0);
  Branch (154:14): [Folded - Ignored]
1413
0
            execute_compact_impl(permits), [&](const doris::Exception& ex) {
1414
0
                auto st = garbage_collection();
1415
0
                if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1416
0
                    _tablet->enable_unique_key_merge_on_write() && !st.ok()) {
1417
                    // if compaction fail, be will try to abort compaction, and delete bitmap lock
1418
                    // will release if abort job successfully, but if abort failed, delete bitmap
1419
                    // lock will not release, in this situation, be need to send this rpc to ms
1420
                    // to try to release delete bitmap lock.
1421
0
                    _engine.meta_mgr().remove_delete_bitmap_update_lock(
1422
0
                            _tablet->table_id(), COMPACTION_DELETE_BITMAP_LOCK_ID, initiator(),
1423
0
                            _tablet->tablet_id());
1424
0
                }
1425
0
            });
1426
1427
0
    DorisMetrics::instance()->remote_compaction_read_rows_total->increment(_input_row_num);
1428
0
    DorisMetrics::instance()->remote_compaction_write_rows_total->increment(
1429
0
            _output_rowset->num_rows());
1430
0
    DorisMetrics::instance()->remote_compaction_write_bytes_total->increment(
1431
0
            _output_rowset->total_disk_size());
1432
1433
0
    _load_segment_to_cache();
1434
0
    return Status::OK();
1435
0
}
1436
1437
0
Status CloudCompactionMixin::modify_rowsets() {
1438
0
    return Status::OK();
1439
0
}
1440
1441
0
Status CloudCompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1442
    // only do index compaction for dup_keys and unique_keys with mow enabled
1443
0
    if (config::inverted_index_compaction_enable &&
  Branch (1443:9): [True: 0, False: 0]
1444
0
        (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
  Branch (1444:12): [True: 0, False: 0]
1445
0
           _tablet->enable_unique_key_merge_on_write()) ||
  Branch (1445:12): [True: 0, False: 0]
1446
0
          _tablet->keys_type() == KeysType::DUP_KEYS))) {
  Branch (1446:11): [True: 0, False: 0]
1447
0
        construct_index_compaction_columns(ctx);
1448
0
    }
1449
1450
    // Use the storage resource of the previous rowset
1451
0
    ctx.storage_resource =
1452
0
            *DORIS_TRY(_input_rowsets.back()->rowset_meta()->remote_storage_resource());
1453
1454
0
    ctx.txn_id = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
1455
0
                 std::numeric_limits<int64_t>::max(); // MUST be positive
1456
0
    ctx.txn_expiration = _expiration;
1457
1458
0
    ctx.version = _output_version;
1459
0
    ctx.rowset_state = VISIBLE;
1460
0
    ctx.segments_overlap = NONOVERLAPPING;
1461
0
    ctx.tablet_schema = _cur_tablet_schema;
1462
0
    ctx.newest_write_timestamp = _newest_write_timestamp;
1463
0
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1464
0
    ctx.compaction_type = compaction_type();
1465
1466
0
    auto compaction_policy = _tablet->tablet_meta()->compaction_policy();
1467
0
    if (_tablet->tablet_meta()->time_series_compaction_level_threshold() >= 2) {
  Branch (1467:9): [True: 0, False: 0]
1468
0
        ctx.compaction_level = _engine.cumu_compaction_policy(compaction_policy)
1469
0
                                       ->new_compaction_level(_input_rowsets);
1470
0
    }
1471
    // We presume that the data involved in cumulative compaction is sufficiently 'hot'
1472
    // and should always be retained in the cache.
1473
    // TODO(gavin): Ensure that the retention of hot data is implemented with precision.
1474
0
    ctx.write_file_cache = (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) ||
  Branch (1474:28): [True: 0, False: 0]
1475
0
                           (config::enable_file_cache_keep_base_compaction_output &&
  Branch (1475:29): [True: 0, False: 0]
1476
0
                            compaction_type() == ReaderType::READER_BASE_COMPACTION);
  Branch (1476:29): [True: 0, False: 0]
1477
0
    ctx.file_cache_ttl_sec = _tablet->ttl_seconds();
1478
0
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1479
0
    RETURN_IF_ERROR(
1480
0
            _engine.meta_mgr().prepare_rowset(*_output_rs_writer->rowset_meta().get(), _uuid));
1481
0
    return Status::OK();
1482
0
}
1483
1484
0
Status CloudCompactionMixin::garbage_collection() {
1485
0
    if (!config::enable_file_cache) {
  Branch (1485:9): [True: 0, False: 0]
1486
0
        return Status::OK();
1487
0
    }
1488
0
    if (_output_rs_writer) {
  Branch (1488:9): [True: 0, False: 0]
1489
0
        auto* beta_rowset_writer = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get());
1490
0
        DCHECK(beta_rowset_writer);
1491
0
        for (const auto& [_, file_writer] : beta_rowset_writer->get_file_writers()) {
  Branch (1491:43): [True: 0, False: 0]
1492
0
            auto file_key = io::BlockFileCache::hash(file_writer->path().filename().native());
1493
0
            auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1494
0
            file_cache->remove_if_cached_async(file_key);
1495
0
        }
1496
0
    }
1497
0
    return Status::OK();
1498
0
}
1499
1500
} // namespace doris