Coverage Report

Created: 2026-08-07 13:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/compaction/compaction.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/compaction/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 "cloud/config.h"
43
#include "cloud/pb_convert.h"
44
#include "common/config.h"
45
#include "common/metrics/doris_metrics.h"
46
#include "common/status.h"
47
#include "cpp/sync_point.h"
48
#include "exec/common/variant_util.h"
49
#include "io/cache/block_file_cache_factory.h"
50
#include "io/fs/file_system.h"
51
#include "io/fs/file_writer.h"
52
#include "io/fs/remote_file_system.h"
53
#include "io/io_common.h"
54
#include "runtime/memory/mem_tracker_limiter.h"
55
#include "runtime/thread_context.h"
56
#include "storage/compaction/collection_statistics.h"
57
#include "storage/compaction/cumulative_compaction.h"
58
#include "storage/compaction/cumulative_compaction_binlog_policy.h"
59
#include "storage/compaction/cumulative_compaction_policy.h"
60
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
61
#include "storage/compaction_task_tracker.h"
62
#include "storage/data_dir.h"
63
#include "storage/index/index_file_reader.h"
64
#include "storage/index/index_file_writer.h"
65
#include "storage/index/inverted/inverted_index_compaction.h"
66
#include "storage/index/inverted/inverted_index_desc.h"
67
#include "storage/index/inverted/inverted_index_fs_directory.h"
68
#include "storage/olap_common.h"
69
#include "storage/olap_define.h"
70
#include "storage/rowset/beta_rowset.h"
71
#include "storage/rowset/beta_rowset_reader.h"
72
#include "storage/rowset/beta_rowset_writer.h"
73
#include "storage/rowset/rowset.h"
74
#include "storage/rowset/rowset_fwd.h"
75
#include "storage/rowset/rowset_meta.h"
76
#include "storage/rowset/rowset_writer.h"
77
#include "storage/rowset/rowset_writer_context.h"
78
#include "storage/storage_engine.h"
79
#include "storage/storage_policy.h"
80
#include "storage/tablet/tablet.h"
81
#include "storage/tablet/tablet_meta.h"
82
#include "storage/tablet/tablet_meta_manager.h"
83
#include "storage/task/engine_checksum_task.h"
84
#include "storage/txn/txn_manager.h"
85
#include "storage/utils.h"
86
#include "util/pretty_printer.h"
87
#include "util/time.h"
88
#include "util/trace.h"
89
90
using std::vector;
91
92
namespace doris {
93
using namespace ErrorCode;
94
95
// Determine whether to enable index-only file cache mode for compaction output.
96
// This function decides if only index files should be written to cache, based on:
97
// - write_file_cache: whether file cache is enabled
98
// - compaction_type: type of compaction (base or cumulative)
99
// - enable_base_index_only: config flag for base compaction
100
// - enable_cumu_index_only: config flag for cumulative compaction
101
// Returns true if index-only mode should be enabled, false otherwise.
102
bool should_enable_compaction_cache_index_only(bool write_file_cache, ReaderType compaction_type,
103
                                               bool enable_base_index_only,
104
7.08k
                                               bool enable_cumu_index_only) {
105
7.08k
    if (!write_file_cache) {
106
129
        return false;
107
129
    }
108
109
6.96k
    if (compaction_type == ReaderType::READER_BASE_COMPACTION && enable_base_index_only) {
110
2
        return true;
111
2
    }
112
113
6.95k
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION && enable_cumu_index_only) {
114
2
        return true;
115
2
    }
116
117
6.95k
    return false;
118
6.95k
}
119
120
namespace {
121
122
bool is_rowset_tidy(std::string& pre_max_key, bool& pre_rs_key_bounds_truncated,
123
4.30k
                    const RowsetSharedPtr& rhs) {
124
4.30k
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
125
4.30k
    if (rhs->num_segments() == 0) {
126
3.48k
        return true;
127
3.48k
    }
128
825
    if (rhs->is_segments_overlapping()) {
129
0
        return false;
130
0
    }
131
    // check segment size
132
825
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
133
825
    std::vector<size_t> segments_size;
134
825
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
135
833
    for (auto segment_size : segments_size) {
136
        // is segment is too small, need to do compaction
137
833
        if (segment_size < min_tidy_size) {
138
736
            return false;
139
736
        }
140
833
    }
141
88
    std::string min_key;
142
88
    auto ret = rhs->first_key(&min_key);
143
88
    if (!ret) {
144
0
        return false;
145
0
    }
146
88
    bool cur_rs_key_bounds_truncated {rhs->is_segments_key_bounds_truncated()};
147
88
    if (!Slice::lhs_is_strictly_less_than_rhs(Slice {pre_max_key}, pre_rs_key_bounds_truncated,
148
88
                                              Slice {min_key}, cur_rs_key_bounds_truncated)) {
149
23
        return false;
150
23
    }
151
88
    CHECK(rhs->last_key(&pre_max_key));
152
65
    pre_rs_key_bounds_truncated = cur_rs_key_bounds_truncated;
153
65
    return true;
154
88
}
155
156
11.7k
TsoRange commit_tso_range(const std::vector<RowsetSharedPtr>& rowsets) {
157
11.7k
    DCHECK(!rowsets.empty());
158
11.7k
    auto range = rowsets.front()->commit_tso();
159
97.9k
    for (const auto& rowset : rowsets) {
160
97.9k
        const auto commit_tso = rowset->commit_tso();
161
97.9k
        range.first = std::min(range.first, commit_tso.start_tso());
162
97.9k
        range.second = std::max(range.second, commit_tso.end_tso());
163
97.9k
    }
164
11.7k
    return range;
165
11.7k
}
166
167
} // namespace
168
169
Compaction::Compaction(BaseTabletSPtr tablet, const std::string& label)
170
485k
        : _compaction_id(CompactionTaskTracker::instance()->next_compaction_id()),
171
          _mem_tracker(
172
485k
                  MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label)),
173
485k
          _tablet(std::move(tablet)),
174
485k
          _is_vertical(config::enable_vertical_compaction),
175
485k
          _allow_delete_in_cumu_compaction(config::enable_delete_when_cumu_compaction),
176
          _enable_vertical_compact_variant_subcolumns(
177
485k
                  config::enable_vertical_compact_variant_subcolumns),
178
485k
          _enable_inverted_index_compaction(config::inverted_index_compaction_enable) {
179
485k
    init_profile(label);
180
485k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
181
485k
    _rowid_conversion = std::make_unique<RowIdConversion>();
182
485k
}
183
184
485k
Compaction::~Compaction() {
185
485k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
186
485k
    _output_rs_writer.reset();
187
485k
    _tablet.reset();
188
485k
    _input_rowsets.clear();
189
485k
    _output_rowset.reset();
190
485k
    _cur_tablet_schema.reset();
191
485k
    _rowid_conversion.reset();
192
485k
}
193
194
22.0k
std::string Compaction::input_version_range_str() const {
195
22.0k
    if (_input_rowsets.empty()) return "";
196
22.0k
    return fmt::format("[{}-{}]", _input_rowsets.front()->start_version(),
197
22.0k
                       _input_rowsets.back()->end_version());
198
22.0k
}
199
200
void Compaction::submit_profile_record(bool success, int64_t start_time_ms,
201
11.6k
                                       const std::string& status_msg) {
202
11.6k
    if (!profile_type().has_value()) {
203
850
        return;
204
850
    }
205
10.8k
    auto* tracker = CompactionTaskTracker::instance();
206
10.8k
    CompletionStats stats;
207
    // Input stats for backfill: local compaction fills these in build_basic_info()
208
    // which runs inside execute_compact_impl(), so they are available now.
209
10.8k
    stats.input_version_range = input_version_range_str();
210
10.8k
    stats.input_rowsets_count = static_cast<int64_t>(_input_rowsets.size());
211
10.8k
    stats.input_row_num = _input_row_num;
212
10.8k
    stats.input_data_size = _input_rowsets_data_size;
213
10.8k
    stats.input_index_size = _input_rowsets_index_size;
214
10.8k
    stats.input_total_size = _input_rowsets_total_size;
215
10.8k
    stats.input_segments_num = input_segments_num_value();
216
10.8k
    stats.end_time_ms = UnixMillis();
217
10.8k
    stats.merged_rows = _stats.merged_rows;
218
10.8k
    stats.filtered_rows = _stats.filtered_rows;
219
10.8k
    stats.output_rows = _stats.output_rows;
220
10.8k
    if (_output_rowset) {
221
10.8k
        stats.output_row_num = _output_rowset->num_rows();
222
10.8k
        stats.output_data_size = _output_rowset->data_disk_size();
223
10.8k
        stats.output_index_size = _output_rowset->index_disk_size();
224
10.8k
        stats.output_total_size = _output_rowset->total_disk_size();
225
10.8k
        stats.output_segments_num = _output_rowset->num_segments();
226
10.8k
    }
227
10.8k
    stats.output_version = _output_version.to_string();
228
10.8k
    stats.is_ordered_data_compaction = _is_ordered_data_compaction;
229
10.8k
    if (_merge_rowsets_latency_timer) {
230
10.8k
        stats.merge_latency_ms = _merge_rowsets_latency_timer->value() / 1000000;
231
10.8k
    }
232
10.8k
    stats.bytes_read_from_local = _stats.bytes_read_from_local;
233
10.8k
    stats.bytes_read_from_remote = _stats.bytes_read_from_remote;
234
10.8k
    if (_mem_tracker) {
235
10.8k
        stats.peak_memory_bytes = _mem_tracker->peak_consumption();
236
10.8k
    }
237
10.8k
    if (success) {
238
10.8k
        tracker->complete(_compaction_id, stats);
239
10.8k
    } else {
240
10
        tracker->fail(_compaction_id, stats, status_msg);
241
10
    }
242
10.8k
}
243
244
485k
void Compaction::init_profile(const std::string& label) {
245
485k
    _profile = std::make_unique<RuntimeProfile>(label);
246
247
485k
    _input_rowsets_data_size_counter =
248
485k
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
249
485k
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
250
485k
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
251
485k
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
252
485k
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
253
485k
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
254
485k
    _output_rowset_data_size_counter =
255
485k
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
256
485k
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
257
485k
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
258
485k
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
259
485k
}
260
261
11.1k
int64_t Compaction::merge_way_num() {
262
11.1k
    int64_t way_num = 0;
263
94.4k
    for (auto&& rowset : _input_rowsets) {
264
94.4k
        way_num += rowset->rowset_meta()->get_merge_way_num();
265
94.4k
    }
266
267
11.1k
    return way_num;
268
11.1k
}
269
270
11.2k
Status Compaction::merge_input_rowsets() {
271
11.2k
    MergeInputRowsetsResult result;
272
11.2k
    RETURN_IF_ERROR(prepare_merge_input_rowsets(&result));
273
274
11.2k
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
275
11.2k
    input_rs_readers.reserve(_input_rowsets.size());
276
94.7k
    for (auto& rowset : _input_rowsets) {
277
94.7k
        RowsetReaderSharedPtr rs_reader;
278
94.7k
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
279
94.7k
        input_rs_readers.push_back(std::move(rs_reader));
280
94.7k
    }
281
282
11.2k
    RowsetWriterContext ctx;
283
    // Propagate input rowset readers into the rowset writer context before the writer is created.
284
    // Variant nested-group compaction uses this metadata to enable the streaming writer path.
285
11.2k
    ctx.input_rs_readers = input_rs_readers;
286
11.2k
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
287
288
    // write merged rows to output rowset
289
    // The test results show that merger is low-memory-footprint, there is no need to tracker its mem pool
290
    // if ctx.columns_to_do_index_compaction.size() > 0, it means we need to do inverted index compaction.
291
    // the row ID conversion matrix needs to be used for inverted index compaction.
292
11.2k
    if (!ctx.columns_to_do_index_compaction.empty() ||
293
11.2k
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
294
10.8k
         _tablet->enable_unique_key_merge_on_write())) {
295
6.92k
        _stats.rowid_conversion = _rowid_conversion.get();
296
6.92k
    }
297
298
11.2k
    {
299
11.2k
        SCOPED_TIMER(_merge_rowsets_latency_timer);
300
        // 1. Merge segment files and write bkd inverted index
301
11.2k
        RETURN_IF_ERROR(do_merge_input_rowsets(input_rs_readers, &result));
302
        // 2. Merge the remaining inverted index files of the string type
303
11.2k
        RETURN_IF_ERROR(do_inverted_index_compaction());
304
11.2k
    }
305
306
11.2k
    COUNTER_UPDATE(_merged_rows_counter, _stats.merged_rows);
307
11.2k
    COUNTER_UPDATE(_filtered_rows_counter, _stats.filtered_rows);
308
309
    // 3. In the `build`, `_close_file_writers` is called to close the inverted index file writer and write the final compound index file.
310
11.2k
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
311
11.2k
                                   fmt::format("rowset writer build failed. output_version: {}",
312
11.2k
                                               _output_version.to_string()));
313
11.2k
    _output_rowset->rowset_meta()->set_commit_tso(commit_tso_range(_input_rowsets));
314
315
    // When true, writers should remove variant extracted subcolumns from the
316
    // schema stored in RowsetMeta. This is used when compaction temporarily
317
    // extends schema to split variant subcolumns for vertical compaction but
318
    // the final rowset meta must not persist those extracted subcolumns.
