Coverage Report

Created: 2026-06-03 03:56

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