Coverage Report

Created: 2026-07-02 12:30

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.60k
                                               bool enable_cumu_index_only) {
105
7.60k
    if (!write_file_cache) {
106
124
        return false;
107
124
    }
108
109
7.48k
    if (compaction_type == ReaderType::READER_BASE_COMPACTION && enable_base_index_only) {
110
2
        return true;
111
2
    }
112
113
7.47k
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION && enable_cumu_index_only) {
114
2
        return true;
115
2
    }
116
117
7.47k
    return false;
118
7.47k
}
119
120
namespace {
121
122
bool is_rowset_tidy(std::string& pre_max_key, bool& pre_rs_key_bounds_truncated,
123
2.16k
                    const RowsetSharedPtr& rhs) {
124
2.16k
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
125
2.16k
    if (rhs->num_segments() == 0) {
126
1.72k
        return true;
127
1.72k
    }
128
436
    if (rhs->is_segments_overlapping()) {
129
0
        return false;
130
0
    }
131
    // check segment size
132
436
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
133
436
    std::vector<size_t> segments_size;
134
436
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
135
445
    for (auto segment_size : segments_size) {
136
        // is segment is too small, need to do compaction
137
445
        if (segment_size < min_tidy_size) {
138
348
            return false;
139
348
        }
140
445
    }
141
87
    std::string min_key;
142
87
    auto ret = rhs->first_key(&min_key);
143
87
    if (!ret) {
144
0
        return false;
145
0
    }
146
87
    bool cur_rs_key_bounds_truncated {rhs->is_segments_key_bounds_truncated()};
147
87
    if (!Slice::lhs_is_strictly_less_than_rhs(Slice {pre_max_key}, pre_rs_key_bounds_truncated,
148
87
                                              Slice {min_key}, cur_rs_key_bounds_truncated)) {
149
23
        return false;
150
23
    }
151
87
    CHECK(rhs->last_key(&pre_max_key));
152
64
    pre_rs_key_bounds_truncated = cur_rs_key_bounds_truncated;
153
64
    return true;
154
87
}
155
156
9.60k
TsoRange commit_tso_range(const std::vector<RowsetSharedPtr>& rowsets) {
157
9.60k
    DCHECK(!rowsets.empty());
158
9.60k
    auto range = rowsets.front()->commit_tso();
159
77.2k
    for (const auto& rowset : rowsets) {
160
77.2k
        const auto commit_tso = rowset->commit_tso();
161
77.2k
        range.first = std::min(range.first, commit_tso.start_tso());
162
77.2k
        range.second = std::max(range.second, commit_tso.end_tso());
163
77.2k
    }
164
9.60k
    return range;
165
9.60k
}
166
167
} // namespace
168
169
Compaction::Compaction(BaseTabletSPtr tablet, const std::string& label)
170
295k
        : _compaction_id(CompactionTaskTracker::instance()->next_compaction_id()),
171
          _mem_tracker(
172
295k
                  MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label)),
173
295k
          _tablet(std::move(tablet)),
174
295k
          _is_vertical(config::enable_vertical_compaction),
175
295k
          _allow_delete_in_cumu_compaction(config::enable_delete_when_cumu_compaction),
176
          _enable_vertical_compact_variant_subcolumns(
177
295k
                  config::enable_vertical_compact_variant_subcolumns),
178
295k
          _enable_inverted_index_compaction(config::inverted_index_compaction_enable) {
179
295k
    init_profile(label);
180
295k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
181
295k
    _rowid_conversion = std::make_unique<RowIdConversion>();
182
295k
}
183
184
295k
Compaction::~Compaction() {
185
295k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
186
295k
    _output_rs_writer.reset();
187
295k
    _tablet.reset();
188
295k
    _input_rowsets.clear();
189
295k
    _output_rowset.reset();
190
295k
    _cur_tablet_schema.reset();
191
295k
    _rowid_conversion.reset();
192
295k
}
193
194
17.9k
std::string Compaction::input_version_range_str() const {
195
17.9k
    if (_input_rowsets.empty()) return "";
196
17.9k
    return fmt::format("[{}-{}]", _input_rowsets.front()->start_version(),
197
17.9k
                       _input_rowsets.back()->end_version());
198
17.9k
}
199
200
void Compaction::submit_profile_record(bool success, int64_t start_time_ms,
201
9.56k
                                       const std::string& status_msg) {
202
9.56k
    if (!profile_type().has_value()) {
203
807
        return;
204
807
    }
205
8.75k
    auto* tracker = CompactionTaskTracker::instance();
206
8.75k
    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
8.75k
    stats.input_version_range = input_version_range_str();
210
8.75k
    stats.input_rowsets_count = static_cast<int64_t>(_input_rowsets.size());
211
8.75k
    stats.input_row_num = _input_row_num;
212
8.75k
    stats.input_data_size = _input_rowsets_data_size;
213
8.75k
    stats.input_index_size = _input_rowsets_index_size;
214
8.75k
    stats.input_total_size = _input_rowsets_total_size;
215
8.75k
    stats.input_segments_num = input_segments_num_value();
216
8.75k
    stats.end_time_ms = UnixMillis();
217
8.75k
    stats.merged_rows = _stats.merged_rows;
218
8.75k
    stats.filtered_rows = _stats.filtered_rows;
219
8.75k
    stats.output_rows = _stats.output_rows;
220
8.77k
    if (_output_rowset) {
221
8.77k
        stats.output_row_num = _output_rowset->num_rows();
222
8.77k
        stats.output_data_size = _output_rowset->data_disk_size();
223
8.77k
        stats.output_index_size = _output_rowset->index_disk_size();
224
8.77k
        stats.output_total_size = _output_rowset->total_disk_size();
225
8.77k
        stats.output_segments_num = _output_rowset->num_segments();
226
8.77k
    }
227
8.75k
    stats.output_version = _output_version.to_string();
228
8.75k
    stats.is_ordered_data_compaction = _is_ordered_data_compaction;
229
8.79k
    if (_merge_rowsets_latency_timer) {
230
8.79k
        stats.merge_latency_ms = _merge_rowsets_latency_timer->value() / 1000000;
231
8.79k
    }
232
8.75k
    stats.bytes_read_from_local = _stats.bytes_read_from_local;
233
8.75k
    stats.bytes_read_from_remote = _stats.bytes_read_from_remote;
234
8.76k
    if (_mem_tracker) {
235
8.76k
        stats.peak_memory_bytes = _mem_tracker->peak_consumption();
236
8.76k
    }
237
8.75k
    if (success) {
238
8.72k
        tracker->complete(_compaction_id, stats);
239
8.72k
    } else {
240
30
        tracker->fail(_compaction_id, stats, status_msg);
241
30
    }
242
8.75k
}
243
244
295k
void Compaction::init_profile(const std::string& label) {
245
295k
    _profile = std::make_unique<RuntimeProfile>(label);
246
247
295k
    _input_rowsets_data_size_counter =
248
295k
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
249
295k
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
250
295k
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
251
295k
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
252
295k
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
253
295k
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
254
295k
    _output_rowset_data_size_counter =
255
295k
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
256
295k
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
257
295k
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
258
295k
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
259
295k
}
260
261
9.30k
int64_t Compaction::merge_way_num() {
262
9.30k
    int64_t way_num = 0;
263
75.2k
    for (auto&& rowset : _input_rowsets) {
264
75.2k
        way_num += rowset->rowset_meta()->get_merge_way_num();
265
75.2k
    }
266
267
9.30k
    return way_num;
268
9.30k
}
269
270
9.37k
Status Compaction::merge_input_rowsets() {
271
9.37k
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
272
9.37k
    input_rs_readers.reserve(_input_rowsets.size());
273
75.7k
    for (auto& rowset : _input_rowsets) {
274
75.7k
        RowsetReaderSharedPtr rs_reader;
275
75.7k
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
276
75.7k
        input_rs_readers.push_back(std::move(rs_reader));
277
75.7k
    }
278
279
9.37k
    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
9.37k
    ctx.input_rs_readers = input_rs_readers;
283
9.37k
    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
9.37k
    if (!ctx.columns_to_do_index_compaction.empty() ||
290
9.37k
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
291
8.87k
         _tablet->enable_unique_key_merge_on_write())) {
292
5.15k
        _stats.rowid_conversion = _rowid_conversion.get();
293
5.15k
    }