319
11.2k
    if (_enable_vertical_compact_variant_subcolumns &&
320
11.2k
        (_cur_tablet_schema->num_variant_columns() > 0)) {
321
562
        _output_rowset->rowset_meta()->set_tablet_schema(
322
562
                _cur_tablet_schema->copy_without_variant_extracted_columns());
323
562
    }
324
325
    //RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get()));
326
11.2k
    set_delete_predicate_for_output_rowset();
327
11.2k
    update_output_rowset_after_build(result);
328
329
11.2k
    _local_read_bytes_total = _stats.bytes_read_from_local;
330
11.2k
    _remote_read_bytes_total = _stats.bytes_read_from_remote;
331
11.2k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(_local_read_bytes_total);
332
11.2k
    DorisMetrics::instance()->remote_compaction_read_bytes_total->increment(
333
11.2k
            _remote_read_bytes_total);
334
11.2k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
335
11.2k
            _stats.cached_bytes_total);
336
337
11.2k
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
338
11.2k
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
339
11.2k
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
340
341
11.2k
    return check_correctness();
342
11.2k
}
343
344
Status Compaction::do_merge_input_rowsets(
345
        const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
346
11.1k
        MergeInputRowsetsResult* /*result*/) {
347
11.1k
    return execute_merge(input_rs_readers, merge_way_num(), &_stats);
348
11.1k
}
349
350
Status Compaction::execute_merge(const std::vector<RowsetReaderSharedPtr>& input_rs_readers,
351
                                 int64_t merge_way_num, Merger::Statistics* stats,
352
                                 std::optional<std::pair<int64_t, int64_t>> segment_range,
353
11.2k
                                 VerticalMergeProgressContext progress) {
354
11.2k
    Status status;
355
    // TODO implement vertical compaction for seq map
356
11.2k
    if (_is_vertical && !_tablet->tablet_schema()->has_seq_map()) {
357
11.2k
        if (!_tablet->tablet_schema()->cluster_key_uids().empty() && !segment_range.has_value()) {
358
107
            RETURN_IF_ERROR(update_delete_bitmap());
359
107
        }
360
11.2k
        auto progress_cb = [compaction_id = this->_compaction_id, progress](int64_t total,
361
39.8k
                                                                            int64_t completed) {
362
39.8k
            CompactionTaskTracker::instance()->update_progress(
363
39.8k
                    compaction_id, total * progress.total_ranges,
364
39.8k
                    total * progress.range_index + completed);
365
39.8k
        };
366
11.2k
        status = Merger::vertical_merge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
367
11.2k
                                                input_rs_readers, _output_rs_writer.get(),
368
11.2k
                                                cast_set<uint32_t>(get_avg_segment_rows()),
369
11.2k
                                                merge_way_num, stats, progress_cb, segment_range);
370
18.4E
    } else {
371
18.4E
        if (!_tablet->tablet_schema()->cluster_key_uids().empty()) {
372
0
            return Status::InternalError(
373
0
                    "mow table with cluster keys does not support non vertical compaction");
374
0
        }
375
18.4E
        status = Merger::vmerge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
376
18.4E
                                        input_rs_readers, _output_rs_writer.get(), stats,
377
18.4E
                                        segment_range);
378
18.4E
    }
379
380
11.2k
    _tablet->last_compaction_status = status;
381
11.2k
    return status;
382
11.2k
}
383
384
11.1k
void Compaction::set_delete_predicate_for_output_rowset() {
385
    // Now we support delete in cumu compaction, to make all data in rowsets whose version
386
    // is below output_version to be delete in the future base compaction, we should carry
387
    // all delete predicate in the output rowset.
388
    // Output start version > 2 means we must set the delete predicate in the output rowset
389
11.1k
    if (_output_rowset->version().first > 2 &&
390
11.1k
        (_allow_delete_in_cumu_compaction || is_index_change_compaction())) {
391
502
        DeletePredicatePB delete_predicate;
392
502
        std::accumulate(_input_rowsets.begin(), _input_rowsets.end(), &delete_predicate,
393
502
                        [](DeletePredicatePB* delete_predicate, const RowsetSharedPtr& rs) {
394
501
                            if (rs->rowset_meta()->has_delete_predicate()) {
395
3
                                delete_predicate->MergeFrom(rs->rowset_meta()->delete_predicate());
396
3
                            }
397
501
                            return delete_predicate;
398
501
                        });
399
        // now version in delete_predicate is deprecated
400
502
        if (!delete_predicate.in_predicates().empty() ||
401
502
            !delete_predicate.sub_predicates_v2().empty() ||
402
502
            !delete_predicate.sub_predicates().empty()) {
403
3
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
404
3
        }
405
502
    }
406
11.1k
}
407
408
11.1k
int64_t Compaction::get_avg_segment_rows() {
409
    // take care of empty rowset
410
    // input_rowsets_size is total disk_size of input_rowset, this size is the
411
    // final size after codec and compress, so expect dest segment file size
412
    // in disk is config::vertical_compaction_max_segment_size
413
11.1k
    const auto& meta = _tablet->tablet_meta();
414
11.1k
    if (meta->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY) {
415
6
        int64_t compaction_goal_size_mbytes = meta->time_series_compaction_goal_size_mbytes();
416
        // The output segment rows should be less than total input rows
417
6
        return std::min((compaction_goal_size_mbytes * 1024 * 1024 * 2) /
418
6
                                (_input_rowsets_data_size / (_input_row_num + 1) + 1),
419
6
                        _input_row_num + 1);
420
6
    }
421
11.1k
    return std::min(config::vertical_compaction_max_segment_size /
422
11.1k
                            (_input_rowsets_data_size / (_input_row_num + 1) + 1),
423
11.1k
                    _input_row_num + 1);
424
11.1k
}
425
426
CompactionMixin::CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet,
427
                                 const std::string& label)
428
372k
        : Compaction(tablet, label), _engine(engine) {}
429
430
372k
CompactionMixin::~CompactionMixin() {
431
372k
    if (_state != CompactionState::SUCCESS && _output_rowset != nullptr) {
432
6
        if (!_output_rowset->is_local()) {
433
0
            tablet()->record_unused_remote_rowset(_output_rowset->rowset_id(),
434
0
                                                  _output_rowset->rowset_meta()->resource_id(),
435
0
                                                  _output_rowset->num_segments());
436
0
            return;
437
0
        }
438
6
        _engine.add_unused_rowset(_output_rowset);
439
6
    }
440
372k
}
441
442
3.91M
Tablet* CompactionMixin::tablet() {
443
3.91M
    return static_cast<Tablet*>(_tablet.get());
444
3.91M
}
445
446
514
Status CompactionMixin::do_compact_ordered_rowsets() {
447
514
    RETURN_IF_ERROR(build_basic_info(true));
448
514
    RowsetWriterContext ctx;
449
514
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
450
514
    const auto& output_rowset_dir = tablet()->tablet_path();
451
452
514
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
453
514
              << ", output_version=" << _output_version;
454
    // link data to new rowset
455
514
    auto seg_id = 0;
456
514
    bool segments_key_bounds_truncated {false};
457
514
    bool any_input_aggregated {false};
458
514
    std::vector<KeyBoundsPB> segment_key_bounds;
459
514
    std::vector<uint32_t> num_segment_rows;
460
3.20k
    for (auto rowset : _input_rowsets) {
461
3.20k
        RETURN_IF_ERROR(
462
3.20k
                rowset->link_files_to(output_rowset_dir, _output_rs_writer->rowset_id(), seg_id));
463
3.20k
        seg_id += rowset->num_segments();
464
3.20k
        segments_key_bounds_truncated |= rowset->is_segments_key_bounds_truncated();
465
3.20k
        any_input_aggregated |= rowset->rowset_meta()->is_segments_key_bounds_aggregated();
466
3.20k
        std::vector<KeyBoundsPB> key_bounds;
467
3.20k
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
468
3.20k
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
469
3.20k
        std::vector<uint32_t> input_segment_rows;
470
3.20k
        rowset->get_num_segment_rows(&input_segment_rows);
471
3.20k
        num_segment_rows.insert(num_segment_rows.end(), input_segment_rows.begin(),
472
3.20k
                                input_segment_rows.end());
473
3.20k
    }
474
    // build output rowset
475
514
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
476
514
    rowset_meta->set_num_rows(_input_row_num);
477
514
    rowset_meta->set_total_disk_size(_input_rowsets_data_size + _input_rowsets_index_size);
478
514
    rowset_meta->set_data_disk_size(_input_rowsets_data_size);
479
514
    rowset_meta->set_index_disk_size(_input_rowsets_index_size);
480
514
    rowset_meta->set_empty(_input_row_num == 0);
481
514
    rowset_meta->set_num_segments(_input_num_segments);
482
514
    rowset_meta->set_segments_overlap(_trigger_quick_merge_by_binlog ? OVERLAPPING
483
514
                                                                     : NONOVERLAPPING);
484
514
    rowset_meta->set_rowset_state(VISIBLE);
485
514
    rowset_meta->set_segments_key_bounds_truncated(segments_key_bounds_truncated);
486
    // If any input was already aggregated we have no way to recover per-segment
487
    // bounds, so force aggregation on the output to keep the layout consistent
488
    // with `num_segments` / the aggregated flag, even if the config is off now.
489
514
    bool aggregate_key_bounds =
490
514
            any_input_aggregated ||
491
514
            (config::enable_aggregate_non_mow_key_bounds &&
492
502
             !_tablet->enable_unique_key_merge_on_write() && !tablet()->is_row_binlog_tablet());
493
514
    rowset_meta->set_segments_key_bounds(segment_key_bounds, aggregate_key_bounds);
494
514
    rowset_meta->set_num_segment_rows(num_segment_rows);
495
514
    rowset_meta->set_commit_tso(commit_tso_range(_input_rowsets));
496
497
514
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
498
499
    // 2. check variant column path stats
500
514
    RETURN_IF_ERROR(variant_util::VariantCompactionUtil::check_path_stats(_input_rowsets,
501
514
                                                                          _output_rowset, _tablet));
502
514
    return Status::OK();
503
514
}
504
505
4.61k
Status CompactionMixin::build_basic_info(bool is_ordered_compaction) {
506
41.4k
    for (auto& rowset : _input_rowsets) {
507
41.4k
        const auto& rowset_meta = rowset->rowset_meta();
508
41.4k
        auto index_size = rowset_meta->index_disk_size();
509
41.4k
        auto total_size = rowset_meta->total_disk_size();
510
41.4k
        auto data_size = rowset_meta->data_disk_size();
511
        // corrupted index size caused by bug before 2.1.5 or 3.0.0 version
512
        // try to get real index size from disk.
513
41.4k
        if (index_size < 0 || index_size > total_size * 2) {
514
0
            LOG(ERROR) << "invalid index size:" << index_size << " total size:" << total_size
515
0
                       << " data size:" << data_size << " tablet:" << rowset_meta->tablet_id()
516
0
                       << " rowset:" << rowset_meta->rowset_id();
517
0
            index_size = 0;
518
0
            auto st = rowset->get_inverted_index_size(&index_size);
519
0
            if (!st.ok()) {
520
0
                LOG(ERROR) << "failed to get inverted index size. res=" << st;
521
0
            }
522
0
        }
523
41.4k
        _input_rowsets_data_size += data_size;
524
41.4k
        _input_rowsets_index_size += index_size;
525
41.4k
        _input_rowsets_total_size += total_size;
526
41.4k
        _input_row_num += rowset->num_rows();
527
41.4k
        _input_num_segments += rowset->num_segments();
528
41.4k
    }
529
4.61k
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_data_size);
530
4.61k
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
531
4.61k
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
532
533
4.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::build_basic_info",
534
4.61k
                                      Status::OK());
535
536
4.61k
    _output_version =
537
4.61k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
538
539
4.61k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
540
541
4.61k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
542
4.61k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
543
41.7k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
544
4.61k
    _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
545
546
    // if enable_vertical_compact_variant_subcolumns is true, we need to compact the variant subcolumns in seperate column groups
547
    // so get_extended_compaction_schema will extended the schema for variant columns
548
    // for ordered compaction, we don't need to extend the schema for variant columns
549
4.61k
    if (_enable_vertical_compact_variant_subcolumns && !is_ordered_compaction) {
550
4.11k
        RETURN_IF_ERROR(variant_util::VariantCompactionUtil::get_extended_compaction_schema(
551
4.11k
                _input_rowsets, _cur_tablet_schema));
552
4.11k
    }
553
4.61k
    return Status::OK();
554
4.61k
}
555
556
4.66k
bool CompactionMixin::handle_ordered_data_compaction() {
557
4.66k
    if (config::is_cloud_mode()) {
558
0
        return false;
559
0
    }
560
4.66k
    if (!config::enable_ordered_data_compaction) {
561
0
        return false;
562
0
    }
563
564
    // If some rowsets has idx files and some rowsets has not, we can not do link file compaction.
565
    // Since the output rowset will be broken.
566
567
    // Use schema version instead of schema hash to check if they are the same,
568
    // because light schema change will not change the schema hash on BE, but will increase the schema version
569
    // See fe/fe-core/src/main/java/org/apache/doris/alter/SchemaChangeHandler.java::2979
570
4.66k
    std::vector<int32_t> schema_versions_of_rowsets;
571
572
41.7k
    for (auto input_rowset : _input_rowsets) {
573
41.7k
        schema_versions_of_rowsets.push_back(input_rowset->rowset_meta()->schema_version());
574
41.7k
    }
575
576
    // If all rowsets has same schema version, then we can do link file compaction directly.
577
4.66k
    bool all_same_schema_version =
578
4.66k
            std::all_of(schema_versions_of_rowsets.begin(), schema_versions_of_rowsets.end(),
579
41.7k
                        [&](int32_t v) { return v == schema_versions_of_rowsets.front(); });
580
581
4.66k
    if (!all_same_schema_version) {
582
0
        return false;
583
0
    }
584
585
4.66k
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
586
4.66k
        compaction_type() == ReaderType::READER_FULL_COMPACTION) {
587
        // The remote file system and full compaction does not support to link files.
588
2
        return false;
589
2
    }
