Coverage Report

Created: 2026-06-03 11:48

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