294
295
9.37k
    int64_t way_num = merge_way_num();
296
297
9.37k
    Status res;
298
9.37k
    {
299
9.37k
        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
9.37k
        if (_is_vertical && !_tablet->tablet_schema()->has_seq_map()) {
303
9.35k
            if (!_tablet->tablet_schema()->cluster_key_uids().empty()) {
304
157
                RETURN_IF_ERROR(update_delete_bitmap());
305
157
            }
306
9.35k
            auto progress_cb = [compaction_id = this->_compaction_id](int64_t total,
307
34.4k
                                                                      int64_t completed) {
308
34.4k
                CompactionTaskTracker::instance()->update_progress(compaction_id, total, completed);
309
34.4k
            };
310
9.35k
            res = Merger::vertical_merge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
311
9.35k
                                                 input_rs_readers, _output_rs_writer.get(),
312
9.35k
                                                 cast_set<uint32_t>(get_avg_segment_rows()),
313
9.35k
                                                 way_num, &_stats, progress_cb);
314
9.35k
        } else {
315
21
            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
21
            res = Merger::vmerge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
320
21
                                         input_rs_readers, _output_rs_writer.get(), &_stats);
321
21
        }
322
323
9.37k
        _tablet->last_compaction_status = res;
324
9.37k
        if (!res.ok()) {
325
0
            return res;
326
0
        }
327
        // 2. Merge the remaining inverted index files of the string type
328
9.37k
        RETURN_IF_ERROR(do_inverted_index_compaction());
329
9.37k
    }
330
331
9.37k
    COUNTER_UPDATE(_merged_rows_counter, _stats.merged_rows);
332
9.37k
    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
9.37k
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
336
9.37k
                                   fmt::format("rowset writer build failed. output_version: {}",
337
9.37k
                                               _output_version.to_string()));
338
9.37k
    _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
9.37k
    if (_enable_vertical_compact_variant_subcolumns &&
345
9.37k
        (_cur_tablet_schema->num_variant_columns() > 0)) {
346
529
        _output_rowset->rowset_meta()->set_tablet_schema(
347
529
                _cur_tablet_schema->copy_without_variant_extracted_columns());
348
529
    }
349
350
    //RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get()));
351
9.37k
    set_delete_predicate_for_output_rowset();
352
353
9.37k
    _local_read_bytes_total = _stats.bytes_read_from_local;
354
9.37k
    _remote_read_bytes_total = _stats.bytes_read_from_remote;
355
9.37k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(_local_read_bytes_total);
356
9.37k
    DorisMetrics::instance()->remote_compaction_read_bytes_total->increment(
357
9.37k
            _remote_read_bytes_total);
358
9.37k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
359
9.37k
            _stats.cached_bytes_total);
360
361
9.37k
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
362
9.37k
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
363
9.37k
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
364
365
9.37k
    return check_correctness();
366
9.37k
}
367
368
9.33k
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
9.33k
    if (_output_rowset->version().first > 2 &&
374
9.33k
        (_allow_delete_in_cumu_compaction || is_index_change_compaction())) {
375
461
        DeletePredicatePB delete_predicate;
376
461
        std::accumulate(_input_rowsets.begin(), _input_rowsets.end(), &delete_predicate,
377
461
                        [](DeletePredicatePB* delete_predicate, const RowsetSharedPtr& rs) {
378
459
                            if (rs->rowset_meta()->has_delete_predicate()) {
379
3
                                delete_predicate->MergeFrom(rs->rowset_meta()->delete_predicate());
380
3
                            }
381
459
                            return delete_predicate;
382
459
                        });
383
        // now version in delete_predicate is deprecated
384
461
        if (!delete_predicate.in_predicates().empty() ||
385
461
            !delete_predicate.sub_predicates_v2().empty() ||
386
461
            !delete_predicate.sub_predicates().empty()) {
387
3
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
388
3
        }
389
461
    }
390
9.33k
}
391
392
9.29k
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
9.29k
    const auto& meta = _tablet->tablet_meta();
398
9.29k
    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
9.29k
    return std::min(config::vertical_compaction_max_segment_size /
406
9.29k
                            (_input_rowsets_data_size / (_input_row_num + 1) + 1),
407
9.29k
                    _input_row_num + 1);
408
9.29k
}
409
410
CompactionMixin::CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet,
411
                                 const std::string& label)
412
163k
        : Compaction(tablet, label), _engine(engine) {}
413
414
163k
CompactionMixin::~CompactionMixin() {
415
163k
    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
163k
}
425
426
1.50M
Tablet* CompactionMixin::tablet() {
427
1.50M
    return static_cast<Tablet*>(_tablet.get());
428
1.50M
}
429
430
258
Status CompactionMixin::do_compact_ordered_rowsets() {
431
258
    RETURN_IF_ERROR(build_basic_info(true));
432
258
    RowsetWriterContext ctx;
433
258
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
434
258
    const auto& output_rowset_dir = compaction_type() == ReaderType::READER_BINLOG_COMPACTION
435
258
                                            ? tablet()->row_binlog_path()
436
258
                                            : tablet()->tablet_path();
437
438
258
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
439
258
              << ", output_version=" << _output_version;
440
    // link data to new rowset
441
258
    auto seg_id = 0;
442
258
    bool segments_key_bounds_truncated {false};
443
258
    bool any_input_aggregated {false};
444
258
    std::vector<KeyBoundsPB> segment_key_bounds;
445
258
    std::vector<uint32_t> num_segment_rows;
446
1.60k
    for (auto rowset : _input_rowsets) {
447
1.60k
        RETURN_IF_ERROR(
448
1.60k
                rowset->link_files_to(output_rowset_dir, _output_rs_writer->rowset_id(), seg_id));
449
1.60k
        seg_id += rowset->num_segments();
450
1.60k
        segments_key_bounds_truncated |= rowset->is_segments_key_bounds_truncated();
451
1.60k
        any_input_aggregated |= rowset->rowset_meta()->is_segments_key_bounds_aggregated();
452
1.60k
        std::vector<KeyBoundsPB> key_bounds;
453
1.60k
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
454
1.60k
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
455
1.60k
        std::vector<uint32_t> input_segment_rows;
456
1.60k
        rowset->get_num_segment_rows(&input_segment_rows);
457
1.60k
        num_segment_rows.insert(num_segment_rows.end(), input_segment_rows.begin(),
458
1.60k
                                input_segment_rows.end());
459
1.60k
    }
460
    // build output rowset
461
258
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
462
258
    rowset_meta->set_num_rows(_input_row_num);
463
258
    rowset_meta->set_total_disk_size(_input_rowsets_data_size + _input_rowsets_index_size);
464
258
    rowset_meta->set_data_disk_size(_input_rowsets_data_size);
465
258
    rowset_meta->set_index_disk_size(_input_rowsets_index_size);
466
258
    rowset_meta->set_empty(_input_row_num == 0);
467
258
    rowset_meta->set_num_segments(_input_num_segments);
468
258
    rowset_meta->set_segments_overlap(NONOVERLAPPING);
469
258
    rowset_meta->set_rowset_state(VISIBLE);
470
258
    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
258
    bool aggregate_key_bounds =
475
258
            any_input_aggregated || (config::enable_aggregate_non_mow_key_bounds &&
476
246
                                     !_tablet->enable_unique_key_merge_on_write());
477
258
    rowset_meta->set_segments_key_bounds(segment_key_bounds, aggregate_key_bounds);
478
258
    rowset_meta->set_num_segment_rows(num_segment_rows);
479
258
    rowset_meta->set_commit_tso(commit_tso_range(_input_rowsets));
480
481
258
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
482
483
    // 2. check variant column path stats
484
258
    RETURN_IF_ERROR(variant_util::VariantCompactionUtil::check_path_stats(_input_rowsets,
485
258
                                                                          _output_rowset, _tablet));
486
258
    return Status::OK();
487
258
}
488
489
1.99k
Status CompactionMixin::build_basic_info(bool is_ordered_compaction) {
490
18.0k
    for (auto& rowset : _input_rowsets) {
491
18.0k
        const auto& rowset_meta = rowset->rowset_meta();
492
18.0k
        auto index_size = rowset_meta->index_disk_size();
493
18.0k
        auto total_size = rowset_meta->total_disk_size();
494
18.0k
        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
18.0k
        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
18.0k
        _input_rowsets_data_size += data_size;
508
18.0k
        _input_rowsets_index_size += index_size;
509
18.0k
        _input_rowsets_total_size += total_size;
510
18.0k
        _input_row_num += rowset->num_rows();
511
18.0k
        _input_num_segments += rowset->num_segments();
512
18.0k
    }
513
1.99k
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_data_size);
514
1.99k
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
515
1.99k
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
516
517
1.99k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::build_basic_info",
518
1.99k
                                      Status::OK());