590
4.65k
    bool is_binlog_compaction = _tablet->is_row_binlog_tablet();
591
4.65k
    if (is_binlog_compaction && !_input_rowsets.empty()) {
592
0
        RowsetIdUnorderedSet input_rowset_ids;
593
0
        input_rowset_ids.reserve(_input_rowsets.size());
594
0
        for (const auto& rs : _input_rowsets) {
595
0
            input_rowset_ids.insert(rs->rowset_id());
596
0
        }
597
0
        if (_tablet->tablet_meta()->delete_bitmap().contain_rowsets(input_rowset_ids)) {
598
0
            return false;
599
0
        }
600
0
    }
601
602
4.65k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
603
4.65k
        _tablet->enable_unique_key_merge_on_write() && !is_binlog_compaction) {
604
3.43k
        return false;
605
3.43k
    }
606
607
1.22k
    if (_tablet->tablet_meta()->tablet_schema()->skip_write_index_on_load()) {
608
        // Expected to create index through normal compaction
609
0
        return false;
610
0
    }
611
612
    // check delete version: if compaction type is base compaction and
613
    // has a delete version, use original compaction
614
1.22k
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION ||
615
1.22k
        (_allow_delete_in_cumu_compaction &&
616
1.21k
         compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION)) {
617
24
        for (auto& rowset : _input_rowsets) {
618
24
            if (rowset->rowset_meta()->has_delete_predicate()) {
619
8
                return false;
620
8
            }
621
24
        }
622
8
    }
623
624
1.22k
    if (is_binlog_compaction) {
625
0
        DCHECK(!_input_rowsets.empty()) << "tablet=" << _tablet->tablet_id();
626
0
        auto compaction_level = _input_rowsets.front()->rowset_meta()->compaction_level();
627
0
        bool can_quick_merge_binlog =
628
0
                compaction_level ==
629
0
                        BinlogCumulativeCompactionPolicy::kBinlogCompactionMaxLevel - 1 &&
630
0
                _input_rowsets.size() >= 2 && _input_rowsets[0]->start_version() == 0;
631
0
        if (!can_quick_merge_binlog) {
632
0
            return false;
633
0
        }
634
0
        _trigger_quick_merge_by_binlog = true;
635
636
        // Binlog quick merge at LMax is a special meta/link compaction path selected by
637
        // BinlogCumulativeCompactionPolicy. It does not require the whole input to satisfy the normal
638
        // ordered-data tidy check, but the output rowset built by do_compact_ordered_rowsets()
639
        // is still NONOVERLAPPING (excluding row-binlog).
640
0
        auto st = do_compact_ordered_rowsets();
641
0
        if (!st.ok()) {
642
0
            LOG(WARNING) << "failed to compact ordered rowsets: " << st;
643
0
            _pending_rs_guard.drop();
644
0
        }
645
0
        return st.ok();
646
1.22k
    } else {
647
        // Check if rowsets are tidy so we can just modify meta and do link files to handle
648
        // ordered data compaction.
649
1.22k
        auto input_size = _input_rowsets.size();
650
1.22k
        std::string pre_max_key;
651
1.22k
        bool pre_rs_key_bounds_truncated {false};
652
4.76k
        for (auto i = 0; i < input_size; ++i) {
653
4.30k
            if (!is_rowset_tidy(pre_max_key, pre_rs_key_bounds_truncated, _input_rowsets[i])) {
654
760
                if (i <= input_size / 2) {
655
704
                    return false;
656
704
                } else {
657
56
                    _input_rowsets.resize(i);
658
56
                    break;
659
56
                }
660
760
            }
661
4.30k
        }
662
1.22k
    }
663
664
    // most rowset of current compaction is nonoverlapping
665
    // just handle nonoverlappint rowsets
666
516
    auto st = do_compact_ordered_rowsets();
667
516
    if (!st.ok()) {
668
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
669
0
        _pending_rs_guard.drop();
670
0
    }
671
672
516
    return st.ok();
673
1.22k
}
674
675
4.61k
Status CompactionMixin::execute_compact() {
676
4.61k
    int64_t profile_start_time_ms = UnixMillis();
677
4.61k
    uint32_t checksum_before;
678
4.61k
    uint32_t checksum_after;
679
4.61k
    bool enable_compaction_checksum = config::enable_compaction_checksum;
680
4.61k
    if (enable_compaction_checksum) {
681
0
        EngineChecksumTask checksum_task(_engine, _tablet->tablet_id(), _tablet->schema_hash(),
682
0
                                         _input_rowsets.back()->end_version(), &checksum_before);
683
0
        auto st = checksum_task.execute();
684
0
        if (!st.ok()) {
685
0
            submit_profile_record(false, profile_start_time_ms, st.to_string());
686
0
            return st;
687
0
        }
688
0
    }
689
690
4.61k
    auto* data_dir = tablet()->data_dir();
691
4.61k
    int64_t permits = get_compaction_permits();
692
4.61k
    data_dir->disks_compaction_score_increment(permits);
693
4.61k
    data_dir->disks_compaction_num_increment(1);
694
695
4.61k
    auto record_compaction_stats = [&](const doris::Exception& ex) {
696
4.61k
        _tablet->compaction_count.fetch_add(1, std::memory_order_relaxed);
697
4.61k
        data_dir->disks_compaction_score_increment(-permits);
698
4.61k
        data_dir->disks_compaction_num_increment(-1);
699
4.61k
    };
700
    // Handler for execute_compact_impl failure (both Status error and C++ exception).
701
    // The macro calls this then returns, so submit_profile_record(false) must be here.
702
4.61k
    auto on_compact_impl_failure = [&](const doris::Exception& ex) {
703
0
        record_compaction_stats(ex);
704
0
        submit_profile_record(false, profile_start_time_ms,
705
0
                              ex.what() ? std::string(ex.what()) : "");
706
0
    };
707
708
4.61k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(execute_compact_impl(permits), on_compact_impl_failure);
709
    // Only reached on success (macro returns on failure).
710
4.61k
    record_compaction_stats(doris::Exception());
711
712
4.61k
    if (enable_compaction_checksum) {
713
0
        EngineChecksumTask checksum_task(_engine, _tablet->tablet_id(), _tablet->schema_hash(),
714
0
                                         _input_rowsets.back()->end_version(), &checksum_after);
715
0
        auto st = checksum_task.execute();
716
0
        if (!st.ok()) {
717
0
            submit_profile_record(false, profile_start_time_ms, st.to_string());
718
0
            return st;
719
0
        }
720
0
        if (checksum_before != checksum_after) {
721
0
            auto mismatch_st = Status::InternalError(
722
0
                    "compaction tablet checksum not consistent, before={}, after={}, tablet_id={}",
723
0
                    checksum_before, checksum_after, _tablet->tablet_id());
724
0
            submit_profile_record(false, profile_start_time_ms, mismatch_st.to_string());
725
0
            return mismatch_st;
726
0
        }
727
0
    }
728
729
4.61k
    DorisMetrics::instance()->local_compaction_read_rows_total->increment(_input_row_num);
730
4.61k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(
731
4.61k
            _input_rowsets_total_size);
732
733
4.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact", Status::OK());
734
735
4.61k
    DorisMetrics::instance()->local_compaction_write_rows_total->increment(
736
4.61k
            _output_rowset->num_rows());
737
4.61k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
738
4.61k
            _output_rowset->total_disk_size());
739
740
4.61k
    _load_segment_to_cache();
741
4.61k
    submit_profile_record(true, profile_start_time_ms);
742
4.61k
    return Status::OK();
743
4.61k
}
744
745
4.61k
Status CompactionMixin::execute_compact_impl(int64_t permits) {
746
4.61k
    OlapStopWatch watch;
747
748
4.61k
    if (handle_ordered_data_compaction()) {
749
498
        _is_ordered_data_compaction = true;
750
498
        RETURN_IF_ERROR(modify_rowsets());
751
498
        int64_t input_compaction_level = _input_rowsets.front()->rowset_meta()->compaction_level();
752
498
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
753
498
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
754
498
                  << ", disk=" << tablet()->data_dir()->path()
755
498
                  << ", input_compaction_level=" << input_compaction_level
756
498
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
757
498
                  << ", output_row_num=" << _output_rowset->num_rows()
758
498
                  << ", input_rowsets_data_size=" << _input_rowsets_data_size
759
498
                  << ", input_rowsets_index_size=" << _input_rowsets_index_size
760
498
                  << ", input_rowsets_total_size=" << _input_rowsets_total_size
761
498
                  << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
762
498
                  << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
763
498
                  << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
764
498
                  << ". elapsed time=" << watch.get_elapse_second() << "s.";
765
498
        _state = CompactionState::SUCCESS;
766
498
        return Status::OK();
767
498
    }
768
4.12k
    RETURN_IF_ERROR(build_basic_info());
769
770
4.12k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact_impl",
771
4.12k
                                      Status::OK());
772
773
4.12k
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
774
775
4.12k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
776
4.12k
              << ", output_version=" << _output_version << ", permits: " << permits;
777
778
4.12k
    RETURN_IF_ERROR(merge_input_rowsets());
779
780
    // Currently, updates are only made in the time_series and binlog policies.
781
4.12k
    update_compaction_level();
782
783
4.12k
    RETURN_IF_ERROR(modify_rowsets());
784
785
4.12k
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
786
4.12k
    DCHECK(cumu_policy);
787
4.12k
    int64_t input_compaction_level = _input_rowsets.front()->rowset_meta()->compaction_level();
788
4.12k
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << _is_vertical
789
4.12k
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
790
4.12k
              << ", current_max_version=" << tablet()->max_version().second
791
4.12k
              << ", disk=" << tablet()->data_dir()->path()
792
4.12k
              << ", input_compaction_level=" << input_compaction_level
793
4.12k
              << ", input_segments=" << _input_num_segments << ", input_rowsets_data_size="
794
4.12k
              << PrettyPrinter::print_bytes(_input_rowsets_data_size)
795
4.12k
              << ", input_rowsets_index_size="
796
4.12k
              << PrettyPrinter::print_bytes(_input_rowsets_index_size)
797
4.12k
              << ", input_rowsets_total_size="
798
4.12k
              << PrettyPrinter::print_bytes(_input_rowsets_total_size)
799
4.12k
              << ", output_rowset_data_size="
800
4.12k
              << PrettyPrinter::print_bytes(_output_rowset->data_disk_size())
801
4.12k
              << ", output_rowset_index_size="
802
4.12k
              << PrettyPrinter::print_bytes(_output_rowset->index_disk_size())
803
4.12k
              << ", output_rowset_total_size="
804
4.12k
              << PrettyPrinter::print_bytes(_output_rowset->total_disk_size())
805
4.12k
              << ", input_row_num=" << _input_row_num
806
4.12k
              << ", output_row_num=" << _output_rowset->num_rows()
807
4.12k
              << ", filtered_row_num=" << _stats.filtered_rows
808
4.12k
              << ", merged_row_num=" << _stats.merged_rows
809
4.12k
              << ". elapsed time=" << watch.get_elapse_second()
810
4.12k
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
811
4.12k
              << ", compact_row_per_second="
812
4.12k
              << cast_set<double>(_input_row_num) / watch.get_elapse_second();
813
814
4.12k
    _state = CompactionState::SUCCESS;
815
816
4.12k
    return Status::OK();
817
4.12k
}
818
819
11.2k
Status Compaction::do_inverted_index_compaction() {
820
11.2k
    const auto& ctx = _output_rs_writer->context();
821
11.2k
    if (!_enable_inverted_index_compaction || _input_row_num <= 0 ||
822
11.2k
        ctx.columns_to_do_index_compaction.empty()) {
823
11.0k
        return Status::OK();
824
11.0k
    }
825
826
213
    auto error_handler = [this](int64_t index_id, int64_t column_uniq_id) {
827
2
        LOG(WARNING) << "failed to do index compaction"
828
2
                     << ". tablet=" << _tablet->tablet_id() << ". column uniq id=" << column_uniq_id
829
2
                     << ". index_id=" << index_id;
830
4
        for (auto& rowset : _input_rowsets) {
831
4
            rowset->set_skip_index_compaction(cast_set<int32_t>(column_uniq_id));
832
4
            LOG(INFO) << "mark skipping inverted index compaction next time"
833
4
                      << ". tablet=" << _tablet->tablet_id() << ", rowset=" << rowset->rowset_id()
834
4
                      << ", column uniq id=" << column_uniq_id << ", index_id=" << index_id;
835
4
        }
836
2
    };
837
838
213
    DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_rowid_conversion_null",
839
213
                    { _stats.rowid_conversion = nullptr; })
