Coverage Report

Created: 2026-06-25 16:02

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