Coverage Report

Created: 2025-04-16 14:29

/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 <cstdlib>
26
#include <list>
27
#include <map>
28
#include <memory>
29
#include <mutex>
30
#include <nlohmann/json.hpp>
31
#include <numeric>
32
#include <ostream>
33
#include <set>
34
#include <shared_mutex>
35
#include <utility>
36
37
#include "common/config.h"
38
#include "common/status.h"
39
#include "io/fs/file_system.h"
40
#include "io/fs/file_writer.h"
41
#include "io/fs/remote_file_system.h"
42
#include "io/io_common.h"
43
#include "olap/cumulative_compaction_policy.h"
44
#include "olap/cumulative_compaction_time_series_policy.h"
45
#include "olap/data_dir.h"
46
#include "olap/olap_common.h"
47
#include "olap/olap_define.h"
48
#include "olap/rowset/beta_rowset.h"
49
#include "olap/rowset/rowset.h"
50
#include "olap/rowset/rowset_meta.h"
51
#include "olap/rowset/rowset_writer.h"
52
#include "olap/rowset/rowset_writer_context.h"
53
#include "olap/rowset/segment_v2/inverted_index_compaction.h"
54
#include "olap/rowset/segment_v2/inverted_index_file_reader.h"
55
#include "olap/rowset/segment_v2/inverted_index_file_writer.h"
56
#include "olap/rowset/segment_v2/inverted_index_fs_directory.h"
57
#include "olap/storage_engine.h"
58
#include "olap/storage_policy.h"
59
#include "olap/tablet.h"
60
#include "olap/tablet_meta.h"
61
#include "olap/tablet_meta_manager.h"
62
#include "olap/task/engine_checksum_task.h"
63
#include "olap/txn_manager.h"
64
#include "olap/utils.h"
65
#include "runtime/memory/mem_tracker_limiter.h"
66
#include "runtime/thread_context.h"
67
#include "util/time.h"
68
#include "util/trace.h"
69
70
using std::vector;
71
72
namespace doris {
73
using namespace ErrorCode;
74
75
Compaction::Compaction(const TabletSharedPtr& tablet, const std::string& label)
76
        : _tablet(tablet),
77
          _input_rowsets_size(0),
78
          _input_row_num(0),
79
          _input_num_segments(0),
80
          _input_index_size(0),
81
18
          _state(CompactionState::INITED) {
82
18
    _mem_tracker = MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label);
83
18
    init_profile(label);
84
18
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
85
18
    _rowid_conversion = std::make_unique<RowIdConversion>();
86
18
}
87
88
18
Compaction::~Compaction() {
89
18
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
90
18
    _output_rs_writer.reset();
91
18
    _tablet.reset();
92
18
    _input_rowsets.clear();
93
18
    _output_rowset.reset();
94
18
    _cur_tablet_schema.reset();
95
18
    _rowid_conversion.reset();
96
18
}
97
98
18
void Compaction::init_profile(const std::string& label) {
99
18
    _profile = std::make_unique<RuntimeProfile>(label);
100
101
18
    _input_rowsets_data_size_counter =
102
18
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
103
18
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
104
18
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
105
18
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
106
18
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
107
18
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
108
18
    _output_rowset_data_size_counter =
109
18
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
110
18
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
111
18
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
112
18
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
113
18
}
114
115
0
Status Compaction::compact() {
116
0
    RETURN_IF_ERROR(prepare_compact());
117
0
    RETURN_IF_ERROR(execute_compact());
118
0
    return Status::OK();
119
0
}
120
121
0
Status Compaction::execute_compact() {
122
0
    Status st = execute_compact_impl();
123
0
    if (!st.ok()) {
124
0
        gc_output_rowset();
125
0
    }
126
0
    return st;
127
0
}
128
129
0
Status Compaction::do_compaction(int64_t permits) {
130
0
    uint32_t checksum_before;
131
0
    uint32_t checksum_after;
132
0
    if (config::enable_compaction_checksum) {
133
0
        EngineChecksumTask checksum_task(_tablet->tablet_id(), _tablet->schema_hash(),
134
0
                                         _input_rowsets.back()->end_version(), &checksum_before);
135
0
        RETURN_IF_ERROR(checksum_task.execute());
136
0
    }
137
138
0
    _tablet->data_dir()->disks_compaction_score_increment(permits);
139
0
    _tablet->data_dir()->disks_compaction_num_increment(1);
140
0
    Status st = do_compaction_impl(permits);
141
0
    _tablet->data_dir()->disks_compaction_score_increment(-permits);
142
0
    _tablet->data_dir()->disks_compaction_num_increment(-1);
143
144
0
    if (config::enable_compaction_checksum) {
145
0
        EngineChecksumTask checksum_task(_tablet->tablet_id(), _tablet->schema_hash(),
146
0
                                         _input_rowsets.back()->end_version(), &checksum_after);
147
0
        RETURN_IF_ERROR(checksum_task.execute());
148
0
        if (checksum_before != checksum_after) {
149
0
            LOG(WARNING) << "Compaction tablet=" << _tablet->tablet_id()
150
0
                         << " checksum not consistent"
151
0
                         << ", before=" << checksum_before << ", checksum_after=" << checksum_after;
152
0
        }
153
0
    }
154
0
    if (st.ok()) {
155
0
        _load_segment_to_cache();
156
0
    }
157
0
    return st;
158
0
}
159
160
0
bool Compaction::should_vertical_compaction() {
161
    // some conditions that not use vertical compaction
162
0
    if (!config::enable_vertical_compaction) {
163
0
        return false;
164
0
    }
165
0
    return true;
166
0
}
167
168
0
int64_t Compaction::get_avg_segment_rows() {
169
    // take care of empty rowset
170
    // input_rowsets_size is total disk_size of input_rowset, this size is the
171
    // final size after codec and compress, so expect dest segment file size
172
    // in disk is config::vertical_compaction_max_segment_size
173
0
    const auto& meta = _tablet->tablet_meta();
174
0
    if (meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
175
0
        int64_t compaction_goal_size_mbytes = meta->time_series_compaction_goal_size_mbytes();
176
0
        return (compaction_goal_size_mbytes * 1024 * 1024 * 2) /
177
0
               (_input_rowsets_size / (_input_row_num + 1) + 1);
178
0
    }
179
0
    return config::vertical_compaction_max_segment_size /
180
0
           (_input_rowsets_size / (_input_row_num + 1) + 1);
181
0
}
182
183
5
bool Compaction::is_rowset_tidy(std::string& pre_max_key, const RowsetSharedPtr& rhs) {
184
5
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
185
5
    if (rhs->num_segments() == 0) {
186
0
        return true;
187
0
    }
188
5
    if (rhs->is_segments_overlapping()) {
189
0
        return false;
190
0
    }
191
    // check segment size
192
5
    auto beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
193
5
    std::vector<size_t> segments_size;
194
5
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
195
10
    for (auto segment_size : segments_size) {
196
        // is segment is too small, need to do compaction
197
10
        if (segment_size < min_tidy_size) {
198
0
            return false;
199
0
        }
200
10
    }
201
5
    std::string min_key;
202
5
    auto ret = rhs->first_key(&min_key);
203
5
    if (!ret) {
204
0
        return false;
205
0
    }
206
5
    if (min_key <= pre_max_key) {
207
0
        return false;
208
0
    }
209
5
    CHECK(rhs->last_key(&pre_max_key));
210
211
5
    return true;
212
5
}
213
214
1
Status Compaction::do_compact_ordered_rowsets() {
215
1
    build_basic_info();
216
1
    RowsetWriterContext ctx;
217
1
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
218
219
1
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
220
1
              << ", output_version=" << _output_version;
221
    // link data to new rowset
222
1
    auto seg_id = 0;
223
1
    std::vector<KeyBoundsPB> segment_key_bounds;
224
5
    for (auto rowset : _input_rowsets) {
225
5
        RETURN_IF_ERROR(rowset->link_files_to(_tablet->tablet_path(),
226
5
                                              _output_rs_writer->rowset_id(), seg_id));
227
5
        seg_id += rowset->num_segments();
228
229
5
        std::vector<KeyBoundsPB> key_bounds;
230
5
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
231
5
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
232
5
    }
233
    // build output rowset
234
1
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
235
1
    rowset_meta->set_num_rows(_input_row_num);
236
1
    rowset_meta->set_total_disk_size(_input_rowsets_size);
237
1
    rowset_meta->set_data_disk_size(_input_rowsets_size);
238
1
    rowset_meta->set_index_disk_size(_input_index_size);
239
1
    rowset_meta->set_empty(_input_row_num == 0);
240
1
    rowset_meta->set_num_segments(_input_num_segments);
241
1
    rowset_meta->set_segments_overlap(NONOVERLAPPING);
242
1
    rowset_meta->set_rowset_state(VISIBLE);
243
244
1
    rowset_meta->set_segments_key_bounds(segment_key_bounds);
245
1
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
246
1
    return Status::OK();
247
1
}
248
249
3
void Compaction::build_basic_info() {
250
11
    for (auto& rowset : _input_rowsets) {
251
11
        _input_rowsets_size += rowset->data_disk_size();
252
11
        _input_index_size += rowset->index_disk_size();
253
11
        _input_row_num += rowset->num_rows();
254
11
        _input_num_segments += rowset->num_segments();
255
11
    }
256
3
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_size);
257
3
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
258
3
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
259
260
3
    _output_version =