840
213
    if (!_stats.rowid_conversion) {
841
0
        LOG(WARNING) << "failed to do index compaction, rowid conversion is null"
842
0
                     << ". tablet=" << _tablet->tablet_id()
843
0
                     << ", input row number=" << _input_row_num;
844
0
        mark_skip_index_compaction(ctx, error_handler);
845
846
0
        return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
847
0
                "failed to do index compaction, rowid conversion is null. tablet={}",
848
0
                _tablet->tablet_id());
849
0
    }
850
851
213
    OlapStopWatch inverted_watch;
852
853
    // translation vec
854
    // <<dest_idx_num, dest_docId>>
855
    // the first level vector: index indicates src segment.
856
    // the second level vector: index indicates row id of source segment,
857
    // value indicates row id of destination segment.
858
    // <UINT32_MAX, UINT32_MAX> indicates current row not exist.
859
213
    const auto& trans_vec = _stats.rowid_conversion->get_rowid_conversion_map();
860
861
    // source rowset,segment -> index_id
862
213
    const auto& src_seg_to_id_map = _stats.rowid_conversion->get_src_segment_to_id_map();
863
864
    // dest rowset id
865
213
    RowsetId dest_rowset_id = _stats.rowid_conversion->get_dst_rowset_id();
866
    // dest segment id -> num rows
867
213
    std::vector<uint32_t> dest_segment_num_rows;
868
213
    RETURN_IF_ERROR(_output_rs_writer->get_segment_num_rows(&dest_segment_num_rows));
869
870
213
    auto src_segment_num = src_seg_to_id_map.size();
871
213
    auto dest_segment_num = dest_segment_num_rows.size();
872
873
    // when all the input rowsets are deleted, the output rowset will be empty and dest_segment_num will be 0.
874
213
    if (dest_segment_num <= 0) {
875
2
        LOG(INFO) << "skip doing index compaction due to no output segments"
876
2
                  << ". tablet=" << _tablet->tablet_id() << ", input row number=" << _input_row_num
877
2
                  << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
878
2
        return Status::OK();
879
2
    }
880
881
    // Only write info files when debug index compaction is enabled.
882
    // The files are used to debug index compaction and works with index_tool.
883
211
    if (config::debug_inverted_index_compaction) {
884
        // src index files
885
        // format: rowsetId_segmentId
886
0
        std::vector<std::string> src_index_files(src_segment_num);
887
0
        for (const auto& m : src_seg_to_id_map) {
888
0
            std::pair<RowsetId, uint32_t> p = m.first;
889
0
            src_index_files[m.second] = p.first.to_string() + "_" + std::to_string(p.second);
890
0
        }
891
892
        // dest index files
893
        // format: rowsetId_segmentId
894
0
        std::vector<std::string> dest_index_files(dest_segment_num);
895
0
        for (int i = 0; i < dest_segment_num; ++i) {
896
0
            auto prefix = dest_rowset_id.to_string() + "_" + std::to_string(i);
897
0
            dest_index_files[i] = prefix;
898
0
        }
899
900
0
        auto write_json_to_file = [&](const nlohmann::json& json_obj,
901
0
                                      const std::string& file_name) {
902
0
            io::FileWriterPtr file_writer;
903
0
            std::string file_path =
904
0
                    fmt::format("{}/{}.json", std::string(getenv("LOG_DIR")), file_name);
905
0
            RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &file_writer));
906
0
            RETURN_IF_ERROR(file_writer->append(json_obj.dump()));
907
0
            RETURN_IF_ERROR(file_writer->append("\n"));
908
0
            return file_writer->close();
909
0
        };
910
911
        // Convert trans_vec to JSON and print it
912
0
        nlohmann::json trans_vec_json = trans_vec;
913
0
        auto output_version =
914
0
                _output_version.to_string().substr(1, _output_version.to_string().size() - 2);
915
0
        RETURN_IF_ERROR(write_json_to_file(
916
0
                trans_vec_json,
917
0
                fmt::format("trans_vec_{}_{}", _tablet->tablet_id(), output_version)));
918
919
0
        nlohmann::json src_index_files_json = src_index_files;
920
0
        RETURN_IF_ERROR(write_json_to_file(
921
0
                src_index_files_json,
922
0
                fmt::format("src_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
923
924
0
        nlohmann::json dest_index_files_json = dest_index_files;
925
0
        RETURN_IF_ERROR(write_json_to_file(
926
0
                dest_index_files_json,
927
0
                fmt::format("dest_idx_dirs_{}_{}", _tablet->tablet_id(), output_version)));
928
929
0
        nlohmann::json dest_segment_num_rows_json = dest_segment_num_rows;
930
0
        RETURN_IF_ERROR(write_json_to_file(
931
0
                dest_segment_num_rows_json,
932
0
                fmt::format("dest_seg_num_rows_{}_{}", _tablet->tablet_id(), output_version)));
933
0
    }
934
935
    // create index_writer to compaction indexes
936
211
    std::unordered_map<RowsetId, Rowset*> rs_id_to_rowset_map;
937
1.41k
    for (auto&& rs : _input_rowsets) {
938
1.41k
        rs_id_to_rowset_map.emplace(rs->rowset_id(), rs.get());
939
1.41k
    }
940
941
    // src index dirs
942
211
    std::vector<std::unique_ptr<IndexFileReader>> index_file_readers(src_segment_num);
943
950
    for (const auto& m : src_seg_to_id_map) {
944
950
        const auto& [rowset_id, seg_id] = m.first;
945
946
950
        auto find_it = rs_id_to_rowset_map.find(rowset_id);
947
950
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_find_rowset_error",
948
950
                        { find_it = rs_id_to_rowset_map.end(); })
949
950
        if (find_it == rs_id_to_rowset_map.end()) [[unlikely]] {
950
0
            LOG(WARNING) << "failed to do index compaction, cannot find rowset. tablet_id="
951
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string();
952
0
            mark_skip_index_compaction(ctx, error_handler);
953
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
954
0
                    "failed to do index compaction, cannot find rowset. tablet_id={} rowset_id={}",
955
0
                    _tablet->tablet_id(), rowset_id.to_string());
956
0
        }
957
958
950
        auto* rowset = find_it->second;
959
950
        auto fs = rowset->rowset_meta()->fs();
960
950
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_get_fs_error", { fs = nullptr; })
961
950
        if (!fs) {
962
0
            LOG(WARNING) << "failed to do index compaction, get fs failed. resource_id="
963
0
                         << rowset->rowset_meta()->resource_id();
964
0
            mark_skip_index_compaction(ctx, error_handler);
965
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
966
0
                    "get fs failed, resource_id={}", rowset->rowset_meta()->resource_id());
967
0
        }
968
969
950
        auto seg_path = rowset->segment_path(seg_id);
970
950
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_seg_path_nullptr", {
971
950
            seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
972
950
                    "do_inverted_index_compaction_seg_path_nullptr"));
973
950
        })
974
950
        if (!seg_path.has_value()) {
975
0
            LOG(WARNING) << "failed to do index compaction, get segment path failed. tablet_id="
976
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string()
977
0
                         << " seg_id=" << seg_id;
978
0
            mark_skip_index_compaction(ctx, error_handler);
979
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
980
0
                    "get segment path failed. tablet_id={} rowset_id={} seg_id={}",
981
0
                    _tablet->tablet_id(), rowset_id.to_string(), seg_id);
982
0
        }
983
950
        auto index_file_reader = std::make_unique<IndexFileReader>(
984
950
                fs,
985
950
                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path.value())},
986
950
                _cur_tablet_schema->get_inverted_index_storage_format(),
987
950
                rowset->rowset_meta()->inverted_index_file_info(seg_id), _tablet->tablet_id());
988
950
        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
989
950
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_init_inverted_index_file_reader",
990
950
                        {
991
950
                            st = Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
992
950
                                    "debug point: "
993
950
                                    "Compaction::do_inverted_index_compaction_init_inverted_index_"
994
950
                                    "file_reader error");
995
950
                        })
996
950
        if (!st.ok()) {
997
0
            LOG(WARNING) << "failed to do index compaction, init inverted index file reader "
998
0
                            "failed. tablet_id="
999
0
                         << _tablet->tablet_id() << " rowset_id=" << rowset_id.to_string()
1000
0
                         << " seg_id=" << seg_id;
1001
0
            mark_skip_index_compaction(ctx, error_handler);
1002
0
            return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
1003
0
                    "init inverted index file reader failed. tablet_id={} rowset_id={} seg_id={}",
1004
0
                    _tablet->tablet_id(), rowset_id.to_string(), seg_id);
1005
0
        }
1006
950
        index_file_readers[m.second] = std::move(index_file_reader);
1007
950
    }
1008
1009
    // dest index files
1010
    // format: rowsetId_segmentId
1011
211
    auto& inverted_index_file_writers =
1012
211
            dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get())->index_file_writers();
1013
211
    DBUG_EXECUTE_IF(
1014
211
            "Compaction::do_inverted_index_compaction_inverted_index_file_writers_size_error",
1015
211
            { inverted_index_file_writers.clear(); })
1016
211
    if (inverted_index_file_writers.size() != dest_segment_num) {
1017
0
        LOG(WARNING) << "failed to do index compaction, dest segment num not match. tablet_id="
1018
0
                     << _tablet->tablet_id() << " dest_segment_num=" << dest_segment_num
1019
0
                     << " inverted_index_file_writers.size()="
1020
0
                     << inverted_index_file_writers.size();
1021
0
        mark_skip_index_compaction(ctx, error_handler);
1022
0
        return Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
1023
0
                "dest segment num not match. tablet_id={} dest_segment_num={} "
1024
0
                "inverted_index_file_writers.size()={}",
1025
0
                _tablet->tablet_id(), dest_segment_num, inverted_index_file_writers.size());
1026
0
    }
1027
1028
    // use tmp file dir to store index files
1029
211
    auto tmp_file_dir = ExecEnv::GetInstance()->get_tmp_file_dirs()->get_tmp_file_dir();
1030
211
    auto index_tmp_path = tmp_file_dir / dest_rowset_id.to_string();
1031
211
    LOG(INFO) << "start index compaction"
1032
211
              << ". tablet=" << _tablet->tablet_id() << ", source index size=" << src_segment_num
1033
211
              << ", destination index size=" << dest_segment_num << ".";
1034
1035
211
    Status status = Status::OK();
1036
750
    for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
1037
750
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
1038
750
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
1039
750
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_can_not_find_index_meta",
1040
750
                        { index_metas.clear(); })
1041
750
        if (index_metas.empty()) {
1042
0
            status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(
1043
0
                    fmt::format("Can not find index_meta for col {}", col.name()));
1044
0
            LOG(WARNING) << "failed to do index compaction, can not find index_meta for column"
1045
0
                         << ". tablet=" << _tablet->tablet_id()
1046
0
                         << ", column uniq id=" << column_uniq_id;
1047
0
            error_handler(-1, column_uniq_id);
1048
0
            break;
1049
0
        }
1050
756
        for (const auto& index_meta : index_metas) {
1051
756
            std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
1052
756
            try {
1053
756
                std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>> src_idx_dirs(
1054
756
                        src_segment_num);
1055
3.56k
                for (int src_segment_id = 0; src_segment_id < src_segment_num; src_segment_id++) {
1056
2.80k
                    auto res = index_file_readers[src_segment_id]->open(index_meta);
1057
2.80k
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
1058
2.80k
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1059
2.80k
                                "debug point: Compaction::open_index_file_reader error"));
1060
2.80k
                    })
1061
2.80k
                    if (!res.has_value()) {
1062
0
                        LOG(WARNING) << "failed to do index compaction, open inverted index file "
1063
0
                                        "reader failed"
1064
0
                                     << ". tablet=" << _tablet->tablet_id()
1065
0
                                     << ", column uniq id=" << column_uniq_id
1066
0
                                     << ", src_segment_id=" << src_segment_id;
1067
0
                        throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
1068
0
                                        res.error().msg());
1069
0
                    }
1070
2.80k
                    src_idx_dirs[src_segment_id] = std::move(res.value());
1071
2.80k
                }
1072
1.62k
                for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
1073
867
                     dest_segment_id++) {
1074
867
                    auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
1075
867
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
1076
867
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1077
867
                                "debug point: Compaction::open_inverted_index_file_writer error"));
1078
867
                    })
1079
867
                    if (!res.has_value()) {
1080
0
                        LOG(WARNING) << "failed to do index compaction, open inverted index file "
1081
0
                                        "writer failed"
1082
0
                                     << ". tablet=" << _tablet->tablet_id()
1083
0
                                     << ", column uniq id=" << column_uniq_id
1084
0
                                     << ", dest_segment_id=" << dest_segment_id;
1085
0
                        throw Exception(ErrorCode::INVERTED_INDEX_COMPACTION_ERROR,
1086
0
                                        res.error().msg());
1087
0
                    }
1088
                    // Destination directories in dest_index_dirs do not need to be deconstructed,
1089
                    // but their lifecycle must be managed by inverted_index_file_writers.
1090
867
                    dest_index_dirs[dest_segment_id] = res.value().get();
1091
867
                }
1092
756
                auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
1093
756
                                         index_tmp_path.native(), trans_vec, dest_segment_num_rows);