519
520
1.99k
    _output_version =
521
1.99k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
522
523
1.99k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
524
525
1.99k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
526
1.99k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
527
18.2k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
528
1.99k
    _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
2.00k
    if (_enable_vertical_compact_variant_subcolumns && !is_ordered_compaction) {
534
1.76k
        RETURN_IF_ERROR(variant_util::VariantCompactionUtil::get_extended_compaction_schema(
535
1.76k
                _input_rowsets, _cur_tablet_schema));
536
1.76k
    }
537
1.99k
    return Status::OK();
538
1.99k
}
539
540
2.04k
bool CompactionMixin::handle_ordered_data_compaction() {
541
2.04k
    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
2.04k
    std::vector<int32_t> schema_versions_of_rowsets;
552
553
18.2k
    for (auto input_rowset : _input_rowsets) {
554
18.2k
        schema_versions_of_rowsets.push_back(input_rowset->rowset_meta()->schema_version());
555
18.2k
    }
556
557
    // If all rowsets has same schema version, then we can do link file compaction directly.
558
2.04k
    bool all_same_schema_version =
559
2.04k
            std::all_of(schema_versions_of_rowsets.begin(), schema_versions_of_rowsets.end(),
560
18.3k
                        [&](int32_t v) { return v == schema_versions_of_rowsets.front(); });
561
562
2.04k
    if (!all_same_schema_version) {
563
0
        return false;
564
0
    }
565
566
2.04k
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
567
2.04k
        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
2.04k
    bool is_binlog_compaction = compaction_type() == ReaderType::READER_BINLOG_COMPACTION;
572
2.04k
    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
2.04k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
584
2.04k
        _tablet->enable_unique_key_merge_on_write() && !is_binlog_compaction) {
585
1.44k
        return false;
586
1.44k
    }
587
588
602
    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
602
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION ||
596
602
        (_allow_delete_in_cumu_compaction &&
597
600
         compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION)) {
598
3
        for (auto& rowset : _input_rowsets) {
599
3
            if (rowset->rowset_meta()->has_delete_predicate()) {
600
1
                return false;
601
1
            }
602
3
        }
603
1
    }
604
605
601
    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
601
    } else {
624
        // Check if rowsets are tidy so we can just modify meta and do link files to handle
625
        // ordered data compaction.
626
601
        auto input_size = _input_rowsets.size();
627
601
        std::string pre_max_key;
628
601
        bool pre_rs_key_bounds_truncated {false};
629
2.38k
        for (auto i = 0; i < input_size; ++i) {
630
2.16k
            if (!is_rowset_tidy(pre_max_key, pre_rs_key_bounds_truncated, _input_rowsets[i])) {
631
373
                if (i <= input_size / 2) {
632
343
                    return false;
633
343
                } else {
634
30
                    _input_rowsets.resize(i);
635
30
                    break;
636
30
                }
637
373
            }
638
2.16k
        }
639
601
    }
640
641
    // most rowset of current compaction is nonoverlapping
642
    // just handle nonoverlappint rowsets
643
258
    auto st = do_compact_ordered_rowsets();
644
258
    if (!st.ok()) {
645
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
646
0
        _pending_rs_guard.drop();
647
0
    }
648
649
258
    return st.ok();
650
601
}
651
652
2.00k
Status CompactionMixin::execute_compact() {
653
2.00k
    int64_t profile_start_time_ms = UnixMillis();
654
2.00k
    uint32_t checksum_before;
655
2.00k
    uint32_t checksum_after;
656
2.00k
    bool enable_compaction_checksum = config::enable_compaction_checksum;
657
2.00k
    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
2.00k
    auto* data_dir = tablet()->data_dir();
668
2.00k
    int64_t permits = get_compaction_permits();
669
2.00k
    data_dir->disks_compaction_score_increment(permits);
670
2.00k
    data_dir->disks_compaction_num_increment(1);
671
672
2.00k
    auto record_compaction_stats = [&](const doris::Exception& ex) {
673
2.00k
        _tablet->compaction_count.fetch_add(1, std::memory_order_relaxed);
674
2.00k
        data_dir->disks_compaction_score_increment(-permits);
675
2.00k
        data_dir->disks_compaction_num_increment(-1);
676
2.00k
    };
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
2.00k
    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
2.00k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(execute_compact_impl(permits), on_compact_impl_failure);
686
    // Only reached on success (macro returns on failure).
687
2.00k
    record_compaction_stats(doris::Exception());
688
689
2.00k
    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
2.00k
    DorisMetrics::instance()->local_compaction_read_rows_total->increment(_input_row_num);
707
2.00k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(
708
2.00k
            _input_rowsets_total_size);
709
710
2.00k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact", Status::OK());
711
712
2.00k
    DorisMetrics::instance()->local_compaction_write_rows_total->increment(
713
2.00k
            _output_rowset->num_rows());
714
2.00k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
715
2.00k
            _output_rowset->total_disk_size());
716
717
2.00k
    _load_segment_to_cache();
718
2.00k
    submit_profile_record(true, profile_start_time_ms);
719
2.00k
    return Status::OK();
720
2.00k
}
721
722
2.00k
Status CompactionMixin::execute_compact_impl(int64_t permits) {
723
2.00k
    OlapStopWatch watch;
724
725
2.00k
    if (handle_ordered_data_compaction()) {
726
242
        _is_ordered_data_compaction = true;
727
242
        RETURN_IF_ERROR(modify_rowsets());
728
242
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
729
242
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
730
242
                  << ", disk=" << tablet()->data_dir()->path()
731
242
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
732
242
                  << ", output_row_num=" << _output_rowset->num_rows()
733
242
                  << ", input_rowsets_data_size=" << _input_rowsets_data_size
734
242
                  << ", input_rowsets_index_size=" << _input_rowsets_index_size
735
242
                  << ", input_rowsets_total_size=" << _input_rowsets_total_size
736
242
                  << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
737
242
                  << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
738
242
                  << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
739
242
                  << ". elapsed time=" << watch.get_elapse_second() << "s.";
740
242
        _state = CompactionState::SUCCESS;
741
242
        return Status::OK();
742
242
    }
743
1.76k
    RETURN_IF_ERROR(build_basic_info());
744
745
1.76k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact_impl",
746
1.76k
                                      Status::OK());
747
748
1.76k
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
749
750
1.76k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
751
1.76k
              << ", output_version=" << _output_version << ", permits: " << permits;
752
753
1.76k
    RETURN_IF_ERROR(merge_input_rowsets());
754
755
    // Currently, updates are only made in the time_series.
756
1.76k
    update_compaction_level();
757
758
1.76k
    RETURN_IF_ERROR(modify_rowsets());
759
760
1.76k
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
761
1.76k
    DCHECK(cumu_policy);
762
1.76k
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << _is_vertical
763
1.76k
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
764
1.76k
              << ", current_max_version=" << tablet()->max_version().second
765
1.76k
              << ", disk=" << tablet()->data_dir()->path()
766
1.76k
              << ", input_segments=" << _input_num_segments << ", input_rowsets_data_size="
767
1.76k
              << PrettyPrinter::print_bytes(_input_rowsets_data_size)
768
1.76k
              << ", input_rowsets_index_size="
769
1.76k
              << PrettyPrinter::print_bytes(_input_rowsets_index_size)
770
1.76k
              << ", input_rowsets_total_size="