261
3
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
262
263
3
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
264
265
3
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
266
3
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
267
11
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
268
3
    _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
269
3
}
270
271
1
bool Compaction::handle_ordered_data_compaction() {
272
1
    if (!config::enable_ordered_data_compaction) {
273
0
        return false;
274
0
    }
275
1
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
276
1
        compaction_type() == ReaderType::READER_FULL_COMPACTION) {
277
        // The remote file system and full compaction does not support to link files.
278
0
        return false;
279
0
    }
280
1
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
281
1
        _tablet->enable_unique_key_merge_on_write()) {
282
0
        return false;
283
0
    }
284
285
1
    if (_tablet->tablet_meta()->tablet_schema()->skip_write_index_on_load()) {
286
        // Expected to create index through normal compaction
287
0
        return false;
288
0
    }
289
290
    // check delete version: if compaction type is base compaction and
291
    // has a delete version, use original compaction
292
1
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
293
0
        for (auto& rowset : _input_rowsets) {
294
0
            if (rowset->rowset_meta()->has_delete_predicate()) {
295
0
                return false;
296
0
            }
297
0
        }
298
0
    }
299
300
    // check if rowsets are tidy so we can just modify meta and do link
301
    // files to handle compaction
302
1
    auto input_size = _input_rowsets.size();
303
1
    std::string pre_max_key;
304
6
    for (auto i = 0; i < input_size; ++i) {
305
5
        if (!is_rowset_tidy(pre_max_key, _input_rowsets[i])) {
306
0
            if (i <= input_size / 2) {
307
0
                return false;
308
0
            } else {
309
0
                _input_rowsets.resize(i);
310
0
                break;
311
0
            }
312
0
        }
313
5
    }
314
    // most rowset of current compaction is nonoverlapping
315
    // just handle nonoverlappint rowsets
316
1
    auto st = do_compact_ordered_rowsets();
317
1
    if (!st.ok()) {
318
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
319
0
        _pending_rs_guard.drop();
320
0
    }
321
322
1
    return st.ok();
323
1
}
324
325
0
int64_t Compaction::merge_way_num() {
326
0
    int64_t way_num = 0;
327
0
    for (auto&& rowset : _input_rowsets) {
328
0
        way_num += rowset->rowset_meta()->get_merge_way_num();
329
0
    }
330
331
0
    return way_num;
332
0
}
333
334
0
Status Compaction::do_compaction_impl(int64_t permits) {
335
0
    OlapStopWatch watch;
336
337
0
    if (handle_ordered_data_compaction()) {
338
0
        RETURN_IF_ERROR(modify_rowsets());
339
340
0
        int64_t now = UnixMillis();
341
0
        if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
342
            // TIME_SERIES_POLICY, generating an empty rowset doesn't need to update the timestamp.
343
0
            if (!(_tablet->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY &&
344
0
                  _output_rowset->num_segments() == 0)) {
345
0
                _tablet->set_last_cumu_compaction_success_time(now);
346
0
            }
347
0
        } else if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
348
0
            _tablet->set_last_base_compaction_success_time(now);
349
0
        } else if (compaction_type() == ReaderType::READER_FULL_COMPACTION) {
350
0
            _tablet->set_last_full_compaction_success_time(now);
351
0
        }
352
0
        auto cumu_policy = _tablet->cumulative_compaction_policy();
353
0
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
354
0
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
355
0
                  << ", disk=" << _tablet->data_dir()->path()
356
0
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
357
0
                  << ", output_row_num=" << _output_rowset->num_rows()
358
0
                  << ", input_rowset_size=" << _input_rowsets_size
359
0
                  << ", output_rowset_size=" << _output_rowset->data_disk_size()
360
0
                  << ". elapsed time=" << watch.get_elapse_second()
361
0
                  << "s. cumulative_compaction_policy="
362
0
                  << (cumu_policy == nullptr ? "quick" : cumu_policy->name());
363
0
        return Status::OK();
364
0
    }
365
0
    build_basic_info();
366
367
0
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
368
369
0
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
370
0
              << ", output_version=" << _output_version << ", permits: " << permits;
371
0
    bool vertical_compaction = should_vertical_compaction();
372
0
    RowsetWriterContext ctx;
373
0
    RETURN_IF_ERROR(construct_input_rowset_readers());
374
0
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx, vertical_compaction));
375
376
    // 2. write merged rows to output rowset
377
    // The test results show that merger is low-memory-footprint, there is no need to tracker its mem pool
378
0
    Merger::Statistics stats;
379
    // if ctx.columns_to_do_index_compaction.size() > 0, it means we need to do inverted index compaction.
380
    // the row ID conversion matrix needs to be used for inverted index compaction.
381
0
    if (!ctx.columns_to_do_index_compaction.empty() ||
382
0
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
383
0
         _tablet->enable_unique_key_merge_on_write())) {
384
0
        stats.rowid_conversion = _rowid_conversion.get();
385
0
    }
386
0
    int64_t way_num = merge_way_num();
387
388
0
    Status res;
389
0
    {
390
0
        SCOPED_TIMER(_merge_rowsets_latency_timer);
391
0
        if (vertical_compaction) {
392
0
            res = Merger::vertical_merge_rowsets(_tablet, compaction_type(), _cur_tablet_schema,
393
0
                                                 _input_rs_readers, _output_rs_writer.get(),
394
0
                                                 get_avg_segment_rows(), way_num, &stats);
395
0
        } else {
396
0
            res = Merger::vmerge_rowsets(_tablet, compaction_type(), _cur_tablet_schema,
397
0
                                         _input_rs_readers, _output_rs_writer.get(), &stats);
398
0
        }
399
0
    }