1094
756
                if (!st.ok()) {
1095
2
                    error_handler(index_meta->index_id(), column_uniq_id);
1096
2
                    status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(st.msg());
1097
2
                }
1098
756
            } catch (CLuceneError& e) {
1099
0
                error_handler(index_meta->index_id(), column_uniq_id);
1100
0
                status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
1101
0
            } catch (const Exception& e) {
1102
0
                error_handler(index_meta->index_id(), column_uniq_id);
1103
0
                status = Status::Error<INVERTED_INDEX_COMPACTION_ERROR>(e.what());
1104
0
            }
1105
756
        }
1106
750
    }
1107
1108
    // check index compaction status. If status is not ok, we should return error and end this compaction round.
1109
211
    if (!status.ok()) {
1110
1
        return status;
1111
1
    }
1112
211
    LOG(INFO) << "succeed to do index compaction"
1113
210
              << ". tablet=" << _tablet->tablet_id()
1114
210
              << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
1115
1116
210
    return Status::OK();
1117
211
}
1118
1119
void Compaction::mark_skip_index_compaction(
1120
        const RowsetWriterContext& context,
1121
0
        const std::function<void(int64_t, int64_t)>& error_handler) {
1122
0
    for (auto&& column_uniq_id : context.columns_to_do_index_compaction) {
1123
0
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
1124
0
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
1125
0
        DBUG_EXECUTE_IF("Compaction::mark_skip_index_compaction_can_not_find_index_meta",
1126
0
                        { index_metas.clear(); })
1127
0
        if (index_metas.empty()) {
1128
0
            LOG(WARNING) << "mark skip index compaction, can not find index_meta for column"
1129
0
                         << ". tablet=" << _tablet->tablet_id()
1130
0
                         << ", column uniq id=" << column_uniq_id;
1131
0
            error_handler(-1, column_uniq_id);
1132
0
            continue;
1133
0
        }
1134
0
        for (const auto& index_meta : index_metas) {
1135
0
            error_handler(index_meta->index_id(), column_uniq_id);
1136
0
        }
1137
0
    }
1138
0
}
1139
1140
static bool check_rowset_has_inverted_index(const RowsetSharedPtr& src_rs, int32_t col_unique_id,
1141
                                            const BaseTabletSPtr& tablet,
1142
9.72k
                                            const TabletSchemaSPtr& cur_tablet_schema) {
1143
9.72k
    auto* rowset = static_cast<BetaRowset*>(src_rs.get());
1144
9.72k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_is_skip_index_compaction",
1145
9.72k
                    { rowset->set_skip_index_compaction(col_unique_id); })
1146
9.72k
    if (rowset->is_skip_index_compaction(col_unique_id)) {
1147
1
        LOG(WARNING) << "tablet[" << tablet->tablet_id() << "] rowset[" << rowset->rowset_id()
1148
1
                     << "] column_unique_id[" << col_unique_id
1149
1
                     << "] skip inverted index compaction due to last failure";
1150
1
        return false;
1151
1
    }
1152
1153
9.71k
    auto fs = rowset->rowset_meta()->fs();
1154
9.71k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_get_fs_error", { fs = nullptr; })
1155
9.71k
    if (!fs) {
1156
129
        LOG(WARNING) << "get fs failed, resource_id=" << rowset->rowset_meta()->resource_id();
1157
129
        return false;
1158
129
    }
1159
1160
9.59k
    auto index_metas = rowset->tablet_schema()->inverted_indexs(col_unique_id);
1161
9.59k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_meta_nullptr",
1162
9.59k
                    { index_metas.clear(); })
1163
9.59k
    if (index_metas.empty()) {
1164
0
        LOG(WARNING) << "tablet[" << tablet->tablet_id() << "] column_unique_id[" << col_unique_id
1165
0
                     << "] index meta is null, will skip index compaction";
1166
0
        return false;
1167
0
    }
1168
9.80k
    for (const auto& index_meta : index_metas) {
1169
13.0k
        for (auto i = 0; i < rowset->num_segments(); i++) {
1170
            // TODO: inverted_index_path
1171
3.27k
            auto seg_path = rowset->segment_path(i);
1172
3.27k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_seg_path_nullptr", {
1173
3.27k
                seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
1174
3.27k
                        "construct_skip_inverted_index_seg_path_nullptr"));
1175
3.27k
            })
1176
3.27k
            if (!seg_path) {
1177
0
                LOG(WARNING) << seg_path.error();
1178
0
                return false;
1179
0
            }
1180
1181
3.27k
            std::string index_file_path;
1182
3.27k
            try {
1183
3.27k
                auto index_file_reader = std::make_unique<IndexFileReader>(
1184
3.27k
                        fs,
1185
3.27k
                        std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
1186
3.27k
                                seg_path.value())},
1187
3.27k
                        cur_tablet_schema->get_inverted_index_storage_format(),
1188
3.27k
                        rowset->rowset_meta()->inverted_index_file_info(i), tablet->tablet_id());
1189
3.27k
                auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
1190
3.27k
                index_file_path = index_file_reader->get_index_file_path(index_meta);
1191
3.27k
                DBUG_EXECUTE_IF(
1192
3.27k
                        "Compaction::construct_skip_inverted_index_index_file_reader_init_"
1193
3.27k
                        "status_not_ok",
1194
3.27k
                        {
1195
3.27k
                            st = Status::Error<ErrorCode::INTERNAL_ERROR>(
1196
3.27k
                                    "debug point: "
1197
3.27k
                                    "construct_skip_inverted_index_index_file_reader_init_"
1198
3.27k
                                    "status_"
1199
3.27k
                                    "not_ok");
1200
3.27k
                        })
1201
3.27k
                if (!st.ok()) {
1202
0
                    LOG(WARNING) << "init index " << index_file_path << " error:" << st;
1203
0
                    return false;
1204
0
                }
1205
1206
                // check index meta
1207
3.27k
                auto result = index_file_reader->open(index_meta);
1208
3.27k
                DBUG_EXECUTE_IF(
1209
3.27k
                        "Compaction::construct_skip_inverted_index_index_file_reader_open_"
1210
3.27k
                        "error",
1211
3.27k
                        {
1212
3.27k
                            result = ResultError(
1213
3.27k
                                    Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1214
3.27k
                                            "CLuceneError occur when open idx file"));
1215
3.27k
                        })
1216
3.27k
                if (!result.has_value()) {
1217
0
                    LOG(WARNING) << "open index " << index_file_path << " error:" << result.error();
1218
0
                    return false;
1219
0
                }
1220
3.27k
                auto reader = std::move(result.value());
1221
3.27k
                std::vector<std::string> files;
1222
3.27k
                reader->list(&files);
1223
3.27k
                reader->close();
1224
3.27k
                DBUG_EXECUTE_IF(
1225
3.27k
                        "Compaction::construct_skip_inverted_index_index_reader_close_"
1226
3.27k
                        "error",
1227
3.27k
                        { _CLTHROWA(CL_ERR_IO, "debug point: reader close error"); })
1228
1229
3.27k
                DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_files_count",
1230
3.27k
                                { files.clear(); })
1231
1232
                // why is 3?
1233
                // slice type index file at least has 3 files: null_bitmap, segments_N, segments.gen
1234
3.27k
                if (files.size() < 3) {
1235
0
                    LOG(WARNING) << "tablet[" << tablet->tablet_id() << "] column_unique_id["
1236
0
                                 << col_unique_id << "]," << index_file_path
1237
0
                                 << " is corrupted, will skip index compaction";
1238
0
                    return false;
1239
0
                }
1240
3.27k
            } catch (CLuceneError& err) {
1241
0
                LOG(WARNING) << "tablet[" << tablet->tablet_id() << "] column_unique_id["
1242
0
                             << col_unique_id << "] open index[" << index_file_path
1243
0
                             << "], will skip index compaction, error:" << err.what();
1244
0
                return false;
1245
0
            }
1246
3.27k
        }
1247
9.80k
    }
1248
9.59k
    return true;
1249
9.59k
}
1250
1251
10.0k
void Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
1252
10.0k
    for (const auto& index : _cur_tablet_schema->inverted_indexes()) {
1253
2.42k
        auto col_unique_ids = index->col_unique_ids();
1254
        // check if column unique ids is empty to avoid crash
1255
2.42k
        if (col_unique_ids.empty()) {
1256
1
            LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] index[" << index->index_id()
1257
1
                         << "] has no column unique id, will skip index compaction."
1258
1
                         << " tablet_schema=" << _cur_tablet_schema->dump_full_schema();
1259
1
            continue;
1260
1
        }
1261
2.42k
        auto col_unique_id = col_unique_ids[0];
1262
2.42k
        if (!_cur_tablet_schema->has_column_unique_id(col_unique_id)) {
1263
0
            LOG(WARNING) << "tablet[" << _tablet->tablet_id() << "] column_unique_id["
1264
0
                         << col_unique_id << "] not found, will skip index compaction";
1265
0
            continue;
1266
0
        }
1267
        // Avoid doing inverted index compaction on non-slice type columns
1268
2.42k
        if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
1269
871
            continue;
1270
871
        }
1271
1272
        // if index properties are different, index compaction maybe needs to be skipped.
1273
1.55k
        bool is_continue = false;
1274
1.55k
        std::optional<std::map<std::string, std::string>> first_properties;
1275
11.0k
        for (const auto& rowset : _input_rowsets) {
1276
11.0k
            auto tablet_indexs = rowset->tablet_schema()->inverted_indexs(col_unique_id);
1277
            // no inverted index or index id is different from current index id
1278
11.0k
            auto it = std::find_if(tablet_indexs.begin(), tablet_indexs.end(),
1279
11.1k
                                   [&index](const auto& tablet_index) {
1280
11.1k
                                       return tablet_index->index_id() == index->index_id();
1281
11.1k
                                   });
1282
11.0k
            if (it != tablet_indexs.end()) {
1283
11.0k
                const auto* tablet_index = *it;
1284
11.0k
                auto properties = tablet_index->properties();
1285
11.0k
                if (!first_properties.has_value()) {
1286
1.55k
                    first_properties = properties;
1287
9.45k
                } else {
1288
9.45k
                    DBUG_EXECUTE_IF(
1289
9.45k
                            "Compaction::do_inverted_index_compaction_index_properties_different",
1290
9.45k
                            { properties.emplace("dummy_key", "dummy_value"); })
1291
9.45k
                    if (properties != first_properties.value()) {
1292
3
                        is_continue = true;
1293
3
                        break;
1294
3
                    }
1295
9.45k
                }
1296
11.0k
            } else {
1297
1
                is_continue = true;
1298
1
                break;
1299
1
            }
1300
11.0k
        }
1301
1.55k
        if (is_continue) {
1302
5
            continue;
1303
5
        }
1304
1.54k
        bool all_have_inverted_index =
1305
1.54k
                std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1306
9.72k
                            [this, col_unique_id](const RowsetSharedPtr& src_rs) {
1307
9.72k
                                return check_rowset_has_inverted_index(src_rs, col_unique_id,
1308
9.72k
                                                                       _tablet, _cur_tablet_schema);
1309
9.72k
                            });
1310
1311
1.54k
        if (all_have_inverted_index) {
1312
1.42k
            ctx.columns_to_do_index_compaction.insert(col_unique_id);
1313
1.42k
        }
1314
1.54k
    }
