Coverage Report

Created: 2026-05-19 12:36

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