400
401
0
    _tablet->last_compaction_status = res;
402
403
0
    if (!res.ok()) {
404
0
        LOG(WARNING) << "fail to do " << compaction_name() << ". res=" << res
405
0
                     << ", tablet=" << _tablet->tablet_id()
406
0
                     << ", output_version=" << _output_version;
407
0
        return res;
408
0
    }
409
0
    COUNTER_UPDATE(_merged_rows_counter, stats.merged_rows);
410
0
    COUNTER_UPDATE(_filtered_rows_counter, stats.filtered_rows);
411
412
0
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
413
0
                                   fmt::format("rowset writer build failed. output_version: {}",
414
0
                                               _output_version.to_string()));
415
    // Now we support delete in cumu compaction, to make all data in rowsets whose version
416
    // is below output_version to be delete in the future base compaction, we should carry
417
    // all delete predicate in the output rowset.
418
    // Output start version > 2 means we must set the delete predicate in the output rowset
419
0
    if (allow_delete_in_cumu_compaction() && _output_rowset->version().first > 2) {
420
0
        DeletePredicatePB delete_predicate;
421
0
        std::accumulate(
422
0
                _input_rs_readers.begin(), _input_rs_readers.end(), &delete_predicate,
423
0
                [](DeletePredicatePB* delete_predicate, const RowsetReaderSharedPtr& reader) {
424
0
                    if (reader->rowset()->rowset_meta()->has_delete_predicate()) {
425
0
                        delete_predicate->MergeFrom(
426
0
                                reader->rowset()->rowset_meta()->delete_predicate());
427
0
                    }
428
0
                    return delete_predicate;
429
0
                });
430
        // now version in delete_predicate is deprecated
431
0
        if (!delete_predicate.in_predicates().empty() ||
432
0
            !delete_predicate.sub_predicates_v2().empty() ||
433
0
            !delete_predicate.sub_predicates().empty()) {
434
0
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
435
0
        }
436
0
    }
437
438
0
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
439
0
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
440
0
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
441
442
    // 3. check correctness
443
0
    RETURN_IF_ERROR(check_correctness(stats));
