Coverage Report

Created: 2026-08-13 14:03

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