Coverage Report

Created: 2026-07-30 17:55

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