444
445
0
    if (_input_row_num > 0 && stats.rowid_conversion && config::inverted_index_compaction_enable &&
446
0
        !ctx.columns_to_do_index_compaction.empty()) {
447
0
        OlapStopWatch inverted_watch;
448
449
        // translation vec
450
        // <<dest_idx_num, dest_docId>>
451
        // the first level vector: index indicates src segment.
452
        // the second level vector: index indicates row id of source segment,
453
        // value indicates row id of destination segment.
454
        // <UINT32_MAX, UINT32_MAX> indicates current row not exist.
455
0
        std::vector<std::vector<std::pair<uint32_t, uint32_t>>> trans_vec =
456
0
                stats.rowid_conversion->get_rowid_conversion_map();
457
458
        // source rowset,segment -> index_id
459
0
        std::map<std::pair<RowsetId, uint32_t>, uint32_t> src_seg_to_id_map =
460
0
                stats.rowid_conversion->get_src_segment_to_id_map();
461
        // dest rowset id
462
0
        RowsetId dest_rowset_id = stats.rowid_conversion->get_dst_rowset_id();
463
        // dest segment id -> num rows
464
0
        std::vector<uint32_t> dest_segment_num_rows;
465
0
        RETURN_IF_ERROR(_output_rs_writer->get_segment_num_rows(&dest_segment_num_rows));
466
467
0
        auto src_segment_num = src_seg_to_id_map.size();
468
0
        auto dest_segment_num = dest_segment_num_rows.size();
469
470
0
        if (dest_segment_num > 0) {
471
            // src index files
472
            // format: rowsetId_segmentId
473
0
            std::vector<std::string> src_index_files(src_segment_num);
474
0
            for (const auto& m : src_seg_to_id_map) {
475
0
                std::pair<RowsetId, uint32_t> p = m.first;
476
0
                src_index_files[m.second] = p.first.to_string() + "_" + std::to_string(p.second);
477
0
            }
478
479
            // dest index files
480
            // format: rowsetId_segmentId
481
0
            std::vector<std::string> dest_index_files(dest_segment_num);
482
0
            for (int i = 0; i < dest_segment_num; ++i) {
483
0
                auto prefix = dest_rowset_id.to_string() + "_" + std::to_string(i);
484
0
                dest_index_files[i] = prefix;
485
0
            }
486
487
            // Only write info files when debug index compaction is enabled.
488
            // The files are used to debug index compaction and works with index_tool.
489
0
            if (config::debug_inverted_index_compaction) {
490
0
                auto write_json_to_file = [&](const nlohmann::json& json_obj,
491
0
                                              const std::string& file_name) {
492
0
                    io::FileWriterPtr file_writer;
493
0
                    std::string file_path =
494
0
                            fmt::format("{}/{}.json", std::string(getenv("LOG_DIR")), file_name);
495
0
                    RETURN_IF_ERROR(
496
0
                            io::global_local_filesystem()->create_file(file_path, &file_writer));
497
0
                    RETURN_IF_ERROR(file_writer->append(json_obj.dump()));
498
0
                    RETURN_IF_ERROR(file_writer->append("\n"));
499
0
                    return file_writer->close();
500
0
                };
501
502
                // Convert trans_vec to JSON and print it
503
0
                nlohmann::json trans_vec_json = trans_vec;
504
0
                auto output_version = _output_version.to_string().substr(
505
0
                        1, _output_version.to_string().size() - 2);
506
0
                RETURN_IF_ERROR(write_json_to_file(
507
0
                        trans_vec_json,
508
0
                        fmt::format("trans_vec_{}_{}", _tablet->tablet_id(), output_version)));
509
510
0
                nlohmann::json src_index_files_json = src_index_files;
511
0
                RETURN_IF_ERROR(write_json_to_file(
512
0
                        src_index_files_json,
513
0
                        fmt::format("src_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
514
515
0
                nlohmann::json dest_index_files_json = dest_index_files;
516
0
                RETURN_IF_ERROR(write_json_to_file(
517
0
                        dest_index_files_json,
518
0
                        fmt::format("dest_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
519
520
0
                nlohmann::json dest_segment_num_rows_json = dest_segment_num_rows;
521
0
                RETURN_IF_ERROR(
522
0
                        write_json_to_file(dest_segment_num_rows_json,
523
0
                                           fmt::format("dest_seg_num_rows_{}_{}",
524
0
                                                       _tablet->tablet_id(), output_version)));
525
0
            }
526
527
            // create index_writer to compaction indexes
528
0
            const auto& fs = _output_rowset->rowset_meta()->fs();
529
0
            const auto& tablet_path = _tablet->tablet_path();
530
531
            // src index dirs
532
            // format: rowsetId_segmentId
533
0
            std::vector<std::unique_ptr<InvertedIndexFileReader>> inverted_index_file_readers(
534
0
                    src_segment_num);
535
0
            for (const auto& m : src_seg_to_id_map) {
536
0
                std::pair<RowsetId, uint32_t> p = m.first;
537
0
                auto segment_file_name =
538
0
                        p.first.to_string() + "_" + std::to_string(p.second) + ".dat";
539
0
                auto inverted_index_file_reader = std::make_unique<InvertedIndexFileReader>(
540
0
                        fs, tablet_path, segment_file_name,
541
0
                        _cur_tablet_schema->get_inverted_index_storage_format());
542
0
                bool open_idx_file_cache = false;
543
0
                auto st = inverted_index_file_reader->init(config::inverted_index_read_buffer_size,
544
0
                                                           open_idx_file_cache);
545
0
                if (!st.ok()) {
546
0
                    LOG(ERROR) << "init inverted index "
547
0
                               << InvertedIndexDescriptor::get_index_file_name(segment_file_name)
548
0
                               << " failed in compaction when init inverted index file reader";
549
0
                    return st;
550
0
                }
551
0
                inverted_index_file_readers[m.second] = std::move(inverted_index_file_reader);
552
0
            }
553
554
            // dest index files
555
            // format: rowsetId_segmentId
556
0
            std::vector<std::unique_ptr<InvertedIndexFileWriter>> inverted_index_file_writers(
557
0
                    dest_segment_num);
558
559
            // Some columns have already been indexed
560
            // key: seg_id, value: inverted index file size
561
0
            std::unordered_map<int, int64_t> compacted_idx_file_size;
562
0
            for (int seg_id = 0; seg_id < dest_segment_num; ++seg_id) {
563
0
                auto prefix = dest_rowset_id.to_string() + "_" + std::to_string(seg_id) + ".dat";
564
0
                auto inverted_index_file_reader = std::make_unique<InvertedIndexFileReader>(
565
0
                        fs, tablet_path, prefix,
566
0
                        _cur_tablet_schema->get_inverted_index_storage_format());
567
0
                bool open_idx_file_cache = false;
568
0
                auto st = inverted_index_file_reader->init(config::inverted_index_read_buffer_size,
569
0
                                                           open_idx_file_cache);
570
0
                if (st.ok()) {
571
0
                    auto index_not_need_to_compact =
572
0
                            DORIS_TRY(inverted_index_file_reader->get_all_directories());
573
                    // V1: each index is a separate file
574
                    // V2: all indexes are in a single file
575
0
                    if (_cur_tablet_schema->get_inverted_index_storage_format() !=
576
0
                        doris::InvertedIndexStorageFormatPB::V1) {
577
0
                        int64_t fsize = 0;
578
0
                        st = fs->file_size(InvertedIndexDescriptor::get_index_file_name(prefix),
579
0
                                           &fsize);
580
0
                        if (!st.ok()) {
581
0
                            LOG(ERROR) << "file size error in index compaction, error:" << st.msg();
582
0
                            return st;
583
0
                        }
584
0
                        compacted_idx_file_size[seg_id] = fsize;
585
0
                    }
586
0
                    auto inverted_index_file_writer = std::make_unique<InvertedIndexFileWriter>(
587
0
                            fs, tablet_path, prefix,
588
0
                            _cur_tablet_schema->get_inverted_index_storage_format());
589
0
                    RETURN_NOT_OK_STATUS_WITH_WARN(
590
0
                            inverted_index_file_writer->initialize(index_not_need_to_compact),
591
0
                            "failed to initialize inverted_index_file_writer for " +
592
0
                                    inverted_index_file_writer->get_index_file_name());
593
0
                    inverted_index_file_writers[seg_id] = std::move(inverted_index_file_writer);
594
0
                } else if (st.is<ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND>()) {
595
0
                    auto inverted_index_file_writer = std::make_unique<InvertedIndexFileWriter>(
596
0
                            fs, tablet_path, prefix,
597
0
                            _cur_tablet_schema->get_inverted_index_storage_format());
598
0
                    inverted_index_file_writers[seg_id] = std::move(inverted_index_file_writer);
599
                    // no index file
600
0
                    compacted_idx_file_size[seg_id] = 0;
601
0
                } else {
602
0
                    LOG(ERROR) << "init inverted index "
603
0
                               << InvertedIndexDescriptor::get_index_file_name(prefix)
604
0
                               << " failed in compaction when create inverted index file writer";
605
0
                    return st;
606
0
                }
607
0
            }
608
609
            // we choose the first destination segment name as the temporary index writer path
610
            // Used to distinguish between different index compaction
611
0
            auto index_tmp_path = tablet_path + "/" + dest_rowset_id.to_string() + "_" + "tmp";
612
0
            LOG(INFO) << "start index compaction"
613
0
                      << ". tablet=" << _tablet->tablet_id()
614
0
                      << ", source index size=" << src_segment_num
615
0
                      << ", destination index size=" << dest_segment_num << ".";
616
617
0
            auto error_handler = [this](int64_t index_id, int64_t column_uniq_id) {
618
0
                LOG(WARNING) << "failed to do index compaction"
619
0
                             << ". tablet=" << _tablet->tablet_id()
620
0
                             << ". column uniq id=" << column_uniq_id << ". index_id=" << index_id;
621
0
                for (auto& rowset : _input_rowsets) {
622
0
                    rowset->set_skip_index_compaction(column_uniq_id);
623
0
                    LOG(INFO) << "mark skipping inverted index compaction next time"
624
0
                              << ". tablet=" << _tablet->tablet_id()
625
0
                              << ", rowset=" << rowset->rowset_id()
626
0
                              << ", column uniq id=" << column_uniq_id << ", index_id=" << index_id;
627
0
                }
628
0
            };
629
630
0
            Status status = Status::OK();
631
0
            for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
632
0
                auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
633
0
                const auto* index_meta = _cur_tablet_schema->get_inverted_index(col);
634
635
                // if index properties are different, index compaction maybe needs to be skipped.
636
0
                bool is_continue = false;
637
0
                std::optional<std::map<std::string, std::string>> first_properties;
638
0
                for (const auto& rowset : _input_rowsets) {
639
0
                    const auto* tablet_index = rowset->tablet_schema()->get_inverted_index(col);
640
                    // no inverted index or index id is different from current index id
641
0
                    if (tablet_index == nullptr ||
642
0
                        tablet_index->index_id() != index_meta->index_id()) {
643
0
                        error_handler(index_meta->index_id(), column_uniq_id);
644
0
                        status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
645
0
                                "index ids are different, skip index compaction");
646
0
                        is_continue = true;
647
0
                        break;
648
0
                    }
649
0
                    const auto& properties = tablet_index->properties();
650
0
                    if (!first_properties.has_value()) {
651
0
                        first_properties = properties;
652
0
                    } else {
653
0
                        if (properties != first_properties.value()) {
654
0
                            error_handler(index_meta->index_id(), column_uniq_id);
655
0
                            status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
656
0
                                    "if index properties are different, index compaction needs to "
657
0
                                    "be "
658
0
                                    "skipped.");
659
0
                            is_continue = true;
660
0
                            break;
661
0
                        }
662
0
                    }
663
0
                }
664
0
                if (is_continue) {
665
0
                    continue;
666
0
                }
667
668
0
                std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
669
0
                try {
670
0
                    std::vector<std::unique_ptr<DorisCompoundReader>> src_idx_dirs(src_segment_num);
671
0
                    for (int src_segment_id = 0; src_segment_id < src_segment_num;
672
0
                         src_segment_id++) {
673
0
                        auto res = inverted_index_file_readers[src_segment_id]->open(index_meta);
674
0
                        DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
675
0
                            res = ResultError(Status::Error<
676
0
                                              ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
677
0
                                    "debug point: Compaction::open_index_file_reader error"));
678
0
                        })
679
0
                        if (!res.has_value()) {
680
0
                            throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
681
0
                                            res.error().msg());
682
0
                        }
683
0
                        src_idx_dirs[src_segment_id] = std::move(res.value());
684
0
                    }
685
0
                    for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
686
0
                         dest_segment_id++) {
687
0
                        auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
688
0
                        DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
689
0
                            res = ResultError(
690
0
                                    Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
691
0
                                            "debug point: "
692
0
                                            "Compaction::open_inverted_index_file_writer error"));
693
0
                        })
