Coverage Report

Created: 2026-06-16 15:14

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