771
1.76k
              << PrettyPrinter::print_bytes(_input_rowsets_total_size)
772
1.76k
              << ", output_rowset_data_size="
773
1.76k
              << PrettyPrinter::print_bytes(_output_rowset->data_disk_size())
774
1.76k
              << ", output_rowset_index_size="
775
1.76k
              << PrettyPrinter::print_bytes(_output_rowset->index_disk_size())
776
1.76k
              << ", output_rowset_total_size="
777
1.76k
              << PrettyPrinter::print_bytes(_output_rowset->total_disk_size())
778
1.76k
              << ", input_row_num=" << _input_row_num
779
1.76k
              << ", output_row_num=" << _output_rowset->num_rows()
780
1.76k
              << ", filtered_row_num=" << _stats.filtered_rows
781
1.76k
              << ", merged_row_num=" << _stats.merged_rows
782
1.76k
              << ". elapsed time=" << watch.get_elapse_second()
783
1.76k
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
784
1.76k
              << ", compact_row_per_second="
785
1.76k
              << cast_set<double>(_input_row_num) / watch.get_elapse_second();
786
787
1.76k
    _state = CompactionState::SUCCESS;
788
789
1.76k
    return Status::OK();
790
1.76k
}
791
792
9.39k
Status Compaction::do_inverted_index_compaction() {
793
9.39k
    const auto& ctx = _output_rs_writer->context();
794
9.39k
    if (!_enable_inverted_index_compaction || _input_row_num <= 0 ||
795
9.39k
        ctx.columns_to_do_index_compaction.empty()) {
796
9.13k
        return Status::OK();
797
9.13k
    }
798
799
265
    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
265
    DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_rowid_conversion_null",
812
265
                    { _stats.rowid_conversion = nullptr; })
813
265
    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
265
    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
265
    const auto& trans_vec = _stats.rowid_conversion->get_rowid_conversion_map();
833
834
    // source rowset,segment -> index_id
835
265
    const auto& src_seg_to_id_map = _stats.rowid_conversion->get_src_segment_to_id_map();
836
837
    // dest rowset id
838
265
    RowsetId dest_rowset_id = _stats.rowid_conversion->get_dst_rowset_id();
839
    // dest segment id -> num rows
840
265
    std::vector<uint32_t> dest_segment_num_rows;
841
265
    RETURN_IF_ERROR(_output_rs_writer->get_segment_num_rows(&dest_segment_num_rows));
842
843
265
    auto src_segment_num = src_seg_to_id_map.size();
844
265
    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
265
    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
263
    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
263
    std::unordered_map<RowsetId, Rowset*> rs_id_to_rowset_map;
910
1.66k
    for (auto&& rs : _input_rowsets) {
911
1.66k
        rs_id_to_rowset_map.emplace(rs->rowset_id(), rs.get());
912
1.66k
    }
913
914
    // src index dirs
915
263
    std::vector<std::unique_ptr<IndexFileReader>> index_file_readers(src_segment_num);
916
1.05k
    for (const auto& m : src_seg_to_id_map) {
917
1.05k
        const auto& [rowset_id, seg_id] = m.first;
918
919
1.05k
        auto find_it = rs_id_to_rowset_map.find(rowset_id);
920
1.05k
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_find_rowset_error",
921
1.05k
                        { find_it = rs_id_to_rowset_map.end(); })
922
1.05k
        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
1.05k
        auto* rowset = find_it->second;
932
1.05k
        auto fs = rowset->rowset_meta()->fs();
933
1.05k
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_get_fs_error", { fs = nullptr; })
934
1.05k
        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
1.05k
        auto seg_path = rowset->segment_path(seg_id);
943
1.05k
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_seg_path_nullptr", {
944
1.05k
            seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
945
1.05k
                    "do_inverted_index_compaction_seg_path_nullptr"));
946
1.05k
        })
947
1.05k
        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
1.05k
        auto index_file_reader = std::make_unique<IndexFileReader>(
957
1.05k
                fs,
958
1.05k
                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path.value())},
959
1.05k
                _cur_tablet_schema->get_inverted_index_storage_format(),
960
1.05k
                rowset->rowset_meta()->inverted_index_file_info(seg_id), _tablet->tablet_id());
961
1.05k
        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
962
1.05k
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_init_inverted_index_file_reader",
963
1.05k
                        {
964
1.05k
                            st = Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
965
1.05k
                                    "debug point: "
966
1.05k
                                    "Compaction::do_inverted_index_compaction_init_inverted_index_"
967
1.05k
                                    "file_reader error");
968
1.05k
                        })
969
1.05k
        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
1.05k
        index_file_readers[m.second] = std::move(index_file_reader);
980
1.05k
    }
981
982
    // dest index files
983
    // format: rowsetId_segmentId
984
263
    auto& inverted_index_file_writers =
985
263
            dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get())->index_file_writers();
986
263
    DBUG_EXECUTE_IF(
987
263
            "Compaction::do_inverted_index_compaction_inverted_index_file_writers_size_error",
988
263
            { inverted_index_file_writers.clear(); })
989
263
    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
263
    auto tmp_file_dir = ExecEnv::GetInstance()->get_tmp_file_dirs()->get_tmp_file_dir();
1003
263
    auto index_tmp_path = tmp_file_dir / dest_rowset_id.to_string();
1004
263
    LOG(INFO) << "start index compaction"
1005
263
              << ". tablet=" << _tablet->tablet_id() << ", source index size=" << src_segment_num
1006
263
              << ", destination index size=" << dest_segment_num << ".";
1007
1008
263
    Status status = Status::OK();
1009
867
    for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
1010
867
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
1011
867
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
1012
867
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_can_not_find_index_meta",
1013
867
                        { index_metas.clear(); })
1014
867
        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
888
        for (const auto& index_meta : index_metas) {
1024
888
            std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
1025
888
            try {
1026
888
                std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>> src_idx_dirs(
1027
888
                        src_segment_num);
1028
4.01k
                for (int src_segment_id = 0; src_segment_id < src_segment_num; src_segment_id++) {
1029
3.12k
                    auto res = index_file_readers[src_segment_id]->open(index_meta);
1030
3.12k
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
1031
3.12k
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1032
3.12k
                                "debug point: Compaction::open_index_file_reader error"));
1033
3.12k
                    })
1034
3.12k
                    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
3.12k
                    src_idx_dirs[src_segment_id] = std::move(res.value());
1044
3.12k
                }
1045
1.88k
                for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
1046
999
                     dest_segment_id++) {
1047
999
                    auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
1048
999
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
1049
999
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1050
999
                                "debug point: Compaction::open_inverted_index_file_writer error"));
1051
999
                    })
1052
999
                    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
999
                    dest_index_dirs[dest_segment_id] = res.value().get();
1064
999
                }
1065
888
                auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
1066
888
                                         index_tmp_path.native(), trans_vec, dest_segment_num_rows);
1067
888
                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
888
            } 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
888
        }
1079
867
    }
1080
1081
    // check index compaction status. If status is not ok, we should return error and end this compaction round.
1082
262
    if (!status.ok()) {
1083
1
        return status;
1084
1
    }
1085
262
    LOG(INFO) << "succeed to do index compaction"
1086
261
              << ". tablet=" << _tablet->tablet_id()
1087
261
              << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
1088
1089
261
    return Status::OK();
1090
262
}
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
11.4k
                                            const TabletSchemaSPtr& cur_tablet_schema) {
1116
11.4k
    auto* rowset = static_cast<BetaRowset*>(src_rs.get());
1117
11.4k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_is_skip_index_compaction",
1118
11.4k
                    { rowset->set_skip_index_compaction(col_unique_id); })
1119
11.4k
    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
11.4k
    auto fs = rowset->rowset_meta()->fs();
1127
11.4k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_get_fs_error", { fs = nullptr; })
1128
11.4k
    if (!fs) {
1129
2
        LOG(WARNING) << "get fs failed, resource_id=" << rowset->rowset_meta()->resource_id();
1130
2
        return false;
1131
2
    }
1132
1133
11.4k
    auto index_metas = rowset->tablet_schema()->inverted_indexs(col_unique_id);