1315
10.0k
}
1316
1317
0
Status CompactionMixin::update_delete_bitmap() {
1318
    // for mow with cluster keys, compaction read data with delete bitmap
1319
    // if tablet is not ready(such as schema change), we need to update delete bitmap
1320
0
    {
1321
0
        std::shared_lock meta_rlock(_tablet->get_header_lock());
1322
0
        if (_tablet->tablet_state() != TABLET_NOTREADY) {
1323
0
            return Status::OK();
1324
0
        }
1325
0
    }
1326
0
    OlapStopWatch watch;
1327
0
    std::vector<RowsetSharedPtr> rowsets;
1328
0
    for (const auto& rowset : _input_rowsets) {
1329
0
        std::lock_guard rwlock(tablet()->get_rowset_update_lock());
1330
0
        std::shared_lock rlock(_tablet->get_header_lock());
1331
0
        Status st = _tablet->update_delete_bitmap_without_lock(_tablet, rowset, &rowsets);
1332
0
        if (!st.ok()) {
1333
0
            LOG(INFO) << "failed update_delete_bitmap_without_lock for tablet_id="
1334
0
                      << _tablet->tablet_id() << ", st=" << st.to_string();
1335
0
            return st;
1336
0
        }
1337
0
        rowsets.push_back(rowset);
1338
0
    }
1339
0
    LOG(INFO) << "finish update delete bitmap for tablet: " << _tablet->tablet_id()
1340
0
              << ", rowsets: " << _input_rowsets.size() << ", cost: " << watch.get_elapse_time_us()
1341
0
              << "(us)";
1342
0
    return Status::OK();
1343
0
}
1344
1345
107
Status CloudCompactionMixin::update_delete_bitmap() {
1346
    // for mow with cluster keys, compaction read data with delete bitmap
1347
    // if tablet is not ready(such as schema change), we need to update delete bitmap
1348
107
    {
1349
107
        std::shared_lock meta_rlock(_tablet->get_header_lock());
1350
107
        if (_tablet->tablet_state() != TABLET_NOTREADY) {
1351
107
            return Status::OK();
1352
107
        }
1353
107
    }
1354
0
    OlapStopWatch watch;
1355
0
    std::vector<RowsetSharedPtr> rowsets;
1356
0
    for (const auto& rowset : _input_rowsets) {
1357
0
        Status st = _tablet->update_delete_bitmap_without_lock(_tablet, rowset, &rowsets);
1358
0
        if (!st.ok()) {
1359
0
            LOG(INFO) << "failed update_delete_bitmap_without_lock for tablet_id="
1360
0
                      << _tablet->tablet_id() << ", st=" << st.to_string();
1361
0
            return st;
1362
0
        }
1363
0
        rowsets.push_back(rowset);
1364
0
    }
1365
0
    LOG(INFO) << "finish update delete bitmap for tablet: " << _tablet->tablet_id()
1366
0
              << ", rowsets: " << _input_rowsets.size() << ", cost: " << watch.get_elapse_time_us()
1367
0
              << "(us)";
1368
0
    return Status::OK();
1369
0
}
1370
1371
void CompactionMixin::find_longest_consecutive_version(std::vector<RowsetSharedPtr>* rowsets,
1372
287k
                                                       std::vector<Version>* missing_version) {
1373
287k
    if (rowsets->empty()) {
1374
0
        return;
1375
0
    }
1376
1377
287k
    RowsetSharedPtr prev_rowset = rowsets->front();
1378
287k
    int max_start = 0;
1379
287k
    int max_length = 1;
1380
287k
    int start = 0;
1381
287k
    int length = 1;
1382
1.05M
    for (int i = 1; i < rowsets->size(); ++i) {
1383
768k
        RowsetSharedPtr rowset = (*rowsets)[i];
1384
768k
        if (rowset->start_version() != prev_rowset->end_version() + 1) {
1385
6
            if (missing_version != nullptr) {
1386
6
                missing_version->push_back(prev_rowset->version());
1387
6
                missing_version->push_back(rowset->version());
1388
6
            }
1389
6
            start = i;
1390
6
            length = 1;
1391
768k
        } else {
1392
768k
            ++length;
1393
768k
        }
1394
1395
768k
        if (length > max_length) {
1396
768k
            max_start = start;
1397
768k
            max_length = length;
1398
768k
        }
1399
1400
768k
        prev_rowset = rowset;
1401
768k
    }
1402
287k
    *rowsets = {rowsets->begin() + max_start, rowsets->begin() + max_start + max_length};
1403
287k
}
1404
1405
4.68k
Status CompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1406
    // only do index compaction for dup_keys and unique_keys with mow enabled
1407
4.68k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1408
4.63k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1409
4.63k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1410
4.60k
        construct_index_compaction_columns(ctx);
1411
4.60k
    }
1412
4.68k
    if (_tablet->is_row_binlog_tablet()) {
1413
0
        ctx.write_binlog_opt().enable = true;
1414
0
    }
1415
4.68k
    ctx.version = _output_version;
1416
4.68k
    ctx.rowset_state = VISIBLE;
1417
4.68k
    ctx.segments_overlap = _trigger_quick_merge_by_binlog ? OVERLAPPING : NONOVERLAPPING;
1418
4.68k
    ctx.tablet_schema = _cur_tablet_schema;
1419
4.68k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1420
4.68k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1421
4.68k
    ctx.compaction_type = compaction_type();
1422
4.68k
    ctx.allow_packed_file = false;
1423
4.68k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1424
4.68k
    _pending_rs_guard = _engine.add_pending_rowset(ctx);
1425
4.68k
    return Status::OK();
1426
4.68k
}
1427
1428
4.63k
Status CompactionMixin::modify_rowsets() {
1429
4.63k
    std::vector<RowsetSharedPtr> output_rowsets;
1430
4.63k
    output_rowsets.push_back(_output_rowset);
1431
1432
4.63k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1433
4.63k
        _tablet->enable_unique_key_merge_on_write()) {
1434
3.42k
        Version version = tablet()->max_version();
1435
3.42k
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
1436
3.42k
        std::unique_ptr<RowLocationSet> missed_rows;
1437
3.42k
        if ((config::enable_missing_rows_correctness_check ||
1438
3.42k
             config::enable_mow_compaction_correctness_check_core ||
1439
3.42k
             config::enable_mow_compaction_correctness_check_fail) &&
1440
3.42k
            !_allow_delete_in_cumu_compaction &&
1441
3.42k
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1442
3.41k
            missed_rows = std::make_unique<RowLocationSet>();
1443
3.41k
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
1444
3.41k
        }
1445
3.42k
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1446
3.42k
        if (config::enable_rowid_conversion_correctness_check &&
1447
3.42k
            tablet()->tablet_schema()->cluster_key_uids().empty()) {
1448
0
            location_map = std::make_unique<std::map<RowsetSharedPtr, RowLocationPairList>>();
1449
0
            LOG(INFO) << "Location Map inited succ for tablet:" << _tablet->tablet_id();
1450
0
        }
1451
        // Convert the delete bitmap of the input rowsets to output rowset.
1452
        // New loads are not blocked, so some keys of input rowsets might
1453
        // be deleted during the time. We need to deal with delete bitmap
1454
        // of incremental data later.
1455
        // TODO(LiaoXin): check if there are duplicate keys
1456
3.42k
        std::size_t missed_rows_size = 0;
1457
3.42k
        tablet()->calc_compaction_output_rowset_delete_bitmap(
1458
3.42k
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1459
3.42k
                location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1460
3.42k
                &output_rowset_delete_bitmap);
1461
3.43k
        if (missed_rows) {
1462
3.43k
            missed_rows_size = missed_rows->size();
1463
3.43k
            std::size_t merged_missed_rows_size = _stats.merged_rows;
1464
3.43k
            if (!_tablet->tablet_meta()->tablet_schema()->cluster_key_uids().empty()) {
1465
0
                merged_missed_rows_size += _stats.filtered_rows;
1466
0
            }
1467
1468
            // Suppose a heavy schema change process on BE converting tablet A to tablet B.
1469
            // 1. during schema change double write, new loads write [X-Y] on tablet B.
1470
            // 2. rowsets with version [a],[a+1],...,[b-1],[b] on tablet B are picked for cumu compaction(X<=a<b<=Y).(cumu compaction
1471
            //    on new tablet during schema change double write is allowed after https://github.com/apache/doris/pull/16470)
1472
            // 3. schema change remove all rowsets on tablet B before version Z(b<=Z<=Y) before it begins to convert historical rowsets.
1473
            // 4. schema change finishes.
1474
            // 5. cumu compation begins on new tablet with version [a],...,[b]. If there are duplicate keys between these rowsets,
1475
            //    the compaction check will fail because these rowsets have skipped to calculate delete bitmap in commit phase and
1476
            //    publish phase because tablet B is in NOT_READY state when writing.
1477
1478
            // Considering that the cumu compaction will fail finally in this situation because `Tablet::modify_rowsets` will check if rowsets in
1479
            // `to_delete`(_input_rowsets) still exist in tablet's `_rs_version_map`, we can just skip to check missed rows here.
1480
3.43k
            bool need_to_check_missed_rows = true;
1481
3.43k
            {
1482
3.43k
                std::shared_lock rlock(_tablet->get_header_lock());
1483
3.43k
                need_to_check_missed_rows =
1484
3.43k
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1485
32.3k
                                    [&](const RowsetSharedPtr& rowset) {
1486
32.3k
                                        return tablet()->rowset_exists_unlocked(rowset);
1487
32.3k
                                    });
1488
3.43k
            }
1489
1490
3.43k
            if (_tablet->tablet_state() == TABLET_RUNNING &&
1491
3.43k
                merged_missed_rows_size != missed_rows_size && need_to_check_missed_rows) {
1492
0
                std::stringstream ss;
1493
0
                ss << "cumulative compaction: the merged rows(" << _stats.merged_rows
1494
0
                   << "), filtered rows(" << _stats.filtered_rows
1495
0
                   << ") is not equal to missed rows(" << missed_rows_size
1496
0
                   << ") in rowid conversion, tablet_id: " << _tablet->tablet_id()
1497
0
                   << ", table_id:" << _tablet->table_id();
1498
0
                if (missed_rows_size == 0) {
1499
0
                    ss << ", debug info: ";
1500
0
                    DeleteBitmap subset_map(_tablet->tablet_id());
1501
0
                    for (auto rs : _input_rowsets) {
1502
0
                        _tablet->tablet_meta()->delete_bitmap().subset(
1503
0
                                {rs->rowset_id(), 0, 0},
1504
0
                                {rs->rowset_id(), rs->num_segments(), version.second + 1},
1505
0
                                &subset_map);
1506
0
                        ss << "(rowset id: " << rs->rowset_id()
1507
0
                           << ", delete bitmap cardinality: " << subset_map.cardinality() << ")";
1508
0
                    }
1509
0
                    ss << ", version[0-" << version.second + 1 << "]";
1510
0
                }
1511
0
                std::string err_msg = fmt::format(
1512
0
                        "cumulative compaction: the merged rows({}), filtered rows({})"
1513
0
                        " is not equal to missed rows({}) in rowid conversion,"
1514
0
                        " tablet_id: {}, table_id:{}",
1515
0
                        _stats.merged_rows, _stats.filtered_rows, missed_rows_size,
1516
0
                        _tablet->tablet_id(), _tablet->table_id());
1517
0
                LOG(WARNING) << err_msg;
1518
0
                if (config::enable_mow_compaction_correctness_check_core) {
1519
0
                    CHECK(false) << err_msg;
1520
0
                } else if (config::enable_mow_compaction_correctness_check_fail) {
1521
0
                    return Status::InternalError<false>(err_msg);
1522
0
                } else {
1523
0
                    DCHECK(false) << err_msg;
1524
0
                }
1525
0
            }
1526
3.43k
        }
1527
1528
3.42k
        if (location_map) {
1529
0
            RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1530
0
            location_map->clear();
1531
0
        }
1532
1533
3.42k
        {
1534
3.42k
            std::lock_guard<std::mutex> wrlock_(tablet()->get_rowset_update_lock());
1535
3.42k
            std::lock_guard wrlock(_tablet->get_header_lock());
1536
3.42k
            SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1537
1538
            // Here we will calculate all the rowsets delete bitmaps which are committed but not published to reduce the calculation pressure
1539
            // of publish phase.
1540
            // All rowsets which need to recalculate have been published so we don't need to acquire lock.
1541
            // Step1: collect this tablet's all committed rowsets' delete bitmaps
1542
3.42k
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1543
3.42k
            _engine.txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1544
3.42k
                    *tablet(), &commit_tablet_txn_info_vec);
1545
1546
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1547
3.42k
            for (auto& it : commit_tablet_txn_info_vec) {
1548
28
                if (!_check_if_includes_input_rowsets(it.rowset_ids)) {
1549
                    // When calculating the delete bitmap of all committed rowsets relative to the compaction,
1550
                    // there may be cases where the compacted rowsets are newer than the committed rowsets.
1551
                    // At this time, row number conversion cannot be performed, otherwise data will be missing.
1552
                    // Therefore, we need to check if every committed rowset has calculated delete bitmap for
1553
                    // all compaction input rowsets.
1554
0
                    continue;
1555
0
                }
1556
28
                DeleteBitmap txn_output_delete_bitmap(_tablet->tablet_id());
1557
28
                tablet()->calc_compaction_output_rowset_delete_bitmap(
1558
28
                        _input_rowsets, *_rowid_conversion, 0, UINT64_MAX, missed_rows.get(),
1559
28
                        location_map.get(), *it.delete_bitmap.get(), &txn_output_delete_bitmap);
1560
28
                if (config::enable_merge_on_write_correctness_check) {
1561
28
                    RowsetIdUnorderedSet rowsetids;
1562
28
                    rowsetids.insert(_output_rowset->rowset_id());
1563
28
                    _tablet->add_sentinel_mark_to_delete_bitmap(&txn_output_delete_bitmap,
1564
28
                                                                rowsetids);
1565
28
                }
1566
28
                it.delete_bitmap->merge(txn_output_delete_bitmap);
1567
                // Step3: write back updated delete bitmap and tablet info.
1568
28
                it.rowset_ids.insert(_output_rowset->rowset_id());
1569
28
                _engine.txn_manager()->set_txn_related_delete_bitmap(
1570
28
                        it.partition_id, it.transaction_id, _tablet->tablet_id(),
1571
28
                        tablet()->tablet_uid(), true, it.delete_bitmap, it.rowset_ids,
1572
28
                        it.partial_update_info);
1573
28
            }
1574
1575
            // Convert the delete bitmap of the input rowsets to output rowset for
1576
            // incremental data.
1577
3.42k
            tablet()->calc_compaction_output_rowset_delete_bitmap(
1578
3.42k
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1579
3.42k
                    missed_rows.get(), location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1580
3.42k
                    &output_rowset_delete_bitmap);
1581
1582
3.42k
            if (location_map) {
1583
0
                RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1584
0
            }
1585
1586
3.42k
            tablet()->merge_delete_bitmap(output_rowset_delete_bitmap);
1587
3.42k
            RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1588
3.42k
        }
1589
3.42k
    } else {
1590
1.20k
        std::lock_guard wrlock(_tablet->get_header_lock());
1591
1.20k
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1592
1.20k
        RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1593
1.20k
    }