694
0
                        if (!res.has_value()) {
695
0
                            throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
696
0
                                            res.error().msg());
697
0
                        }
698
0
                        dest_index_dirs[dest_segment_id] = res.value();
699
0
                    }
700
0
                    auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
701
0
                                             fs, index_tmp_path, trans_vec, dest_segment_num_rows);
702
0
                    if (!st.ok()) {
703
0
                        error_handler(index_meta->index_id(), column_uniq_id);
704
0
                        status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(st.msg());
705
0
                    }
706
0
                } catch (CLuceneError& e) {
707
0
                    error_handler(index_meta->index_id(), column_uniq_id);
708
0
                    status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
709
0
                } catch (const Exception& e) {
710
0
                    error_handler(index_meta->index_id(), column_uniq_id);
711
0
                    status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
712
0
                }
713
0
            }
714
0
            uint64_t inverted_index_file_size = 0;
715
0
            for (int seg_id = 0; seg_id < dest_segment_num; ++seg_id) {
716
0
                auto inverted_index_file_writer = inverted_index_file_writers[seg_id].get();
717
0
                if (Status st = inverted_index_file_writer->close(); !st.ok()) {
718
0
                    status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(st.msg());
719
0
                } else {
720
0
                    inverted_index_file_size += inverted_index_file_writer->get_index_file_size();
721
0
                    inverted_index_file_size -= compacted_idx_file_size[seg_id];
722
0
                }
723
0
            }
724
            // check index compaction status. If status is not ok, we should return error and end this compaction round.
725
0
            if (!status.ok()) {
726
0
                return status;
727
0
            }
728
729
            // index compaction should update total disk size and index disk size
730
0
            _output_rowset->rowset_meta()->set_data_disk_size(_output_rowset->data_disk_size() +
731
0
                                                              inverted_index_file_size);
732
0
            _output_rowset->rowset_meta()->set_total_disk_size(_output_rowset->data_disk_size() +
733
0
                                                               inverted_index_file_size);
734
0
            _output_rowset->rowset_meta()->set_index_disk_size(_output_rowset->index_disk_size() +
735
0
                                                               inverted_index_file_size);
736
737
0
            COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
738
0
            LOG(INFO) << "succeed to do index compaction"
739
0
                      << ". tablet=" << _tablet->tablet_id()
740
0
                      << ", input row number=" << _input_row_num
741
0
                      << ", output row number=" << _output_rowset->num_rows()
742
0
                      << ", input_rowset_size=" << _input_rowsets_size
743
0
                      << ", output_rowset_size=" << _output_rowset->data_disk_size()
744
0
                      << ", inverted index file size=" << inverted_index_file_size
745
0
                      << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
746
0
        } else {
747
0
            LOG(INFO) << "skip doing index compaction due to no output segments"
748
0
                      << ". tablet=" << _tablet->tablet_id()
749
0
                      << ", input row number=" << _input_row_num
750
0
                      << ", output row number=" << _output_rowset->num_rows()
751
0
                      << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
752
0
        }
753
0
    }
754
755
    // 4. modify rowsets in memory
756
0
    RETURN_IF_ERROR(modify_rowsets(&stats));
757
758
    // 5. update last success compaction time
759
0
    int64_t now = UnixMillis();
760
    // TODO(yingchun): do the judge in Tablet class
761
0
    if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
762
        // TIME_SERIES_POLICY, generating an empty rowset doesn't need to update the timestamp.
763
0
        if (!(_tablet->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY &&
764
0
              _output_rowset->num_segments() == 0)) {
765
0
            _tablet->set_last_cumu_compaction_success_time(now);
766
0
        }
767
0
    } else if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
768
0
        _tablet->set_last_base_compaction_success_time(now);
769
0
    } else if (compaction_type() == ReaderType::READER_FULL_COMPACTION) {
770
0
        _tablet->set_last_full_compaction_success_time(now);
771
0
    }
772
773
0
    int64_t current_max_version;
774
0
    {
775
0
        std::shared_lock rdlock(_tablet->get_header_lock());
776
0
        RowsetSharedPtr max_rowset = _tablet->rowset_with_max_version();
777
0
        if (max_rowset == nullptr) {
778
0
            current_max_version = -1;
779
0
        } else {
780
0
            current_max_version = _tablet->rowset_with_max_version()->end_version();
781
0
        }
782
0
    }
783
784
0
    auto cumu_policy = _tablet->cumulative_compaction_policy();
785
0
    DCHECK(cumu_policy);
786
0
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << vertical_compaction
787
0
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
788
0
              << ", current_max_version=" << current_max_version
789
0
              << ", disk=" << _tablet->data_dir()->path() << ", segments=" << _input_num_segments
790
0
              << ", input_rowset_size=" << _input_rowsets_size
791
0
              << ", output_rowset_size=" << _output_rowset->data_disk_size()
792
0
              << ", input_row_num=" << _input_row_num
793
0
              << ", output_row_num=" << _output_rowset->num_rows()
794
0
              << ", filtered_row_num=" << stats.filtered_rows
795
0
              << ", merged_row_num=" << stats.merged_rows
796
0
              << ". elapsed time=" << watch.get_elapse_second()
797
0
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
798
0
              << ", compact_row_per_second=" << int(_input_row_num / watch.get_elapse_second());
799
800
0
    return Status::OK();
801
0
}
802
803
3
Status Compaction::construct_output_rowset_writer(RowsetWriterContext& ctx, bool is_vertical) {
804
3
    ctx.version = _output_version;
805
3
    ctx.rowset_state = VISIBLE;
806
3
    ctx.segments_overlap = NONOVERLAPPING;
807
3
    ctx.tablet_schema = _cur_tablet_schema;
808
3
    ctx.newest_write_timestamp = _newest_write_timestamp;
809
3
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
810
3
    if (config::inverted_index_compaction_enable &&
811
3
        (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
812
1
           _tablet->enable_unique_key_merge_on_write()) ||
813
1
          _tablet->keys_type() == KeysType::DUP_KEYS)) &&
814
3
        _cur_tablet_schema->get_inverted_index_storage_format() ==