1134
11.4k
    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_meta_nullptr",
1135
11.4k
                    { index_metas.clear(); })
1136
11.4k
    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
11.7k
    for (const auto& index_meta : index_metas) {
1142
15.3k
        for (auto i = 0; i < rowset->num_segments(); i++) {
1143
            // TODO: inverted_index_path
1144
3.61k
            auto seg_path = rowset->segment_path(i);
1145
3.61k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_seg_path_nullptr", {
1146
3.61k
                seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
1147
3.61k
                        "construct_skip_inverted_index_seg_path_nullptr"));
1148
3.61k
            })
1149
3.61k
            if (!seg_path) {
1150
0
                LOG(WARNING) << seg_path.error();
1151
0
                return false;
1152
0
            }
1153
1154
3.61k
            std::string index_file_path;
1155
3.61k
            try {
1156
3.61k
                auto index_file_reader = std::make_unique<IndexFileReader>(
1157
3.61k
                        fs,
1158
3.61k
                        std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
1159
3.61k
                                seg_path.value())},
1160
3.61k
                        cur_tablet_schema->get_inverted_index_storage_format(),
1161
3.61k
                        rowset->rowset_meta()->inverted_index_file_info(i), tablet->tablet_id());
1162
3.61k
                auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
1163
3.61k
                index_file_path = index_file_reader->get_index_file_path(index_meta);
1164
3.61k
                DBUG_EXECUTE_IF(
1165
3.61k
                        "Compaction::construct_skip_inverted_index_index_file_reader_init_"
1166
3.61k
                        "status_not_ok",
1167
3.61k
                        {
1168
3.61k
                            st = Status::Error<ErrorCode::INTERNAL_ERROR>(
1169
3.61k
                                    "debug point: "
1170
3.61k
                                    "construct_skip_inverted_index_index_file_reader_init_"
1171
3.61k
                                    "status_"
1172
3.61k
                                    "not_ok");
1173
3.61k
                        })
1174
3.61k
                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.61k
                auto result = index_file_reader->open(index_meta);
1181
3.61k
                DBUG_EXECUTE_IF(
1182
3.61k
                        "Compaction::construct_skip_inverted_index_index_file_reader_open_"
1183
3.61k
                        "error",
1184
3.61k
                        {
1185
3.61k
                            result = ResultError(
1186
3.61k
                                    Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1187
3.61k
                                            "CLuceneError occur when open idx file"));
1188
3.61k
                        })
1189
3.61k
                if (!result.has_value()) {
1190
0
                    LOG(WARNING) << "open index " << index_file_path << " error:" << result.error();
1191
0
                    return false;
1192
0
                }
1193
3.61k
                auto reader = std::move(result.value());
1194
3.61k
                std::vector<std::string> files;
1195
3.61k
                reader->list(&files);
1196
3.61k
                reader->close();
1197
3.61k
                DBUG_EXECUTE_IF(
1198
3.61k
                        "Compaction::construct_skip_inverted_index_index_reader_close_"
1199
3.61k
                        "error",
1200
3.61k
                        { _CLTHROWA(CL_ERR_IO, "debug point: reader close error"); })
1201
1202
3.61k
                DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_files_count",
1203
3.61k
                                { 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.61k
                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.61k
            } 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.61k
        }
1220
11.7k
    }
1221
11.4k
    return true;
1222
11.4k
}
1223
1224
7.75k
void Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
1225
7.75k
    for (const auto& index : _cur_tablet_schema->inverted_indexes()) {
1226
2.50k
        auto col_unique_ids = index->col_unique_ids();
1227
        // check if column unique ids is empty to avoid crash
1228
2.50k
        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.50k
        auto col_unique_id = col_unique_ids[0];
1235
2.50k
        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.50k
        if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
1242
861
            continue;
1243
861
        }
1244
1245
        // if index properties are different, index compaction maybe needs to be skipped.
1246
1.64k
        bool is_continue = false;
1247
1.64k
        std::optional<std::map<std::string, std::string>> first_properties;
1248
11.5k
        for (const auto& rowset : _input_rowsets) {
1249
11.5k
            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.5k
            auto it = std::find_if(tablet_indexs.begin(), tablet_indexs.end(),
1252
11.6k
                                   [&index](const auto& tablet_index) {
1253
11.6k
                                       return tablet_index->index_id() == index->index_id();
1254
11.6k
                                   });
1255
11.5k
            if (it != tablet_indexs.end()) {
1256
11.5k
                const auto* tablet_index = *it;
1257
11.5k
                auto properties = tablet_index->properties();
1258
11.5k
                if (!first_properties.has_value()) {
1259
1.64k
                    first_properties = properties;
1260
9.85k
                } else {
1261
9.85k
                    DBUG_EXECUTE_IF(
1262
9.85k
                            "Compaction::do_inverted_index_compaction_index_properties_different",
1263
9.85k
                            { properties.emplace("dummy_key", "dummy_value"); })
1264
9.85k
                    if (properties != first_properties.value()) {
1265
3
                        is_continue = true;
1266
3
                        break;
1267
3
                    }
1268
9.85k
                }
1269
11.5k
            } else {
1270
1
                is_continue = true;
1271
1
                break;
1272
1
            }
1273
11.5k
        }
1274
1.64k
        if (is_continue) {
1275
5
            continue;
1276
5
        }
1277
1.63k
        bool all_have_inverted_index =
1278
1.63k
                std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1279
11.5k
                            [this, col_unique_id](const RowsetSharedPtr& src_rs) {
1280
11.5k
                                return check_rowset_has_inverted_index(src_rs, col_unique_id,
1281
11.5k
                                                                       _tablet, _cur_tablet_schema);
1282
11.5k
                            });
1283
1284
1.63k
        if (all_have_inverted_index) {
1285
1.63k
            ctx.columns_to_do_index_compaction.insert(col_unique_id);
1286
1.63k
        }
1287
1.63k
    }
1288
7.75k
}
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
157
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
157
    {
1322
157
        std::shared_lock meta_rlock(_tablet->get_header_lock());
1323
157
        if (_tablet->tablet_state() != TABLET_NOTREADY) {
1324
157
            return Status::OK();
1325
157
        }
1326
157
    }
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
128k
                                                       std::vector<Version>* missing_version) {
1346
128k
    if (rowsets->empty()) {
1347
0
        return;
1348
0
    }
1349
1350
128k
    RowsetSharedPtr prev_rowset = rowsets->front();
1351
128k
    int max_start = 0;
1352
128k
    int max_length = 1;
1353
128k
    int start = 0;
1354
128k
    int length = 1;
1355
460k
    for (int i = 1; i < rowsets->size(); ++i) {
1356
332k
        RowsetSharedPtr rowset = (*rowsets)[i];
1357
332k
        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
332k
        } else {
1365
332k
            ++length;
1366
332k
        }
1367
1368
332k
        if (length > max_length) {
1369
332k
            max_start = start;
1370
332k
            max_length = length;
1371
332k
        }
1372
1373
332k
        prev_rowset = rowset;
1374
332k
    }
1375
128k
    *rowsets = {rowsets->begin() + max_start, rowsets->begin() + max_start + max_length};
1376
128k
}
1377
1378
2.07k
Status CompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1379
    // only do index compaction for dup_keys and unique_keys with mow enabled
1380
2.07k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1381
2.03k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1382
2.03k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1383
2.01k
        construct_index_compaction_columns(ctx);
1384
2.01k
    }
1385
2.07k
    if (compaction_type() == ReaderType::READER_BINLOG_COMPACTION) {
1386
0
        ctx.write_binlog_opt().enable = true;
1387
0
    }
1388
2.07k
    ctx.version = _output_version;
1389
2.07k
    ctx.rowset_state = VISIBLE;
1390
2.07k
    ctx.segments_overlap = NONOVERLAPPING;
1391
2.07k
    ctx.tablet_schema = _cur_tablet_schema;
1392
2.07k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1393
2.07k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1394
2.07k
    ctx.compaction_type = compaction_type();
1395
2.07k
    ctx.allow_packed_file = false;
1396
2.07k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1397
2.07k
    _pending_rs_guard = _engine.add_pending_rowset(ctx);