1594
1595
4.63k
    if (config::tablet_rowset_stale_sweep_by_size &&
1596
4.63k
        _tablet->tablet_meta()->all_stale_rs_metas().size() >=
1597
0
                config::tablet_rowset_stale_sweep_threshold_size) {
1598
0
        tablet()->delete_expired_stale_rowset();
1599
0
    }
1600
1601
4.63k
    int64_t cur_max_version = 0;
1602
4.63k
    {
1603
4.63k
        std::shared_lock rlock(_tablet->get_header_lock());
1604
4.63k
        cur_max_version = _tablet->max_version_unlocked();
1605
4.63k
        tablet()->save_meta();
1606
4.63k
    }
1607
4.63k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1608
4.63k
        _tablet->enable_unique_key_merge_on_write()) {
1609
3.43k
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1610
3.43k
                tablet()->data_dir(), _tablet->tablet_id(), cur_max_version);
1611
3.43k
        if (!st.ok()) {
1612
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1613
0
        }
1614
3.43k
    }
1615
4.63k
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset",
1616
4.63k
                    { tablet()->delete_expired_stale_rowset(); });
1617
4.63k
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
1618
4.63k
    return Status::OK();
1619
4.63k
}
1620
1621
bool CompactionMixin::_check_if_includes_input_rowsets(
1622
28
        const RowsetIdUnorderedSet& commit_rowset_ids_set) const {
1623
28
    std::vector<RowsetId> commit_rowset_ids {};
1624
28
    commit_rowset_ids.insert(commit_rowset_ids.end(), commit_rowset_ids_set.begin(),
1625
28
                             commit_rowset_ids_set.end());
1626
28
    std::sort(commit_rowset_ids.begin(), commit_rowset_ids.end());
1627
28
    std::vector<RowsetId> input_rowset_ids {};
1628
262
    for (const auto& rowset : _input_rowsets) {
1629
262
        input_rowset_ids.emplace_back(rowset->rowset_meta()->rowset_id());
1630
262
    }
1631
28
    std::sort(input_rowset_ids.begin(), input_rowset_ids.end());
1632
28
    return std::includes(commit_rowset_ids.begin(), commit_rowset_ids.end(),
1633
28
                         input_rowset_ids.begin(), input_rowset_ids.end());
1634
28
}
1635
1636
4.11k
void CompactionMixin::update_compaction_level() {
1637
4.11k
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
1638
4.13k
    if (cumu_policy && (cumu_policy->name() == CUMULATIVE_TIME_SERIES_POLICY ||
1639
4.13k
                        cumu_policy->name() == CUMULATIVE_BINLOG_POLICY)) {
1640
2
        int64_t compaction_level =
1641
2
                cumu_policy->get_compaction_level(tablet(), _input_rowsets, _output_rowset);
1642
2
        _output_rowset->rowset_meta()->set_compaction_level(compaction_level);
1643
2
    }
1644
4.11k
}
1645
1646
11.1k
Status Compaction::check_correctness() {
1647
    // 1. check row number
1648
11.1k
    if (_input_row_num != _output_rowset->num_rows() + _stats.merged_rows + _stats.filtered_rows) {
1649
0
        return Status::Error<CHECK_LINES_ERROR>(
1650
0
                "row_num does not match between cumulative input and output! tablet={}, "
1651
0
                "input_row_num={}, merged_row_num={}, filtered_row_num={}, output_row_num={}",
1652
0
                _tablet->tablet_id(), _input_row_num, _stats.merged_rows, _stats.filtered_rows,
1653
0
                _output_rowset->num_rows());
1654
0
    }
1655
    // 2. check variant column path stats
1656
11.1k
    RETURN_IF_ERROR(variant_util::VariantCompactionUtil::check_path_stats(_input_rowsets,
1657
11.1k
                                                                          _output_rowset, _tablet));
1658
11.1k
    return Status::OK();
1659
11.1k
}
1660
1661
9.28k
int64_t CompactionMixin::get_compaction_permits() {
1662
9.28k
    int64_t permits = 0;
1663
9.28k
    const int64_t point = tablet()->cumulative_layer_point();
1664
83.9k
    for (auto&& rowset : _input_rowsets) {
1665
83.9k
        if (tablet()->is_row_binlog_tablet() && point != Tablet::K_INVALID_CUMULATIVE_POINT &&
1666
83.9k
            rowset->end_version() < point) {
1667
0
            ++permits;
1668
0
            continue;
1669
0
        }
1670
83.9k
        permits += rowset->rowset_meta()->get_compaction_score();
1671
83.9k
    }
1672
9.28k
    return permits;
1673
9.28k
}
1674
1675
2
int64_t CompactionMixin::calc_input_rowsets_total_size() const {
1676
2
    int64_t input_rowsets_total_size = 0;
1677
4
    for (const auto& rowset : _input_rowsets) {
1678
4
        const auto& rowset_meta = rowset->rowset_meta();
1679
4
        auto total_size = rowset_meta->total_disk_size();
1680
4
        input_rowsets_total_size += total_size;
1681
4
    }
1682
2
    return input_rowsets_total_size;
1683
2
}
1684
1685
2
int64_t CompactionMixin::calc_input_rowsets_row_num() const {
1686
2
    int64_t input_rowsets_row_num = 0;
1687
4
    for (const auto& rowset : _input_rowsets) {
1688
4
        const auto& rowset_meta = rowset->rowset_meta();
1689
4
        auto total_size = rowset_meta->total_disk_size();
1690
4
        input_rowsets_row_num += total_size;
1691
4
    }
1692
2
    return input_rowsets_row_num;
1693
2
}
1694
1695
11.6k
void Compaction::_load_segment_to_cache() {
1696
    // Load new rowset's segments to cache.
1697
11.6k
    SegmentCacheHandle handle;
1698
11.6k
    auto st = SegmentLoader::instance()->load_segments(
1699
11.6k
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1700
11.6k
    if (!st.ok()) {
1701
0
        LOG(WARNING) << "failed to load segment to cache! output rowset version="
1702
0
                     << _output_rowset->start_version() << "-" << _output_rowset->end_version()
1703
0
                     << ".";
1704
0
    }
1705
11.6k
}
1706
1707
7.04k
Status CloudCompactionMixin::build_basic_info() {
1708
7.04k
    _output_version =
1709
7.04k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
1710
1711
7.04k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
1712
1713
7.04k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
1714
7.04k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
1715
55.6k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
1716
7.04k
    if (is_index_change_compaction()) {
1717
834
        RETURN_IF_ERROR(rebuild_tablet_schema());
1718
6.21k
    } else {
1719
6.21k
        _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
1720
6.21k
    }
1721
1722
    // if enable_vertical_compact_variant_subcolumns is true, we need to compact the variant subcolumns in seperate column groups
1723
    // so get_extended_compaction_schema will extended the schema for variant columns
1724
7.04k
    if (_enable_vertical_compact_variant_subcolumns) {
1725
7.04k
        RETURN_IF_ERROR(variant_util::VariantCompactionUtil::get_extended_compaction_schema(
1726
7.04k
                _input_rowsets, _cur_tablet_schema));
1727
7.04k
    }
1728
7.04k
    return Status::OK();
1729
7.04k
}
1730
1731
7.03k
int64_t CloudCompactionMixin::get_compaction_permits() {
1732
7.03k
    int64_t permits = 0;
1733
55.7k
    for (auto&& rowset : _input_rowsets) {
1734
55.7k
        permits += rowset->rowset_meta()->get_compaction_score();
1735
55.7k
    }
1736
7.03k
    return permits;
1737
7.03k
}
1738
1739
CloudCompactionMixin::CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
1740
                                           const std::string& label)
1741
113k
        : Compaction(tablet, label), _engine(engine) {
1742
113k
    auto uuid = UUIDGenerator::instance()->next_uuid();
1743
113k
    std::stringstream ss;
1744
113k
    ss << uuid;
1745
113k
    _uuid = ss.str();
1746
113k
}
1747
1748
7.03k
Status CloudCompactionMixin::execute_compact_impl(int64_t permits) {
1749
7.03k
    OlapStopWatch watch;
1750
1751
7.03k
    RETURN_IF_ERROR(build_basic_info());
1752
1753
7.03k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
1754
7.03k
              << ", output_version=" << _output_version << ", permits: " << permits;
1755
1756
7.03k
    RETURN_IF_ERROR(merge_input_rowsets());
1757
1758
7.03k
    DBUG_EXECUTE_IF("CloudFullCompaction::modify_rowsets.wrong_rowset_id", {
1759
7.03k
        DCHECK(compaction_type() == ReaderType::READER_FULL_COMPACTION);
1760
7.03k
        RowsetId id;
1761
7.03k
        id.version = 2;
1762
7.03k
        id.hi = _output_rowset->rowset_meta()->rowset_id().hi + ((int64_t)(1) << 56);
1763
7.03k
        id.mi = _output_rowset->rowset_meta()->rowset_id().mi;
1764
7.03k
        id.lo = _output_rowset->rowset_meta()->rowset_id().lo;
1765
7.03k
        _output_rowset->rowset_meta()->set_rowset_id(id);
1766
7.03k
        LOG(INFO) << "[Debug wrong rowset id]:"
1767
7.03k
                  << _output_rowset->rowset_meta()->rowset_id().to_string();
1768
7.03k
    })
1769
1770
    // Currently, updates are only made in the time_series and binlog policies.
1771
7.03k
    update_compaction_level();
1772
1773
7.03k
    RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get(), _uuid,
1774
7.03k
                                                     _tablet->table_id()));
1775
1776
    // 4. modify rowsets in memory
1777
7.03k
    RETURN_IF_ERROR(modify_rowsets());
1778
1779
    // update compaction status data
1780
6.99k
    auto tablet = std::static_pointer_cast<CloudTablet>(_tablet);
1781
6.99k
    tablet->local_read_time_us.fetch_add(_stats.cloud_local_read_time);
1782
6.99k
    tablet->remote_read_time_us.fetch_add(_stats.cloud_remote_read_time);
1783
6.99k
    tablet->exec_compaction_time_us.fetch_add(watch.get_elapse_time_us());
1784
1785
6.99k
    return Status::OK();
1786
7.03k
}
1787
1788
6.92k
int64_t CloudCompactionMixin::initiator() const {
1789
6.92k
    return HashUtil::hash64(_uuid.data(), _uuid.size(), 0) & std::numeric_limits<int64_t>::max();
1790
6.92k
}
1791
1792
namespace cloud {
1793
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
1794
7.31k
                                    int64_t& truncated_size_bytes) {
1795
7.31k
    if (rowsets.empty()) {
1796
1
        kept_size_bytes = 0;
1797
1
        truncated_size_bytes = 0;
1798
1
        return 0;
1799
1
    }
1800
1801
7.30k
    int64_t max_size = config::compaction_txn_max_size_bytes;
1802
7.30k
    int64_t cumulative_meta_size = 0;
1803
7.30k
    size_t keep_count = 0;
1804
1805
65.5k
    for (size_t i = 0; i < rowsets.size(); ++i) {
1806
58.2k
        const auto& rs = rowsets[i];
1807
1808
        // Estimate rowset meta size using doris_rowset_meta_to_cloud
1809
58.2k
        auto cloud_meta = cloud::doris_rowset_meta_to_cloud(rs->rowset_meta()->get_rowset_pb(true));
1810
58.2k
        int64_t rowset_meta_size = cloud_meta.ByteSizeLong();
1811
1812
58.2k
        cumulative_meta_size += rowset_meta_size;
1813
1814
58.2k
        if (keep_count > 0 && cumulative_meta_size > max_size) {
1815
            // Rollback and stop
1816
4
            cumulative_meta_size -= rowset_meta_size;
1817
4
            break;
1818
4
        }
1819
1820
58.2k
        keep_count++;
1821
58.2k
    }
1822
1823
    // Ensure at least 1 rowset is kept
1824
7.30k
    if (keep_count == 0) {
1825
0
        keep_count = 1;
1826
        // Recalculate size for the first rowset
1827
0
        const auto& rs = rowsets[0];
1828
0
        auto cloud_meta = cloud::doris_rowset_meta_to_cloud(rs->rowset_meta()->get_rowset_pb());
1829
0
        cumulative_meta_size = cloud_meta.ByteSizeLong();
1830
0
    }
1831
1832
    // Calculate truncated size
1833
7.30k
    int64_t truncated_total_size = 0;
1834
7.30k
    size_t truncated_count = rowsets.size() - keep_count;
1835
7.30k
    if (truncated_count > 0) {
1836
35
        for (size_t i = keep_count; i < rowsets.size(); ++i) {
1837
31
            auto cloud_meta =
1838
31
                    cloud::doris_rowset_meta_to_cloud(rowsets[i]->rowset_meta()->get_rowset_pb());
1839
31
            truncated_total_size += cloud_meta.ByteSizeLong();
1840
31
        }
1841
4
        rowsets.resize(keep_count);
1842
4
    }
1843
1844
7.30k
    kept_size_bytes = cumulative_meta_size;
1845
7.30k
    truncated_size_bytes = truncated_total_size;
1846
7.30k
    return truncated_count;
1847
7.31k
}
1848
} // namespace cloud
1849
1850
6.45k
size_t CloudCompactionMixin::apply_txn_size_truncation_and_log(const std::string& compaction_name) {
1851
6.45k
    if (_input_rowsets.empty()) {
1852
1
        return 0;
1853
1
    }
1854
1855
6.44k
    int64_t original_count = _input_rowsets.size();
1856
6.44k
    int64_t original_start_version = _input_rowsets.front()->start_version();
1857
6.44k
    int64_t original_end_version = _input_rowsets.back()->end_version();
1858
1859
6.44k
    int64_t final_size = 0;
1860
6.44k
    int64_t truncated_size = 0;
1861
6.44k
    size_t truncated_count =
1862
6.44k
            cloud::truncate_rowsets_by_txn_size(_input_rowsets, final_size, truncated_size);
1863
1864
6.44k
    if (truncated_count > 0) {
1865
2
        int64_t original_size = final_size + truncated_size;
1866
2
        LOG(INFO) << compaction_name << " txn size estimation truncate"
1867
2
                  << ", tablet_id=" << _tablet->tablet_id() << ", original_version_range=["
1868
2
                  << original_start_version << "-" << original_end_version
1869
2
                  << "], final_version_range=[" << _input_rowsets.front()->start_version() << "-"
1870
2
                  << _input_rowsets.back()->end_version()
1871
2
                  << "], original_rowset_count=" << original_count
1872
2
                  << ", final_rowset_count=" << _input_rowsets.size()
1873
2
                  << ", truncated_rowset_count=" << truncated_count
1874
2
                  << ", original_size_bytes=" << original_size
1875
2
                  << ", final_size_bytes=" << final_size
1876
2
                  << ", truncated_size_bytes=" << truncated_size
1877
2
                  << ", threshold_bytes=" << config::compaction_txn_max_size_bytes;
1878
2
    }
1879
1880
6.44k
    return truncated_count;
1881
6.45k
}
1882
1883
7.01k
Status CloudCompactionMixin::execute_compact() {
1884
7.01k
    int64_t profile_start_time_ms = UnixMillis();
1885
7.01k
    TEST_INJECTION_POINT("Compaction::do_compaction");
1886
7.01k
    int64_t permits = get_compaction_permits();
1887
7.01k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
1888
7.01k
            execute_compact_impl(permits), [&](const doris::Exception& ex) {
1889
7.01k
                auto st = garbage_collection();
1890
7.01k
                if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1891
7.01k
                    _tablet->enable_unique_key_merge_on_write() && !st.ok()) {
1892
                    // if compaction fail, be will try to abort compaction, and delete bitmap lock
1893
                    // will release if abort job successfully, but if abort failed, delete bitmap
1894
                    // lock will not release, in this situation, be need to send this rpc to ms
1895
                    // to try to release delete bitmap lock.
1896
7.01k
                    _engine.meta_mgr().remove_delete_bitmap_update_lock(
1897
7.01k
                            _tablet->table_id(), COMPACTION_DELETE_BITMAP_LOCK_ID, initiator(),
1898
7.01k
                            _tablet->tablet_id());
1899
7.01k
                }
1900
7.01k
                submit_profile_record(false, profile_start_time_ms, ex.what());
1901
7.01k
            });
