Coverage Report

Created: 2026-08-10 08:11

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