1398
2.07k
    return Status::OK();
1399
2.07k
}
1400
1401
2.03k
Status CompactionMixin::modify_rowsets() {
1402
2.03k
    std::vector<RowsetSharedPtr> output_rowsets;
1403
2.03k
    output_rowsets.push_back(_output_rowset);
1404
1405
2.03k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1406
2.03k
        _tablet->enable_unique_key_merge_on_write()) {
1407
1.44k
        Version version = tablet()->max_version();
1408
1.44k
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
1409
1.44k
        std::unique_ptr<RowLocationSet> missed_rows;
1410
1.44k
        if ((config::enable_missing_rows_correctness_check ||
1411
1.44k
             config::enable_mow_compaction_correctness_check_core ||
1412
1.44k
             config::enable_mow_compaction_correctness_check_fail) &&
1413
1.44k
            !_allow_delete_in_cumu_compaction &&
1414
1.44k
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1415
1.44k
            missed_rows = std::make_unique<RowLocationSet>();
1416
1.44k
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
1417
1.44k
        }
1418
1.44k
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1419
1.44k
        if (config::enable_rowid_conversion_correctness_check &&
1420
1.44k
            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
1.44k
        std::size_t missed_rows_size = 0;
1430
1.44k
        tablet()->calc_compaction_output_rowset_delete_bitmap(
1431
1.44k
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1432
1.44k
                location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1433
1.44k
                &output_rowset_delete_bitmap);
1434
1.44k
        if (missed_rows) {
1435
1.44k
            missed_rows_size = missed_rows->size();
1436
1.44k
            std::size_t merged_missed_rows_size = _stats.merged_rows;
1437
1.44k
            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
1.44k
            bool need_to_check_missed_rows = true;
1454
1.44k
            {
1455
1.44k
                std::shared_lock rlock(_tablet->get_header_lock());
1456
1.44k
                need_to_check_missed_rows =
1457
1.44k
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1458
13.6k
                                    [&](const RowsetSharedPtr& rowset) {
1459
13.6k
                                        return tablet()->rowset_exists_unlocked(rowset);
1460
13.6k
                                    });
1461
1.44k
            }
1462
1463
1.44k
            if (_tablet->tablet_state() == TABLET_RUNNING &&
1464
1.44k
                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
1.44k
        }
1500
1501
1.44k
        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
1.44k
        {
1507
1.44k
            std::lock_guard<std::mutex> wrlock_(tablet()->get_rowset_update_lock());
1508
1.44k
            std::lock_guard wrlock(_tablet->get_header_lock());
1509
1.44k
            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
1.44k
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1516
1.44k
            _engine.txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1517
1.44k
                    *tablet(), &commit_tablet_txn_info_vec);
1518
1519
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1520
1.44k
            for (auto& it : commit_tablet_txn_info_vec) {
1521
8
                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
8
                DeleteBitmap txn_output_delete_bitmap(_tablet->tablet_id());
1530
8
                tablet()->calc_compaction_output_rowset_delete_bitmap(
1531
8
                        _input_rowsets, *_rowid_conversion, 0, UINT64_MAX, missed_rows.get(),
1532
8
                        location_map.get(), *it.delete_bitmap.get(), &txn_output_delete_bitmap);
1533
8
                if (config::enable_merge_on_write_correctness_check) {
1534
8
                    RowsetIdUnorderedSet rowsetids;
1535
8
                    rowsetids.insert(_output_rowset->rowset_id());
1536
8
                    _tablet->add_sentinel_mark_to_delete_bitmap(&txn_output_delete_bitmap,
1537
8
                                                                rowsetids);
1538
8
                }
1539
8
                it.delete_bitmap->merge(txn_output_delete_bitmap);
1540
                // Step3: write back updated delete bitmap and tablet info.
1541
8
                it.rowset_ids.insert(_output_rowset->rowset_id());
1542
8
                _engine.txn_manager()->set_txn_related_delete_bitmap(
1543
8
                        it.partition_id, it.transaction_id, _tablet->tablet_id(),
1544
8
                        tablet()->tablet_uid(), true, it.delete_bitmap, it.rowset_ids,
1545
8
                        it.partial_update_info);
1546
8
            }
1547
1548
            // Convert the delete bitmap of the input rowsets to output rowset for
1549
            // incremental data.
1550
1.44k
            tablet()->calc_compaction_output_rowset_delete_bitmap(
1551
1.44k
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1552
1.44k
                    missed_rows.get(), location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1553
1.44k
                    &output_rowset_delete_bitmap);
1554
1555
1.44k
            if (location_map) {
1556
0
                RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1557
0
            }
1558
1559
1.44k
            tablet()->merge_delete_bitmap(output_rowset_delete_bitmap);
1560
1.44k
            RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1561
1.44k
        }
1562
1.44k
    } else {
1563
590
        std::lock_guard wrlock(_tablet->get_header_lock());
1564
590
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1565
590
        RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1566
590
    }
1567
1568
2.03k
    if (config::tablet_rowset_stale_sweep_by_size &&
1569
2.03k
        _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
2.03k
    int64_t cur_max_version = 0;
1575
2.03k
    {
1576
2.03k
        std::shared_lock rlock(_tablet->get_header_lock());
1577
2.03k
        cur_max_version = _tablet->max_version_unlocked();
1578
2.03k
        tablet()->save_meta();
1579
2.03k
    }
1580
2.03k
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1581
2.03k
        _tablet->enable_unique_key_merge_on_write()) {
1582
1.44k
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1583
1.44k
                tablet()->data_dir(), _tablet->tablet_id(), cur_max_version);
1584
1.44k
        if (!st.ok()) {
1585
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1586
0
        }
1587
1.44k
    }
1588
2.03k
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset",
1589
2.03k
                    { tablet()->delete_expired_stale_rowset(); });
1590
2.03k
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
1591
2.03k
    return Status::OK();
1592
2.03k
}
1593
1594
bool CompactionMixin::_check_if_includes_input_rowsets(
1595
8
        const RowsetIdUnorderedSet& commit_rowset_ids_set) const {
1596
8
    std::vector<RowsetId> commit_rowset_ids {};
1597
8
    commit_rowset_ids.insert(commit_rowset_ids.end(), commit_rowset_ids_set.begin(),
1598
8
                             commit_rowset_ids_set.end());
1599
8
    std::sort(commit_rowset_ids.begin(), commit_rowset_ids.end());
1600
8
    std::vector<RowsetId> input_rowset_ids {};
1601
92
    for (const auto& rowset : _input_rowsets) {
1602
92
        input_rowset_ids.emplace_back(rowset->rowset_meta()->rowset_id());
1603
92
    }
1604
8
    std::sort(input_rowset_ids.begin(), input_rowset_ids.end());
1605
8
    return std::includes(commit_rowset_ids.begin(), commit_rowset_ids.end(),
1606
8
                         input_rowset_ids.begin(), input_rowset_ids.end());
1607
8
}
1608
1609
1.78k
void CompactionMixin::update_compaction_level() {
1610
1.78k
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
1611
1.78k
    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
1.78k
}
1617
1618
9.35k
Status Compaction::check_correctness() {
1619
    // 1. check row number
1620
9.35k
    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
9.35k
    RETURN_IF_ERROR(variant_util::VariantCompactionUtil::check_path_stats(_input_rowsets,
1629
9.35k
                                                                          _output_rowset, _tablet));
1630
9.35k
    return Status::OK();
1631
9.35k
}
1632
1633
4.06k
int64_t CompactionMixin::get_compaction_permits() {
1634
4.06k
    int64_t permits = 0;
1635
36.9k
    for (auto&& rowset : _input_rowsets) {
1636
36.9k
        permits += rowset->rowset_meta()->get_compaction_score();
1637
36.9k
    }
1638
4.06k
    return permits;
1639
4.06k
}
1640
1641
2
int64_t CompactionMixin::calc_input_rowsets_total_size() const {
1642
2
    int64_t input_rowsets_total_size = 0;
1643
4
    for (const auto& rowset : _input_rowsets) {
1644
4
        const auto& rowset_meta = rowset->rowset_meta();
1645
4
        auto total_size = rowset_meta->total_disk_size();
1646
4
        input_rowsets_total_size += total_size;
1647
4
    }
1648
2
    return input_rowsets_total_size;
1649
2
}
1650
1651
2
int64_t CompactionMixin::calc_input_rowsets_row_num() const {
1652
2
    int64_t input_rowsets_row_num = 0;
1653
4
    for (const auto& rowset : _input_rowsets) {
1654
4
        const auto& rowset_meta = rowset->rowset_meta();
1655
4
        auto total_size = rowset_meta->total_disk_size();
1656
4
        input_rowsets_row_num += total_size;
1657
4
    }
1658
2
    return input_rowsets_row_num;
1659
2
}
1660
1661
9.51k
void Compaction::_load_segment_to_cache() {
1662
    // Load new rowset's segments to cache.
1663
9.51k
    SegmentCacheHandle handle;
1664
9.51k
    auto st = SegmentLoader::instance()->load_segments(
1665
9.51k
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1666
9.51k
    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
9.51k
}
1672
1673
7.55k
Status CloudCompactionMixin::build_basic_info() {
1674
7.55k
    _output_version =
1675
7.55k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
1676
1677
7.55k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
1678
1679
7.55k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
1680
7.55k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
1681
58.3k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
1682
7.55k
    if (is_index_change_compaction()) {
1683
801
        RETURN_IF_ERROR(rebuild_tablet_schema());
1684
6.75k
    } else {
1685
6.75k
        _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
1686
6.75k
    }
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.55k
    if (_enable_vertical_compact_variant_subcolumns) {
1691
7.54k
        RETURN_IF_ERROR(variant_util::VariantCompactionUtil::get_extended_compaction_schema(
1692
7.54k
                _input_rowsets, _cur_tablet_schema));
1693
7.54k
    }
1694
7.55k
    return Status::OK();
1695
7.55k
}
1696
1697
7.52k
int64_t CloudCompactionMixin::get_compaction_permits() {
1698
7.52k
    int64_t permits = 0;
1699
58.5k
    for (auto&& rowset : _input_rowsets) {
1700
58.5k
        permits += rowset->rowset_meta()->get_compaction_score();
1701
58.5k
    }
1702
7.52k
    return permits;
1703
7.52k
}
1704
1705
CloudCompactionMixin::CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
1706
                                           const std::string& label)