815
1
                InvertedIndexStorageFormatPB::V1) {
816
4
        for (const auto& index : _cur_tablet_schema->indexes()) {
817
4
            if (index.index_type() == IndexType::INVERTED) {
818
4
                auto col_unique_ids = index.col_unique_ids();
819
                // check if column unique ids is empty to avoid crash
820
4
                if (col_unique_ids.empty()) {
821
0
                    LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] index["
822
0
                                 << index.index_id()
823
0
                                 << "] has no column unique id, will skip index compaction."
824
0
                                 << " tablet_schema=" << _cur_tablet_schema->dump_full_schema();
825
0
                    continue;
826
0
                }
827
4
                auto col_unique_id = col_unique_ids[0];
828
                // Avoid doing inverted index compaction on non-slice type columns
829
4
                if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
830
2
                    continue;
831
2
                }
832
                //NOTE: here src_rs may be in building index progress, so it would not contain inverted index info.
833
2
                bool all_have_inverted_index = std::all_of(
834
6
                        _input_rowsets.begin(), _input_rowsets.end(), [&](const auto& src_rs) {
835
6
                            BetaRowsetSharedPtr rowset =
836
6
                                    std::static_pointer_cast<BetaRowset>(src_rs);
837
6
                            if (rowset == nullptr) {
838
0
                                LOG(WARNING) << "tablet[" << _tablet->tablet_id()
839
0
                                             << "] rowset is null, will skip index compaction";
840
0
                                return false;
841
0
                            }
842
6
                            if (rowset->is_skip_index_compaction(col_unique_id)) {
843
0
                                LOG(WARNING)
844
0
                                        << "tablet[" << _tablet->tablet_id() << "] rowset["
845
0
                                        << rowset->rowset_id() << "] column_unique_id["
846
0
                                        << col_unique_id
847
0
                                        << "] skip inverted index compaction due to last failure";
848
0
                                return false;
849
0
                            }
850
6
                            auto fs = rowset->rowset_meta()->fs();
851
852
6
                            const auto* index_meta =
853
6
                                    rowset->tablet_schema()->get_inverted_index(col_unique_id, "");
854
6
                            if (index_meta == nullptr) {
855
0
                                LOG(WARNING) << "tablet[" << _tablet->tablet_id()
856
0
                                             << "] column_unique_id[" << col_unique_id
857
0
                                             << "] index meta is null, will skip index compaction";
858
0
                                return false;
859
0
                            }
860
26
                            for (auto i = 0; i < rowset->num_segments(); i++) {
861
20
                                std::string index_file_path;
862
20
                                try {
863
20
                                    auto segment_file = rowset->segment_file_path(i);
864
20
                                    io::Path segment_path(segment_file);
865
20
                                    auto inverted_index_file_reader =
866
20
                                            std::make_unique<InvertedIndexFileReader>(
867
20
                                                    fs, segment_path.parent_path(),
868
20
                                                    segment_path.filename(),
869
20
                                                    _cur_tablet_schema
870
20
                                                            ->get_inverted_index_storage_format());
871
20
                                    bool open_idx_file_cache = false;
872
20
                                    auto st = inverted_index_file_reader->init(
873
20
                                            config::inverted_index_read_buffer_size,
874
20
                                            open_idx_file_cache);
875
20
                                    index_file_path =
876
20
                                            inverted_index_file_reader->get_index_file_path(
877
20
                                                    index_meta);
878
20
                                    if (!st.ok()) {
879
0
                                        LOG(WARNING) << "init index " << index_file_path
880
0
                                                     << " error:" << st;
881
0
                                        return false;
882
0
                                    }
883
884
20
                                    bool exists = false;
885
20
                                    if (!inverted_index_file_reader
886
20
                                                 ->index_file_exist(index_meta, &exists)
887
20
                                                 .ok()) {
888
0
                                        LOG(ERROR) << index_file_path << " fs->exists error";
889
0
                                        return false;
890
0
                                    }
891
892
20
                                    if (!exists) {
893
0
                                        LOG(WARNING)
894
0
                                                << "tablet[" << _tablet->tablet_id()
895
0
                                                << "] column_unique_id[" << col_unique_id << "],"
896
0
                                                << index_file_path
897
0
                                                << " is not exists, will skip index compaction";
898
0
                                        return false;
899
0
                                    }
900
901
                                    // check index meta
902
20
                                    auto result = inverted_index_file_reader->open(index_meta);
903
20
                                    if (!result.has_value()) {
904
0
                                        LOG(WARNING) << "open index " << index_file_path
905
0
                                                     << " error:" << result.error();
906
0
                                        return false;
907
0
                                    }
908
20
                                    auto reader = std::move(result.value());
909
20
                                    std::vector<std::string> files;
910
20
                                    reader->list(&files);
911
20
                                    reader->close();
912
913
20
                                    DBUG_EXECUTE_IF(
914
20
                                            "Compaction::construct_skip_inverted_index_index_"
915
20
                                            "reader_"
916
20
                                            "close_error",
917
20
                                            {
918
20
                                                _CLTHROWA(CL_ERR_IO,
919
20
                                                          "debug point: reader close error");
920
20
                                            })
921
922
                                    // why is 3?
923
                                    // slice type index file at least has 3 files: null_bitmap, segments_N, segments.gen
924
20
                                    if (files.size() < 3) {
925
0
                                        LOG(WARNING) << "tablet[" << _tablet->tablet_id()
926
0
                                                     << "] column_unique_id[" << col_unique_id
927
0
                                                     << "]," << index_file_path
928
0
                                                     << " is corrupted, will skip index compaction";
929
0
                                        return false;
930
0
                                    }
931
20
                                } catch (CLuceneError& err) {
932
0
                                    LOG(WARNING) << "tablet[" << _tablet->tablet_id()
933
0
                                                 << "] column_unique_id[" << col_unique_id
934
0
                                                 << "] open index[" << index_file_path
935
0
                                                 << "], will skip index compaction, error:"
936
0
                                                 << err.what();
937
0
                                    return false;
938
0
                                }
939
20
                            }
940
6
                            return true;
941
6
                        });
942
2
                if (all_have_inverted_index) {
943
2
                    ctx.columns_to_do_index_compaction.insert(col_unique_id);
944
2
                }
945
2
            }
946
4
        }
947
1
    }
948
3
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION) {
949
        // write output rowset to storage policy resource
950
0
        auto storage_policy = get_storage_policy(_tablet->storage_policy_id());
951
0
        if (storage_policy == nullptr) {
952
0
            return Status::InternalError("could not find storage_policy, storage_policy_id={}",
953
0
                                         _tablet->storage_policy_id());
954
0
        }
955
0
        auto resource = get_storage_resource(storage_policy->resource_id);
956
0
        if (resource.fs == nullptr) {
957
0
            return Status::InternalError("could not find resource, resouce_id={}",
958
0
                                         storage_policy->resource_id);
959
0
        }
960
0
        DCHECK(atol(resource.fs->id().c_str()) == storage_policy->resource_id);
961
0
        DCHECK(resource.fs->type() != io::FileSystemType::LOCAL);
962
0
        ctx.fs = std::move(resource.fs);
963
0
    }
964
3
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, is_vertical));
965
3
    _pending_rs_guard = StorageEngine::instance()->add_pending_rowset(ctx);
966
3
    return Status::OK();
