Coverage Report

Created: 2026-06-05 06:00

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