Coverage Report

Created: 2026-07-03 17:03

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