967
3
}
968
969
0
Status Compaction::construct_input_rowset_readers() {
970
0
    for (auto& rowset : _input_rowsets) {
971
0
        RowsetReaderSharedPtr rs_reader;
972
0
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
973
0
        _input_rs_readers.push_back(std::move(rs_reader));
974
0
    }
975
0
    return Status::OK();
976
0
}
977
978
0
Status Compaction::modify_rowsets(const Merger::Statistics* stats) {
979
0
    std::vector<RowsetSharedPtr> output_rowsets;
980
0
    output_rowsets.push_back(_output_rowset);
981
982
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
983
0
        _tablet->enable_unique_key_merge_on_write() &&
984
0
        _tablet->tablet_schema()->cluster_key_idxes().empty()) {
985
0
        Version version = _tablet->max_version();
986
0
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
987
0
        std::unique_ptr<RowLocationSet> missed_rows;
988
0
        if (config::enable_missing_rows_correctness_check && !allow_delete_in_cumu_compaction() &&
989
0
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
990
0
            missed_rows = std::make_unique<RowLocationSet>();
991
0
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
992
0
        }
993
0
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
994
0
        if (config::enable_rowid_conversion_correctness_check) {
995
0
            location_map = std::make_unique<std::map<RowsetSharedPtr, RowLocationPairList>>();
996
0
            LOG(INFO) << "Location Map inited succ for tablet:" << _tablet->tablet_id();
997
0
        }
998
        // Convert the delete bitmap of the input rowsets to output rowset.
999
        // New loads are not blocked, so some keys of input rowsets might
1000
        // be deleted during the time. We need to deal with delete bitmap
1001
        // of incremental data later.
1002
        // TODO(LiaoXin): check if there are duplicate keys
1003
0
        std::size_t missed_rows_size = 0;
1004
0
        _tablet->calc_compaction_output_rowset_delete_bitmap(
1005
0
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1006
0
                location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1007
0
                &output_rowset_delete_bitmap);
1008
0
        if (missed_rows) {
1009
0
            missed_rows_size = missed_rows->size();
1010
            // Suppose a heavy schema change process on BE converting tablet A to tablet B.
1011
            // 1. during schema change double write, new loads write [X-Y] on tablet B.
1012
            // 2. rowsets with version [a],[a+1],...,[b-1],[b] on tablet B are picked for cumu compaction(X<=a<b<=Y).(cumu compaction
1013
            //    on new tablet during schema change double write is allowed after https://github.com/apache/doris/pull/16470)
1014
            // 3. schema change remove all rowsets on tablet B before version Z(b<=Z<=Y) before it begins to convert historical rowsets.
1015
            // 4. schema change finishes.
1016
            // 5. cumu compation begins on new tablet with version [a],...,[b]. If there are duplicate keys between these rowsets,
1017
            //    the compaction check will fail because these rowsets have skipped to calculate delete bitmap in commit phase and
1018
            //    publish phase because tablet B is in NOT_READY state when writing.
1019
1020
            // Considering that the cumu compaction will fail finally in this situation because `Tablet::modify_rowsets` will check if rowsets in
1021
            // `to_delete`(_input_rowsets) still exist in tablet's `_rs_version_map`, we can just skip to check missed rows here.
1022
0
            bool need_to_check_missed_rows = true;
1023
0
            {
1024
0
                std::shared_lock rlock(_tablet->get_header_lock());
1025
0
                need_to_check_missed_rows =
1026
0
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1027
0
                                    [&](const RowsetSharedPtr& rowset) {
1028
0
                                        return _tablet->rowset_exists_unlocked(rowset);
1029
0
                                    });
1030
0
            }
1031
1032
0
            if (_tablet->tablet_state() == TABLET_RUNNING && stats != nullptr &&
1033
0
                stats->merged_rows != missed_rows_size && need_to_check_missed_rows) {
1034
0
                std::stringstream ss;
1035
0
                ss << "cumulative compaction: the merged rows(" << stats->merged_rows
1036
0
                   << ") is not equal to missed rows(" << missed_rows_size
1037
0
                   << ") in rowid conversion, tablet_id: " << _tablet->tablet_id()
1038
0
                   << ", table_id:" << _tablet->table_id();
1039
0
                if (missed_rows_size == 0) {
1040
0
                    ss << ", debug info: ";
1041
0
                    DeleteBitmap subset_map(_tablet->tablet_id());
1042
0
                    for (auto rs : _input_rowsets) {
1043
0
                        _tablet->tablet_meta()->delete_bitmap().subset(
1044
0
                                {rs->rowset_id(), 0, 0},
1045
0
                                {rs->rowset_id(), rs->num_segments(), version.second + 1},
1046
0
                                &subset_map);
1047
0
                        ss << "(rowset id: " << rs->rowset_id()
1048
0
                           << ", delete bitmap cardinality: " << subset_map.cardinality() << ")";
1049
0
                    }
1050
0
                    ss << ", version[0-" << version.second + 1 << "]";
1051
0
                }
1052
0
                DCHECK(false) << ss.str();
1053
0
                LOG(WARNING) << ss.str();
1054
0
            }
1055
0
        }
1056
1057
0
        if (config::enable_rowid_conversion_correctness_check) {
1058
0
            RETURN_IF_ERROR(_tablet->check_rowid_conversion(_output_rowset, *location_map));
1059
0
            location_map->clear();
1060
0
        }
1061
1062
0
        {
1063
0
            std::lock_guard<std::mutex> wrlock_(_tablet->get_rowset_update_lock());
1064
0
            std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1065
0
            SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1066
1067
            // Here we will calculate all the rowsets delete bitmaps which are committed but not published to reduce the calculation pressure
1068
            // of publish phase.
1069
            // All rowsets which need to recalculate have been published so we don't need to acquire lock.
1070
            // Step1: collect this tablet's all committed rowsets' delete bitmaps
1071
0
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1072
0
            StorageEngine::instance()->txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1073
0
                    _tablet, &commit_tablet_txn_info_vec);
1074
1075
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1076
0
            for (auto& it : commit_tablet_txn_info_vec) {
1077
0
                if (!_check_if_includes_input_rowsets(it.rowset_ids)) {
1078
                    // When calculating the delete bitmap of all committed rowsets relative to the compaction,
1079
                    // there may be cases where the compacted rowsets are newer than the committed rowsets.
1080
                    // At this time, row number conversion cannot be performed, otherwise data will be missing.
1081
                    // Therefore, we need to check if every committed rowset has calculated delete bitmap for
1082
                    // all compaction input rowsets.
1083
0
                    continue;
1084
0
                }
1085
0
                DeleteBitmap txn_output_delete_bitmap(_tablet->tablet_id());
1086
0
                _tablet->calc_compaction_output_rowset_delete_bitmap(
1087
0
                        _input_rowsets, *_rowid_conversion, 0, UINT64_MAX, missed_rows.get(),
1088
0
                        location_map.get(), *it.delete_bitmap.get(), &txn_output_delete_bitmap);
1089
0
                if (config::enable_merge_on_write_correctness_check) {
1090
0
                    RowsetIdUnorderedSet rowsetids;
1091
0
                    rowsetids.insert(_output_rowset->rowset_id());
1092
0
                    _tablet->add_sentinel_mark_to_delete_bitmap(&txn_output_delete_bitmap,
1093
0
                                                                rowsetids);
1094
0
                }
1095
0
                it.delete_bitmap->merge(txn_output_delete_bitmap);
1096
                // Step3: write back updated delete bitmap and tablet info.
1097
0
                it.rowset_ids.insert(_output_rowset->rowset_id());
1098
0
                StorageEngine::instance()->txn_manager()->set_txn_related_delete_bitmap(
1099
0
                        it.partition_id, it.transaction_id, _tablet->tablet_id(),
1100
0
                        _tablet->tablet_uid(), true, it.delete_bitmap, it.rowset_ids,
1101
0
                        it.partial_update_info);
1102
0
            }
1103
1104
            // Convert the delete bitmap of the input rowsets to output rowset for
1105
            // incremental data.
1106
0
            _tablet->calc_compaction_output_rowset_delete_bitmap(
1107
0
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1108
0
                    missed_rows.get(), location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1109
0
                    &output_rowset_delete_bitmap);
1110
1111
0
            if (missed_rows) {
1112
0
                DCHECK_EQ(missed_rows->size(), missed_rows_size);
1113
0
                if (missed_rows->size() != missed_rows_size) {
1114
0
                    LOG(WARNING) << "missed rows don't match, before: " << missed_rows_size
1115
0
                                 << " after: " << missed_rows->size();
1116
0
                }
1117
0
            }