1902
1903
7.01k
    DorisMetrics::instance()->remote_compaction_read_rows_total->increment(_input_row_num);
1904
7.01k
    DorisMetrics::instance()->remote_compaction_write_rows_total->increment(
1905
7.01k
            _output_rowset->num_rows());
1906
7.01k
    DorisMetrics::instance()->remote_compaction_write_bytes_total->increment(
1907
7.01k
            _output_rowset->total_disk_size());
1908
1909
7.01k
    _load_segment_to_cache();
1910
7.01k
    submit_profile_record(true, profile_start_time_ms);
1911
7.01k
    return Status::OK();
1912
7.01k
}
1913
1914
0
Status CloudCompactionMixin::modify_rowsets() {
1915
0
    return Status::OK();
1916
0
}
1917
1918
7.06k
Status CloudCompactionMixin::set_storage_resource_from_input_rowsets(RowsetWriterContext& ctx) {
1919
    // Set storage resource from input rowsets by iterating backwards to find the first rowset
1920
    // with non-empty resource_id. This handles two scenarios:
1921
    // 1. Hole rowsets compaction: Multiple hole rowsets may lack storage resource.
1922
    //    Example: [0-1, 2-2, 3-3, 4-4, 5-5] where 2-5 are hole rowsets.
1923
    //    If 0-1 lacks resource_id, then 2-5 also lack resource_id.
1924
    // 2. Schema change: New tablet may have later version empty rowsets without resource_id,
1925
    //    but middle rowsets get resource_id after historical rowsets are converted.
1926
    //    We iterate backwards to find the most recent rowset with valid resource_id.
1927
1928
13.2k
    for (const auto& rowset : std::ranges::reverse_view(_input_rowsets)) {
1929
13.2k
        const auto& resource_id = rowset->rowset_meta()->resource_id();
1930
1931
13.2k
        if (!resource_id.empty()) {
1932
5.96k
            ctx.storage_resource = *DORIS_TRY(rowset->rowset_meta()->remote_storage_resource());
1933
5.96k
            return Status::OK();
1934
5.96k
        }
1935
1936
        // Validate that non-empty rowsets (num_segments > 0) must have valid resource_id
1937
        // Only hole rowsets or empty rowsets are allowed to have empty resource_id
1938
7.26k
        if (rowset->num_segments() > 0) {
1939
0
            auto error_msg = fmt::format(
1940
0
                    "Non-empty rowset must have valid resource_id. "
1941
0
                    "rowset_id={}, version=[{}-{}], is_hole_rowset={}, num_segments={}, "
1942
0
                    "tablet_id={}, table_id={}",
1943
0
                    rowset->rowset_id().to_string(), rowset->start_version(), rowset->end_version(),
1944
0
                    rowset->is_hole_rowset(), rowset->num_segments(), _tablet->tablet_id(),
1945
0
                    _tablet->table_id());
1946
1947
0
#ifndef BE_TEST
1948
0
            DCHECK(false) << error_msg;
1949
0
#endif
1950
1951
0
            return Status::InternalError<false>(error_msg);
1952
0
        }
1953
7.26k
    }
1954
1955
1.10k
    return Status::OK();
1956
7.06k
}
1957
1958
7.06k
Status CloudCompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1959
    // only do index compaction for dup_keys and unique_keys with mow enabled
1960
7.06k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1961
6.21k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1962
6.21k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1963
5.41k
        construct_index_compaction_columns(ctx);
1964
5.41k
    }
1965
1966
    // Use the storage resource of the previous rowset.
1967
7.06k
    RETURN_IF_ERROR(set_storage_resource_from_input_rowsets(ctx));
1968
1969
7.06k
    ctx.txn_id = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
1970
7.06k
                 std::numeric_limits<int64_t>::max(); // MUST be positive
1971
7.06k
    ctx.txn_expiration = _expiration;
1972
1973
7.06k
    ctx.version = _output_version;
1974
7.06k
    ctx.rowset_state = VISIBLE;
1975
7.06k
    ctx.segments_overlap = NONOVERLAPPING;
1976
7.06k
    ctx.tablet_schema = _cur_tablet_schema;
1977
7.06k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1978
7.06k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1979
7.06k
    ctx.compaction_type = compaction_type();
1980
7.06k
    ctx.allow_packed_file = false;
1981
7.06k
    if (_tablet->is_row_binlog_tablet()) {
1982
0
        ctx.write_binlog_opt().enable = true;
1983
0
    }
1984
1985
    // We presume that the data involved in cumulative compaction is sufficiently 'hot'
1986
    // and should always be retained in the cache.
1987
    // TODO(gavin): Ensure that the retention of hot data is implemented with precision.
1988
1989
7.06k
    ctx.write_file_cache = should_cache_compaction_output();
1990
7.06k
    ctx.file_cache_ttl_sec = _tablet->ttl_seconds();
1991
7.06k
    ctx.approximate_bytes_to_write = _input_rowsets_total_size;
1992
1993
    // Set fine-grained control: only write index files to cache if configured
1994
7.06k
    ctx.compaction_output_write_index_only = should_enable_compaction_cache_index_only(
1995
7.06k
            ctx.write_file_cache, compaction_type(),
1996
7.06k
            config::enable_file_cache_write_base_compaction_index_only,
1997
7.06k
            config::enable_file_cache_write_cumu_compaction_index_only);
1998
1999
7.06k
    ctx.tablet = _tablet;
2000
7.06k
    ctx.job_id = _uuid;
2001
2002
7.06k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
2003
7.06k
    RETURN_IF_ERROR(_engine.meta_mgr().prepare_rowset(*_output_rs_writer->rowset_meta().get(),
2004
7.06k
                                                      _uuid, _tablet->table_id()));
2005
7.06k
    return Status::OK();
2006
7.06k
}
2007
2008
40
Status CloudCompactionMixin::garbage_collection() {
2009
40
    if (!config::enable_file_cache) {
2010
0
        return Status::OK();
2011
0
    }
2012
40
    if (_output_rs_writer) {
2013
40
        auto* beta_rowset_writer = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get());
2014
40
        DCHECK(beta_rowset_writer);
2015
40
        for (const auto& [_, file_writer] : beta_rowset_writer->get_file_writers()) {
2016
38
            auto file_key = io::BlockFileCache::hash(file_writer->path().filename().native());
2017
38
            auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
2018
38
            file_cache->remove_if_cached_async(file_key);
2019
38
        }
2020
40
        for (const auto& [_, index_writer] : beta_rowset_writer->index_file_writers()) {
2021
0
            for (const auto& file_name : index_writer->get_index_file_names()) {
2022
0
                auto file_key = io::BlockFileCache::hash(file_name);
2023
0
                auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
2024
0
                file_cache->remove_if_cached_async(file_key);
2025
0
            }
2026
0
        }
2027
40
    }
2028
40
    return Status::OK();
2029
40
}
2030
2031
7.04k
void CloudCompactionMixin::update_compaction_level() {
2032
    // for index change compaction, compaction level should not changed.
2033
    // because input rowset num is 1.
2034
7.04k
    if (is_index_change_compaction()) {
2035
843
        DCHECK(_input_rowsets.size() == 1);
2036
843
        _output_rowset->rowset_meta()->set_compaction_level(
2037
843
                _input_rowsets.back()->rowset_meta()->compaction_level());
2038
6.20k
    } else {
2039
6.20k
        auto compaction_policy = _tablet->tablet_meta()->compaction_policy();
2040
6.20k
        auto cumu_policy = _engine.cumu_compaction_policy(compaction_policy);
2041
6.22k
        if (cumu_policy && (cumu_policy->name() == CUMULATIVE_TIME_SERIES_POLICY ||
2042
6.22k
                            cumu_policy->name() == CUMULATIVE_BINLOG_POLICY)) {
2043
4
            int64_t compaction_level = cumu_policy->get_compaction_level(
2044
4
                    cloud_tablet(), _input_rowsets, _output_rowset);
2045
4
            _output_rowset->rowset_meta()->set_compaction_level(compaction_level);
2046
4
        }
2047
6.20k
    }
2048
7.04k
}
2049
2050
// should skip hole rowsets, ortherwise the count will be wrong in ms
2051
7.04k
int64_t CloudCompactionMixin::num_input_rowsets() const {
2052
7.04k
    int64_t count = 0;
2053
56.2k
    for (const auto& r : _input_rowsets) {
2054
56.2k
        if (!r->is_hole_rowset()) {
2055
27.4k
            count++;
2056
27.4k
        }
2057
56.2k
    }
2058
7.04k
    return count;
2059
7.04k
}
2060
2061
7.08k
bool CloudCompactionMixin::should_cache_compaction_output() {
2062
7.08k
    if (config::enable_file_cache_write_index_file_only) {
2063
1
        return false;
2064
1
    }
2065
2066
7.08k
    if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
2067
6.92k
        return true;
2068
6.92k
    }
2069
2070
158
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
2071
63
        double input_rowsets_hit_cache_ratio = 0.0;
2072
2073
63
        int64_t _input_rowsets_cached_size =
2074
63
                _input_rowsets_cached_data_size + _input_rowsets_cached_index_size;
2075
63
        if (_input_rowsets_total_size > 0) {
2076
62
            input_rowsets_hit_cache_ratio =
2077
62
                    double(_input_rowsets_cached_size) / double(_input_rowsets_total_size);
2078
62
        }
2079
2080
63
        LOG(INFO) << "CloudBaseCompaction should_cache_compaction_output"
2081
63
                  << ", tablet_id=" << _tablet->tablet_id()
2082
63
                  << ", input_rowsets_hit_cache_ratio=" << input_rowsets_hit_cache_ratio
2083
63
                  << ", _input_rowsets_cached_size=" << _input_rowsets_cached_size
2084
63
                  << ", _input_rowsets_total_size=" << _input_rowsets_total_size
2085
63
                  << ", enable_file_cache_keep_base_compaction_output="
2086
63
                  << config::enable_file_cache_keep_base_compaction_output
2087
63
                  << ", file_cache_keep_base_compaction_output_min_hit_ratio="
2088
63
                  << config::file_cache_keep_base_compaction_output_min_hit_ratio;
2089
2090
63
        if (config::enable_file_cache_keep_base_compaction_output) {
2091
1
            return true;
2092
1
        }
2093
2094
62
        if (input_rowsets_hit_cache_ratio >
2095
62
            config::file_cache_keep_base_compaction_output_min_hit_ratio) {
2096
29
            return true;
2097
29
        }
2098
62
    }
2099
128
    return false;
2100
158
}
2101
2102
} // namespace doris