Coverage Report

Created: 2026-04-10 05:33

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