1118
1119
0
            if (location_map) {
1120
0
                RETURN_IF_ERROR(_tablet->check_rowid_conversion(_output_rowset, *location_map));
1121
0
            }
1122
1123
0
            _tablet->merge_delete_bitmap(output_rowset_delete_bitmap);
1124
0
            RETURN_IF_ERROR(_tablet->modify_rowsets(output_rowsets, _input_rowsets, true));
1125
0
        }
1126
0
    } else {
1127
0
        std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1128
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1129
0
        RETURN_IF_ERROR(_tablet->modify_rowsets(output_rowsets, _input_rowsets, true));
1130
0
    }
1131
1132
0
    if (config::tablet_rowset_stale_sweep_by_size &&
1133
0
        _tablet->tablet_meta()->all_stale_rs_metas().size() >=
1134
0
                config::tablet_rowset_stale_sweep_threshold_size) {
1135
0
        _tablet->delete_expired_stale_rowset();
1136
0
    }
1137
1138
0
    int64_t cur_max_version = 0;
1139
0
    {
1140
0
        std::shared_lock rlock(_tablet->get_header_lock());
1141
0
        cur_max_version = _tablet->max_version_unlocked().second;
1142
0
        _tablet->save_meta();
1143
0
    }
1144
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1145
0
        _tablet->enable_unique_key_merge_on_write()) {
1146
0
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1147
0
                _tablet->data_dir(), _tablet->tablet_id(), cur_max_version);
1148
0
        if (!st.ok()) {
1149
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1150
0
        }
1151
0
    }
1152
0
    return Status::OK();
1153
0
}
1154
1155
bool Compaction::_check_if_includes_input_rowsets(
1156
0
        const RowsetIdUnorderedSet& commit_rowset_ids_set) const {
1157
0
    std::vector<RowsetId> commit_rowset_ids {};
1158
0
    commit_rowset_ids.insert(commit_rowset_ids.end(), commit_rowset_ids_set.begin(),
1159
0
                             commit_rowset_ids_set.end());
1160
0
    std::sort(commit_rowset_ids.begin(), commit_rowset_ids.end());
1161
0
    std::vector<RowsetId> input_rowset_ids {};
1162
0
    for (const auto& rowset : _input_rowsets) {
1163
0
        input_rowset_ids.emplace_back(rowset->rowset_meta()->rowset_id());
1164
0
    }
1165
0
    std::sort(input_rowset_ids.begin(), input_rowset_ids.end());
1166
0
    return std::includes(commit_rowset_ids.begin(), commit_rowset_ids.end(),
1167
0
                         input_rowset_ids.begin(), input_rowset_ids.end());
1168
0
}
1169
1170
0
void Compaction::gc_output_rowset() {
1171
0
    if (_state != CompactionState::SUCCESS && _output_rowset != nullptr) {
1172
0
        if (!_output_rowset->is_local()) {
1173
0
            _tablet->record_unused_remote_rowset(_output_rowset->rowset_id(),
1174
0
                                                 _output_rowset->rowset_meta()->resource_id(),
1175
0
                                                 _output_rowset->num_segments());
1176
0
            return;
1177
0
        }
1178
0
        StorageEngine::instance()->add_unused_rowset(_output_rowset);
1179
0
    }
1180
0
}
1181
1182
// Find the longest consecutive version path in "rowset", from beginning.
1183
// Two versions before and after the missing version will be saved in missing_version,
1184
// if missing_version is not null.
1185
Status Compaction::find_longest_consecutive_version(std::vector<RowsetSharedPtr>* rowsets,
1186
16
                                                    std::vector<Version>* missing_version) {
1187
16
    if (rowsets->empty()) {
1188
2
        return Status::OK();
1189
2
    }
1190
14
    RowsetSharedPtr prev_rowset = rowsets->front();
1191
14
    size_t i = 1;
1192
288
    for (; i < rowsets->size(); ++i) {
1193
276
        RowsetSharedPtr rowset = (*rowsets)[i];
1194
276
        if (rowset->start_version() != prev_rowset->end_version() + 1) {
1195
2
            if (missing_version != nullptr) {
1196
0
                missing_version->push_back(prev_rowset->version());
1197
0
                missing_version->push_back(rowset->version());
1198
0
            }
1199
2
            break;
1200
2
        }
1201
274
        prev_rowset = rowset;
1202
274
    }
1203
1204
14
    rowsets->resize(i);
1205
14
    return Status::OK();
1206
16
}
1207
1208
1
Status Compaction::check_version_continuity(const std::vector<RowsetSharedPtr>& rowsets) {
1209
1
    if (rowsets.empty()) {
1210
0
        return Status::OK();
1211
0
    }
1212
1
    RowsetSharedPtr prev_rowset = rowsets.front();
1213
24
    for (size_t i = 1; i < rowsets.size(); ++i) {
1214
23
        RowsetSharedPtr rowset = rowsets[i];
1215
23
        if (rowset->start_version() != prev_rowset->end_version() + 1) {
1216
0
            return Status::Error<CUMULATIVE_MISS_VERSION>(
1217
0
                    "There are missed versions among rowsets. prev_rowset version={}-{}, rowset "
1218
0
                    "version={}-{}",
1219
0
                    prev_rowset->start_version(), prev_rowset->end_version(),
1220
0
                    rowset->start_version(), rowset->end_version());
1221
0
        }
1222
23
        prev_rowset = rowset;
1223
23
    }
1224
1225
1
    return Status::OK();
1226
1
}
1227
1228
0
Status Compaction::check_correctness(const Merger::Statistics& stats) {
1229
    // 1. check row number
1230
0
    if (_input_row_num != _output_rowset->num_rows() + stats.merged_rows + stats.filtered_rows) {
1231
0
        return Status::Error<CHECK_LINES_ERROR>(
1232
0
                "row_num does not match between cumulative input and output! tablet={}, "
1233
0
                "input_row_num={}, merged_row_num={}, filtered_row_num={}, output_row_num={}",
1234
0
                _tablet->tablet_id(), _input_row_num, stats.merged_rows, stats.filtered_rows,
1235
0
                _output_rowset->num_rows());
1236
0
    }
1237
0
    return Status::OK();
1238
0
}
1239
1240
0
int64_t Compaction::get_compaction_permits() {
1241
0
    int64_t permits = 0;
1242
0
    for (auto rowset : _input_rowsets) {
1243
0
        permits += rowset->rowset_meta()->get_compaction_score();
1244
0
    }
1245
0
    return permits;
1246
0
}
1247
1248
0
void Compaction::_load_segment_to_cache() {
1249
    // Load new rowset's segments to cache.
1250
0
    SegmentCacheHandle handle;
1251
0
    auto st = SegmentLoader::instance()->load_segments(
1252
0
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1253
0
    if (!st.ok()) {
1254
0
        LOG(WARNING) << "failed to load segment to cache! output rowset version="
1255
0
                     << _output_rowset->start_version() << "-" << _output_rowset->end_version()
1256
0
                     << ".";
1257
0
    }
1258
0
}
1259
1260
#ifdef BE_TEST
1261
1
void Compaction::set_input_rowset(const std::vector<RowsetSharedPtr>& rowsets) {
1262
1
    _input_rowsets = rowsets;
1263
1
}
1264
1265
1
RowsetSharedPtr Compaction::output_rowset() {
1266
1
    return _output_rowset;
1267
1
}
1268
#endif
1269
1270
} // namespace doris