1707
131k
        : Compaction(tablet, label), _engine(engine) {
1708
131k
    auto uuid = UUIDGenerator::instance()->next_uuid();
1709
131k
    std::stringstream ss;
1710
131k
    ss << uuid;
1711
131k
    _uuid = ss.str();
1712
131k
}
1713
1714
7.55k
Status CloudCompactionMixin::execute_compact_impl(int64_t permits) {
1715
7.55k
    OlapStopWatch watch;
1716
1717
7.55k
    RETURN_IF_ERROR(build_basic_info());
1718
1719
7.55k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
1720
7.55k
              << ", output_version=" << _output_version << ", permits: " << permits;
1721
1722
7.55k
    RETURN_IF_ERROR(merge_input_rowsets());
1723
1724
7.55k
    DBUG_EXECUTE_IF("CloudFullCompaction::modify_rowsets.wrong_rowset_id", {
1725
7.55k
        DCHECK(compaction_type() == ReaderType::READER_FULL_COMPACTION);
1726
7.55k
        RowsetId id;
1727
7.55k
        id.version = 2;
1728
7.55k
        id.hi = _output_rowset->rowset_meta()->rowset_id().hi + ((int64_t)(1) << 56);
1729
7.55k
        id.mi = _output_rowset->rowset_meta()->rowset_id().mi;
1730
7.55k
        id.lo = _output_rowset->rowset_meta()->rowset_id().lo;
1731
7.55k
        _output_rowset->rowset_meta()->set_rowset_id(id);
1732
7.55k
        LOG(INFO) << "[Debug wrong rowset id]:"
1733
7.55k
                  << _output_rowset->rowset_meta()->rowset_id().to_string();
1734
7.55k
    })
1735
1736
    // Currently, updates are only made in the time_series.
1737
7.55k
    update_compaction_level();
1738
1739
7.55k
    RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get(), _uuid,
1740
7.55k
                                                     _tablet->table_id()));
1741
1742
    // 4. modify rowsets in memory
1743
7.55k
    RETURN_IF_ERROR(modify_rowsets());
1744
1745
    // update compaction status data
1746
7.50k
    auto tablet = std::static_pointer_cast<CloudTablet>(_tablet);
1747
7.50k
    tablet->local_read_time_us.fetch_add(_stats.cloud_local_read_time);
1748
7.50k
    tablet->remote_read_time_us.fetch_add(_stats.cloud_remote_read_time);
1749
7.50k
    tablet->exec_compaction_time_us.fetch_add(watch.get_elapse_time_us());
1750
1751
7.50k
    return Status::OK();
1752
7.55k
}
1753
1754
7.41k
int64_t CloudCompactionMixin::initiator() const {
1755
7.41k
    return HashUtil::hash64(_uuid.data(), _uuid.size(), 0) & std::numeric_limits<int64_t>::max();
1756
7.41k
}
1757
1758
namespace cloud {
1759
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
1760
7.95k
                                    int64_t& truncated_size_bytes) {
1761
7.95k
    if (rowsets.empty()) {
1762
1
        kept_size_bytes = 0;
1763
1
        truncated_size_bytes = 0;
1764
1
        return 0;
1765
1
    }
1766
1767
7.95k
    int64_t max_size = config::compaction_txn_max_size_bytes;
1768
7.95k
    int64_t cumulative_meta_size = 0;
1769
7.95k
    size_t keep_count = 0;
1770
1771
70.2k
    for (size_t i = 0; i < rowsets.size(); ++i) {
1772
62.2k
        const auto& rs = rowsets[i];
1773
1774
        // Estimate rowset meta size using doris_rowset_meta_to_cloud
1775
62.2k
        auto cloud_meta = cloud::doris_rowset_meta_to_cloud(rs->rowset_meta()->get_rowset_pb(true));
1776
62.2k
        int64_t rowset_meta_size = cloud_meta.ByteSizeLong();
1777
1778
62.2k
        cumulative_meta_size += rowset_meta_size;
1779
1780
62.2k
        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.2k
        keep_count++;
1787
62.2k
    }
1788
1789
    // Ensure at least 1 rowset is kept
1790
7.95k
    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
7.95k
    int64_t truncated_total_size = 0;
1800
7.95k
    size_t truncated_count = rowsets.size() - keep_count;
1801
7.95k
    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
7.95k
    kept_size_bytes = cumulative_meta_size;
1811
7.95k
    truncated_size_bytes = truncated_total_size;
1812
7.95k
    return truncated_count;
1813
7.95k
}
1814
} // namespace cloud
1815
1816
7.13k
size_t CloudCompactionMixin::apply_txn_size_truncation_and_log(const std::string& compaction_name) {
1817
7.13k
    if (_input_rowsets.empty()) {
1818
1
        return 0;
1819
1
    }
1820
1821
7.13k
    int64_t original_count = _input_rowsets.size();
1822
7.13k
    int64_t original_start_version = _input_rowsets.front()->start_version();
1823
7.13k
    int64_t original_end_version = _input_rowsets.back()->end_version();
1824
1825
7.13k
    int64_t final_size = 0;
1826
7.13k
    int64_t truncated_size = 0;
1827
7.13k
    size_t truncated_count =
1828
7.13k
            cloud::truncate_rowsets_by_txn_size(_input_rowsets, final_size, truncated_size);
1829
1830
7.13k
    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.13k
    return truncated_count;
1847
7.13k
}
1848
1849
7.50k
Status CloudCompactionMixin::execute_compact() {
1850
7.50k
    int64_t profile_start_time_ms = UnixMillis();
1851
7.50k
    TEST_INJECTION_POINT("Compaction::do_compaction");
1852
7.50k
    int64_t permits = get_compaction_permits();
1853
7.50k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
1854
7.50k
            execute_compact_impl(permits), [&](const doris::Exception& ex) {
1855
7.50k
                auto st = garbage_collection();
1856
7.50k
                if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1857
7.50k
                    _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.50k
                    _engine.meta_mgr().remove_delete_bitmap_update_lock(
1863
7.50k
                            _tablet->table_id(), COMPACTION_DELETE_BITMAP_LOCK_ID, initiator(),
1864
7.50k
                            _tablet->tablet_id());
1865
7.50k
                }
1866
7.50k
                submit_profile_record(false, profile_start_time_ms, ex.what());
1867
7.50k
            });
1868
1869
7.48k
    DorisMetrics::instance()->remote_compaction_read_rows_total->increment(_input_row_num);
1870
7.48k
    DorisMetrics::instance()->remote_compaction_write_rows_total->increment(
1871
7.48k
            _output_rowset->num_rows());
1872
7.48k
    DorisMetrics::instance()->remote_compaction_write_bytes_total->increment(
1873
7.48k
            _output_rowset->total_disk_size());
1874
1875
7.48k
    _load_segment_to_cache();
1876
7.48k
    submit_profile_record(true, profile_start_time_ms);
1877
7.48k
    return Status::OK();
1878
7.50k
}
1879
1880
0
Status CloudCompactionMixin::modify_rowsets() {
1881
0
    return Status::OK();
1882
0
}
1883
1884
7.57k
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
7.58k
    for (const auto& rowset : std::ranges::reverse_view(_input_rowsets)) {
1895
7.58k
        const auto& resource_id = rowset->rowset_meta()->resource_id();
1896
1897
7.58k
        if (!resource_id.empty()) {
1898
7.58k
            ctx.storage_resource = *DORIS_TRY(rowset->rowset_meta()->remote_storage_resource());
1899
7.58k
            return Status::OK();
1900
7.58k
        }
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
18.4E
        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
18.4E
    }
1920
1921
18.4E
    return Status::OK();
1922
7.57k
}
1923
1924
7.54k
Status CloudCompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1925
    // only do index compaction for dup_keys and unique_keys with mow enabled
1926
7.54k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1927
6.75k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1928
6.75k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1929
5.75k
        construct_index_compaction_columns(ctx);
1930
5.75k
    }
1931
1932
    // Use the storage resource of the previous rowset.
1933
7.54k
    RETURN_IF_ERROR(set_storage_resource_from_input_rowsets(ctx));
1934
1935
7.54k
    ctx.txn_id = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
1936
7.54k
                 std::numeric_limits<int64_t>::max(); // MUST be positive
1937
7.54k
    ctx.txn_expiration = _expiration;
1938
1939
7.54k
    ctx.version = _output_version;
1940
7.54k
    ctx.rowset_state = VISIBLE;
1941
7.54k
    ctx.segments_overlap = NONOVERLAPPING;
1942
7.54k
    ctx.tablet_schema = _cur_tablet_schema;
1943
7.54k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1944
7.54k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1945
7.54k
    ctx.compaction_type = compaction_type();
1946
7.54k
    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.54k
    ctx.write_file_cache = should_cache_compaction_output();
1953
7.54k
    ctx.file_cache_ttl_sec = _tablet->ttl_seconds();
1954
7.54k
    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.54k
    ctx.compaction_output_write_index_only = should_enable_compaction_cache_index_only(
1958
7.54k
            ctx.write_file_cache, compaction_type(),
1959
7.54k
            config::enable_file_cache_write_base_compaction_index_only,
1960
7.54k
            config::enable_file_cache_write_cumu_compaction_index_only);
1961
1962
7.54k
    ctx.tablet = _tablet;
1963
7.54k
    ctx.job_id = _uuid;
1964
1965
7.54k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1966
7.54k
    RETURN_IF_ERROR(_engine.meta_mgr().prepare_rowset(*_output_rs_writer->rowset_meta().get(),
1967
7.54k
                                                      _uuid, _tablet->table_id()));
1968
7.54k
    return Status::OK();
1969
7.54k
}
1970
1971
59
Status CloudCompactionMixin::garbage_collection() {
1972
59
    if (!config::enable_file_cache) {
1973
0
        return Status::OK();
1974
0
    }
1975
59
    if (_output_rs_writer) {
1976
59
        auto* beta_rowset_writer = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get());
1977
59
        DCHECK(beta_rowset_writer);
1978
59
        for (const auto& [_, file_writer] : beta_rowset_writer->get_file_writers()) {
1979
54
            auto file_key = io::BlockFileCache::hash(file_writer->path().filename().native());
1980
54
            auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1981
54
            file_cache->remove_if_cached_async(file_key);
1982
54
        }
1983
59
        for (const auto& [_, index_writer] : beta_rowset_writer->index_file_writers()) {
1984
2
            for (const auto& file_name : index_writer->get_index_file_names()) {
1985
2
                auto file_key = io::BlockFileCache::hash(file_name);
1986
2
                auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1987
2
                file_cache->remove_if_cached_async(file_key);
1988
2
            }
1989
2
        }
1990
59
    }
1991
59
    return Status::OK();
1992
59
}
1993
1994
7.53k
void CloudCompactionMixin::update_compaction_level() {
1995
    // for index change compaction, compaction level should not changed.
1996
    // because input rowset num is 1.
1997
7.53k
    if (is_index_change_compaction()) {
1998
805
        DCHECK(_input_rowsets.size() == 1);
1999
805
        _output_rowset->rowset_meta()->set_compaction_level(
2000
805
                _input_rowsets.back()->rowset_meta()->compaction_level());
2001
6.73k
    } else {
2002
6.73k
        auto compaction_policy = _tablet->tablet_meta()->compaction_policy();
2003
6.73k
        auto cumu_policy = _engine.cumu_compaction_policy(compaction_policy);
2004
6.76k
        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.73k
    }
2010
7.53k
}
2011
2012
// should skip hole rowsets, ortherwise the count will be wrong in ms
2013
7.54k
int64_t CloudCompactionMixin::num_input_rowsets() const {
2014
7.54k
    int64_t count = 0;
2015
58.7k
    for (const auto& r : _input_rowsets) {
2016
58.7k
        if (!r->is_hole_rowset()) {
2017
58.7k
            count++;
2018
58.7k
        }
2019
58.7k
    }
2020
7.54k
    return count;
2021
7.54k
}
2022
2023
7.60k
bool CloudCompactionMixin::should_cache_compaction_output() {
2024
7.60k
    if (config::enable_file_cache_write_index_file_only) {
2025
1
        return false;
2026
1
    }
2027
2028
7.59k
    if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
2029
7.43k
        return true;
2030
7.43k
    }
2031
2032
166
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
2033
71
        double input_rowsets_hit_cache_ratio = 0.0;
2034
2035
71
        int64_t _input_rowsets_cached_size =
2036
71
                _input_rowsets_cached_data_size + _input_rowsets_cached_index_size;
2037
71
        if (_input_rowsets_total_size > 0) {
2038
63
            input_rowsets_hit_cache_ratio =
2039
63
                    double(_input_rowsets_cached_size) / double(_input_rowsets_total_size);
2040
63
        }
2041
2042
71
        LOG(INFO) << "CloudBaseCompaction should_cache_compaction_output"
2043
71
                  << ", tablet_id=" << _tablet->tablet_id()
2044
71
                  << ", input_rowsets_hit_cache_ratio=" << input_rowsets_hit_cache_ratio
2045
71
                  << ", _input_rowsets_cached_size=" << _input_rowsets_cached_size
2046
71
                  << ", _input_rowsets_total_size=" << _input_rowsets_total_size
2047
71
                  << ", enable_file_cache_keep_base_compaction_output="
2048
71
                  << config::enable_file_cache_keep_base_compaction_output
2049
71
                  << ", file_cache_keep_base_compaction_output_min_hit_ratio="
2050
71
                  << config::file_cache_keep_base_compaction_output_min_hit_ratio;
2051
2052
71
        if (config::enable_file_cache_keep_base_compaction_output) {
2053
1
            return true;
2054
1
        }
2055
2056
70
        if (input_rowsets_hit_cache_ratio >
2057
70
            config::file_cache_keep_base_compaction_output_min_hit_ratio) {
2058
42
            return true;
2059
42
        }
2060
70
    }
2061
123
    return false;
2062
166
}
2063
2064
} // namespace doris