Coverage Report

Created: 2026-09-07 16:49

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.43k
                                               bool enable_cumu_index_only) {
103
9.43k
    if (!write_file_cache) {
104
104
        return false;
105
104
    }
106
107
9.32k
    if (compaction_type == ReaderType::READER_BASE_COMPACTION && enable_base_index_only) {
108
2
        return true;
109
2
    }
110
111
9.32k
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION && enable_cumu_index_only) {
112
2
        return true;
113
2
    }
114
115
9.32k
    return false;
116
9.32k
}
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
101
                    const RowsetSharedPtr& rhs) {
123
101
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
124
101
    if (rhs->num_segments() == 0) {
125
32
        return true;
126
32
    }
127
69
    if (rhs->is_segments_overlapping()) {
128
0
        return false;
129
0
    }
130
    // check segment size
131
69
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
132
69
    std::vector<size_t> segments_size;
133
69
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
134
76
    for (auto segment_size : segments_size) {
135
        // is segment is too small, need to do compaction
136
76
        if (segment_size < min_tidy_size) {
137
30
            return false;
138
30
        }
139
76
    }
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
205k
        : _compaction_id(CompactionTaskTracker::instance()->next_compaction_id()),
159
          _mem_tracker(
160
205k
                  MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label)),
161
205k
          _tablet(std::move(tablet)),
162
205k
          _is_vertical(config::enable_vertical_compaction),
163
205k
          _allow_delete_in_cumu_compaction(config::enable_delete_when_cumu_compaction),
164
          _enable_vertical_compact_variant_subcolumns(
165
205k
                  config::enable_vertical_compact_variant_subcolumns),
166
205k
          _enable_inverted_index_compaction(config::inverted_index_compaction_enable) {
167
205k
    init_profile(label);
168
205k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
169
205k
    _rowid_conversion = std::make_unique<RowIdConversion>();
170
205k
}
171
172
205k
Compaction::~Compaction() {
173
205k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
174
205k
    _output_rs_writer.reset();
175
205k
    _tablet.reset();
176
205k
    _input_rowsets.clear();
177
205k
    _output_rowset.reset();
178
205k
    _cur_tablet_schema.reset();
179
205k
    _rowid_conversion.reset();
180
205k
}
181
182
18.0k
std::string Compaction::input_version_range_str() const {
183
18.0k
    if (_input_rowsets.empty()) return "";
184
18.0k
    return fmt::format("[{}-{}]", _input_rowsets.front()->start_version(),
185
18.0k
                       _input_rowsets.back()->end_version());
186
18.0k
}
187
188
void Compaction::submit_profile_record(bool success, int64_t start_time_ms,
189
9.39k
                                       const std::string& status_msg) {
190
9.39k
    if (!profile_type().has_value()) {
191
505
        return;
192
505
    }
193
8.89k
    auto* tracker = CompactionTaskTracker::instance();
194
8.89k
    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.89k
    stats.input_version_range = input_version_range_str();
198
8.89k
    stats.input_rowsets_count = static_cast<int64_t>(_input_rowsets.size());
199
8.89k
    stats.input_row_num = _input_row_num;
200
8.89k
    stats.input_data_size = _input_rowsets_data_size;
201
8.89k
    stats.input_index_size = _input_rowsets_index_size;
202
8.89k
    stats.input_total_size = _input_rowsets_total_size;
203
8.89k
    stats.input_segments_num = input_segments_num_value();
204
8.89k
    stats.end_time_ms = UnixMillis();
205
8.89k
    stats.merged_rows = _stats.merged_rows;
206
8.89k
    stats.filtered_rows = _stats.filtered_rows;
207
8.89k
    stats.output_rows = _stats.output_rows;
208
8.95k
    if (_output_rowset) {
209
8.95k
        stats.output_row_num = _output_rowset->num_rows();
210
8.95k
        stats.output_data_size = _output_rowset->data_disk_size();
211
8.95k
        stats.output_index_size = _output_rowset->index_disk_size();
212
8.95k
        stats.output_total_size = _output_rowset->total_disk_size();
213
8.95k
        stats.output_segments_num = _output_rowset->num_segments();
214
8.95k
    }
215
8.89k
    stats.output_version = _output_version.to_string();
216
8.98k
    if (_merge_rowsets_latency_timer) {
217
8.98k
        stats.merge_latency_ms = _merge_rowsets_latency_timer->value() / 1000000;
218
8.98k
    }
219
8.89k
    stats.bytes_read_from_local = _stats.bytes_read_from_local;
220
8.89k
    stats.bytes_read_from_remote = _stats.bytes_read_from_remote;
221
8.95k
    if (_mem_tracker) {
222
8.95k
        stats.peak_memory_bytes = _mem_tracker->peak_consumption();
223
8.95k
    }
224
8.89k
    if (success) {
225
8.89k
        tracker->complete(_compaction_id, stats);
226
18.4E
    } else {
227
18.4E
        tracker->fail(_compaction_id, stats, status_msg);
228
18.4E
    }
229
8.89k
}
230
231
205k
void Compaction::init_profile(const std::string& label) {
232
205k
    _profile = std::make_unique<RuntimeProfile>(label);
233
234
205k
    _input_rowsets_data_size_counter =
235
205k
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
236
205k
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
237
205k
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
238
205k
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
239
205k
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
240
205k
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
241
205k
    _output_rowset_data_size_counter =
242
205k
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
243
205k
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
244
205k
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
245
205k
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
246
205k
}
247
248
9.44k
int64_t Compaction::merge_way_num() {
249
9.44k
    int64_t way_num = 0;
250
75.9k
    for (auto&& rowset : _input_rowsets) {
251
75.9k
        way_num += rowset->rowset_meta()->get_merge_way_num();
252
75.9k
    }
253
254
9.44k
    return way_num;
255
9.44k
}
256
257
9.49k
Status Compaction::merge_input_rowsets() {
258
9.49k
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
259
9.49k
    input_rs_readers.reserve(_input_rowsets.size());
260
76.4k
    for (auto& rowset : _input_rowsets) {
261
76.4k
        RowsetReaderSharedPtr rs_reader;
262
76.4k
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
263
76.4k
        input_rs_readers.push_back(std::move(rs_reader));
264
76.4k
    }
265
266
9.49k
    RowsetWriterContext ctx;
267
9.49k
    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.49k
    if (!ctx.columns_to_do_index_compaction.empty() ||
274
9.49k
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
275
9.18k
         _tablet->enable_unique_key_merge_on_write())) {
276
3.60k
        _stats.rowid_conversion = _rowid_conversion.get();
277
3.60k
    }
278
279
9.49k
    int64_t way_num = merge_way_num();
280
281
9.49k
    Status res;
282
9.49k
    {
283
9.49k
        SCOPED_TIMER(_merge_rowsets_latency_timer);
284
        // 1. Merge segment files and write bkd inverted index
285
9.49k
        if (_is_vertical) {
286
9.48k
            if (!_tablet->tablet_schema()->cluster_key_uids().empty()) {
287
147
                RETURN_IF_ERROR(update_delete_bitmap());
288
147
            }
289
9.48k
            auto progress_cb = [compaction_id = this->_compaction_id](int64_t total,
290
36.6k
                                                                      int64_t completed) {
291
36.6k
                CompactionTaskTracker::instance()->update_progress(compaction_id, total, completed);
292
36.6k
            };
293
9.48k
            res = Merger::vertical_merge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
294
9.48k
                                                 input_rs_readers, _output_rs_writer.get(),
295
9.48k
                                                 cast_set<uint32_t>(get_avg_segment_rows()),
296
9.48k
                                                 way_num, &_stats, progress_cb);
297
9.48k
        } 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.49k
        _tablet->last_compaction_status = res;
307
9.49k
        if (!res.ok()) {
308
0
            return res;
309
0
        }
310
        // 2. Merge the remaining inverted index files of the string type
311
9.49k
        RETURN_IF_ERROR(do_inverted_index_compaction());
312
9.49k
    }
313
314
9.49k
    COUNTER_UPDATE(_merged_rows_counter, _stats.merged_rows);
315
9.49k
    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.49k
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
319
9.49k
                                   fmt::format("rowset writer build failed. output_version: {}",
320
9.49k
                                               _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.49k
    if (_enable_vertical_compact_variant_subcolumns &&
327
9.49k
        (_cur_tablet_schema->num_variant_columns() > 0)) {
328
437
        _output_rowset->rowset_meta()->set_tablet_schema(
329
437
                _cur_tablet_schema->copy_without_variant_extracted_columns());
330
437
    }
331
332
    //RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get()));
333
9.49k
    set_delete_predicate_for_output_rowset();
334
335
9.49k
    _local_read_bytes_total = _stats.bytes_read_from_local;
336
9.49k
    _remote_read_bytes_total = _stats.bytes_read_from_remote;
337
9.49k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(_local_read_bytes_total);
338
9.49k
    DorisMetrics::instance()->remote_compaction_read_bytes_total->increment(
339
9.49k
            _remote_read_bytes_total);
340
9.49k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
341
9.49k
            _stats.cached_bytes_total);
342
343
9.49k
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
344
9.49k
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
345
9.49k
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
346
347
9.49k
    return check_correctness();
348
9.49k
}
349
350
9.47k
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.47k
    if (_output_rowset->version().first > 2 &&
356
9.47k
        (_allow_delete_in_cumu_compaction || is_index_change_compaction())) {
357
158
        DeletePredicatePB delete_predicate;
358
158
        std::accumulate(_input_rowsets.begin(), _input_rowsets.end(), &delete_predicate,
359
158
                        [](DeletePredicatePB* delete_predicate, const RowsetSharedPtr& rs) {
360
158
                            if (rs->rowset_meta()->has_delete_predicate()) {
361
3
                                delete_predicate->MergeFrom(rs->rowset_meta()->delete_predicate());
362
3
                            }
363
158
                            return delete_predicate;
364
158
                        });
365
        // now version in delete_predicate is deprecated
366
158
        if (!delete_predicate.in_predicates().empty() ||
367
158
            !delete_predicate.sub_predicates_v2().empty() ||
368
158
            !delete_predicate.sub_predicates().empty()) {
369
3
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
370
3
        }
371
158
    }
372
9.47k
}
373
374
9.44k
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.44k
    const auto& meta = _tablet->tablet_meta();
380
9.44k
    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.43k
    return std::min(config::vertical_compaction_max_segment_size /
388
9.43k
                            (_input_rowsets_data_size / (_input_row_num + 1) + 1),
389
9.43k
                    _input_row_num + 1);
390
9.44k
}
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.11M
Tablet* CompactionMixin::tablet() {
409
1.11M
    return static_cast<Tablet*>(_tablet.get());
410
1.11M
}
411
412
16
Status CompactionMixin::do_compact_ordered_rowsets() {
413
16
    RETURN_IF_ERROR(build_basic_info(true));
414
16
    RowsetWriterContext ctx;
415
16
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
416
417
16
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
418
16
              << ", output_version=" << _output_version;
419
    // link data to new rowset
420
16
    auto seg_id = 0;
421
16
    bool segments_key_bounds_truncated {false};
422
16
    bool any_input_aggregated {false};
423
16
    std::vector<KeyBoundsPB> segment_key_bounds;
424
16
    std::vector<uint32_t> num_segment_rows;
425
56
    for (auto rowset : _input_rowsets) {
426
56
        RETURN_IF_ERROR(rowset->link_files_to(tablet()->tablet_path(),
427
56
                                              _output_rs_writer->rowset_id(), seg_id));
428
56
        seg_id += rowset->num_segments();
429
56
        segments_key_bounds_truncated |= rowset->is_segments_key_bounds_truncated();
430
56
        any_input_aggregated |= rowset->rowset_meta()->is_segments_key_bounds_aggregated();
431
56
        std::vector<KeyBoundsPB> key_bounds;
432
56
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
433
56
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
434
56
        std::vector<uint32_t> input_segment_rows;
435
56
        rowset->get_num_segment_rows(&input_segment_rows);
436
56
        num_segment_rows.insert(num_segment_rows.end(), input_segment_rows.begin(),
437
56
                                input_segment_rows.end());
438
56
    }
439
    // build output rowset
440
16
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
441
16
    rowset_meta->set_num_rows(_input_row_num);
442
16
    rowset_meta->set_total_disk_size(_input_rowsets_data_size + _input_rowsets_index_size);
443
16
    rowset_meta->set_data_disk_size(_input_rowsets_data_size);
444
16
    rowset_meta->set_index_disk_size(_input_rowsets_index_size);
445
16
    rowset_meta->set_empty(_input_row_num == 0);
446
16
    rowset_meta->set_num_segments(_input_num_segments);
447
16
    rowset_meta->set_segments_overlap(NONOVERLAPPING);
448
16
    rowset_meta->set_rowset_state(VISIBLE);
449
16
    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
16
    bool aggregate_key_bounds =
454
16
            any_input_aggregated || (config::enable_aggregate_non_mow_key_bounds &&
455
16
                                     !_tablet->enable_unique_key_merge_on_write());
456
16
    rowset_meta->set_segments_key_bounds(segment_key_bounds, aggregate_key_bounds);
457
16
    rowset_meta->set_num_segment_rows(num_segment_rows);
458
459
16
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
460
461
    // 2. check variant column path stats
462
16
    RETURN_IF_ERROR(vectorized::schema_util::VariantCompactionUtil::check_path_stats(
463
16
            _input_rowsets, _output_rowset, _tablet));
464
16
    return Status::OK();
465
16
}
466
467
88
Status CompactionMixin::build_basic_info(bool is_ordered_compaction) {
468
628
    for (auto& rowset : _input_rowsets) {
469
628
        const auto& rowset_meta = rowset->rowset_meta();
470
628
        auto index_size = rowset_meta->index_disk_size();
471
628
        auto total_size = rowset_meta->total_disk_size();
472
628
        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
628
        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
628
        _input_rowsets_data_size += data_size;
486
628
        _input_rowsets_index_size += index_size;
487
628
        _input_rowsets_total_size += total_size;
488
628
        _input_row_num += rowset->num_rows();
489
628
        _input_num_segments += rowset->num_segments();
490
628
    }
491
88
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_data_size);
492
88
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
493
88
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
494
495
88
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::build_basic_info",
496
88
                                      Status::OK());
497
498
88
    _output_version =
499
88
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
500
501
88
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
502
503
88
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
504
88
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
505
772
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
506
88
    _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
88
    if (_enable_vertical_compact_variant_subcolumns && !is_ordered_compaction) {
512
78
        RETURN_IF_ERROR(
513
78
                vectorized::schema_util::VariantCompactionUtil::get_extended_compaction_schema(
514
78
                        _input_rowsets, _cur_tablet_schema));
515
78
    }
516
88
    return Status::OK();
517
88
}
518
519
100
bool CompactionMixin::handle_ordered_data_compaction() {
520
100
    if (!config::enable_ordered_data_compaction) {
521
0
        return false;
522
0
    }
523
100
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
524
100
        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
100
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
529
100
        _tablet->enable_unique_key_merge_on_write()) {
530
48
        return false;
531
48
    }
532
533
52
    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
52
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION ||
541
52
        (_allow_delete_in_cumu_compaction &&
542
50
         compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION)) {
543
0
        for (auto& rowset : _input_rowsets) {
544
0
            if (rowset->rowset_meta()->has_delete_predicate()) {
545
0
                return false;
546
0
            }
547
0
        }
548
0
    }
549
550
    // check if rowsets are tidy so we can just modify meta and do link
551
    // files to handle compaction
552
52
    auto input_size = _input_rowsets.size();
553
52
    std::string pre_max_key;
554
52
    bool pre_rs_key_bounds_truncated {false};
555
117
    for (auto i = 0; i < input_size; ++i) {
556
101
        if (!is_rowset_tidy(pre_max_key, pre_rs_key_bounds_truncated, _input_rowsets[i])) {
557
36
            if (i <= input_size / 2) {
558
34
                return false;
559
34
            } else {
560
2
                _input_rowsets.resize(i);
561
2
                break;
562
2
            }
563
36
        }
564
101
    }
565
    // most rowset of current compaction is nonoverlapping
566
    // just handle nonoverlappint rowsets
567
18
    auto st = do_compact_ordered_rowsets();
568
18
    if (!st.ok()) {
569
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
570
0
        _pending_rs_guard.drop();
571
0
    }
572
573
18
    return st.ok();
574
52
}
575
576
86
Status CompactionMixin::execute_compact() {
577
86
    int64_t profile_start_time_ms = UnixMillis();
578
86
    uint32_t checksum_before;
579
86
    uint32_t checksum_after;
580
86
    bool enable_compaction_checksum = config::enable_compaction_checksum;
581
86
    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
86
    auto* data_dir = tablet()->data_dir();
592
86
    int64_t permits = get_compaction_permits();
593
86
    data_dir->disks_compaction_score_increment(permits);
594
86
    data_dir->disks_compaction_num_increment(1);
595
596
88
    auto record_compaction_stats = [&](const doris::Exception& ex) {
597
88
        _tablet->compaction_count.fetch_add(1, std::memory_order_relaxed);
598
88
        data_dir->disks_compaction_score_increment(-permits);
599
88
        data_dir->disks_compaction_num_increment(-1);
600
88
    };
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
86
    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
88
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(execute_compact_impl(permits), on_compact_impl_failure);
610
    // Only reached on success (macro returns on failure).
611
88
    record_compaction_stats(doris::Exception());
612
613
88
    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
88
    DorisMetrics::instance()->local_compaction_read_rows_total->increment(_input_row_num);
631
88
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(
632
88
            _input_rowsets_total_size);
633
634
88
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact", Status::OK());
635
636
88
    DorisMetrics::instance()->local_compaction_write_rows_total->increment(
637
88
            _output_rowset->num_rows());
638
88
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
639
88
            _output_rowset->total_disk_size());
640
641
88
    _load_segment_to_cache();
642
88
    submit_profile_record(true, profile_start_time_ms);
643
88
    return Status::OK();
644
88
}
645
646
88
Status CompactionMixin::execute_compact_impl(int64_t permits) {
647
88
    OlapStopWatch watch;
648
649
88
    if (handle_ordered_data_compaction()) {
650
10
        RETURN_IF_ERROR(modify_rowsets());
651
10
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
652
10
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
653
10
                  << ", disk=" << tablet()->data_dir()->path()
654
10
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
655
10
                  << ", output_row_num=" << _output_rowset->num_rows()
656
10
                  << ", input_rowsets_data_size=" << _input_rowsets_data_size
657
10
                  << ", input_rowsets_index_size=" << _input_rowsets_index_size
658
10
                  << ", input_rowsets_total_size=" << _input_rowsets_total_size
659
10
                  << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
660
10
                  << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
661
10
                  << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
662
10
                  << ". elapsed time=" << watch.get_elapse_second() << "s.";
663
10
        _state = CompactionState::SUCCESS;
664
10
        return Status::OK();
665
10
    }
666
78
    RETURN_IF_ERROR(build_basic_info());
667
668
78
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact_impl",
669
78
                                      Status::OK());
670
671
78
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
672
673
78
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
674
78
              << ", output_version=" << _output_version << ", permits: " << permits;
675
676
78
    RETURN_IF_ERROR(merge_input_rowsets());
677
678
    // Currently, updates are only made in the time_series.
679
78
    update_compaction_level();
680
681
78
    RETURN_IF_ERROR(modify_rowsets());
682
683
78
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
684
78
    DCHECK(cumu_policy);
685
78
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << _is_vertical
686
78
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
687
78
              << ", current_max_version=" << tablet()->max_version().second
688
78
              << ", disk=" << tablet()->data_dir()->path()
689
78
              << ", input_segments=" << _input_num_segments << ", input_rowsets_data_size="
690
78
              << PrettyPrinter::print_bytes(_input_rowsets_data_size)
691
78
              << ", input_rowsets_index_size="
692
78
              << PrettyPrinter::print_bytes(_input_rowsets_index_size)
693
78
              << ", input_rowsets_total_size="
694
78
              << PrettyPrinter::print_bytes(_input_rowsets_total_size)
695
78
              << ", output_rowset_data_size="
696
78
              << PrettyPrinter::print_bytes(_output_rowset->data_disk_size())
697
78
              << ", output_rowset_index_size="
698
78
              << PrettyPrinter::print_bytes(_output_rowset->index_disk_size())
699
78
              << ", output_rowset_total_size="
700
78
              << PrettyPrinter::print_bytes(_output_rowset->total_disk_size())
701
78
              << ", input_row_num=" << _input_row_num
702
78
              << ", output_row_num=" << _output_rowset->num_rows()
703
78
              << ", filtered_row_num=" << _stats.filtered_rows
704
78
              << ", merged_row_num=" << _stats.merged_rows
705
78
              << ". elapsed time=" << watch.get_elapse_second()
706
78
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
707
78
              << ", compact_row_per_second="
708
78
              << cast_set<double>(_input_row_num) / watch.get_elapse_second();
709
710
78
    _state = CompactionState::SUCCESS;
711
712
78
    return Status::OK();
713
78
}
714
715
9.51k
Status Compaction::do_inverted_index_compaction() {
716
9.51k
    const auto& ctx = _output_rs_writer->context();
717
9.51k
    if (!_enable_inverted_index_compaction || _input_row_num <= 0 ||
718
9.51k
        ctx.columns_to_do_index_compaction.empty()) {
719
9.29k
        return Status::OK();
720
9.29k
    }
721
722
220
    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
220
    DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_rowid_conversion_null",
735
220
                    { _stats.rowid_conversion = nullptr; })
736
220
    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
220
    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
220
    const auto& trans_vec = _stats.rowid_conversion->get_rowid_conversion_map();
756
757
    // source rowset,segment -> index_id
758
220
    const auto& src_seg_to_id_map = _stats.rowid_conversion->get_src_segment_to_id_map();
759
760
    // dest rowset id
761
220
    RowsetId dest_rowset_id = _stats.rowid_conversion->get_dst_rowset_id();
762
    // dest segment id -> num rows
763
220
    std::vector<uint32_t> dest_segment_num_rows;
764
220
    RETURN_IF_ERROR(_output_rs_writer->get_segment_num_rows(&dest_segment_num_rows));
765
766
220
    auto src_segment_num = src_seg_to_id_map.size();
767
220
    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
220
    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
218
    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
218
    std::unordered_map<RowsetId, Rowset*> rs_id_to_rowset_map;
833
1.35k
    for (auto&& rs : _input_rowsets) {
834
1.35k
        rs_id_to_rowset_map.emplace(rs->rowset_id(), rs.get());
835
1.35k
    }
836
837
    // src index dirs
838
218
    std::vector<std::unique_ptr<IndexFileReader>> index_file_readers(src_segment_num);
839
943
    for (const auto& m : src_seg_to_id_map) {
840
943
        const auto& [rowset_id, seg_id] = m.first;
841
842
943
        auto find_it = rs_id_to_rowset_map.find(rowset_id);
843
943
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_find_rowset_error",
844
943
                        { find_it = rs_id_to_rowset_map.end(); })
845
943
        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
943
        auto* rowset = find_it->second;
855
943
        auto fs = rowset->rowset_meta()->fs();
856
943
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_get_fs_error", { fs = nullptr; })
857
943
        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
943
        auto seg_path = rowset->segment_path(seg_id);
866
943
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_seg_path_nullptr", {
867
943
            seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
868
943
                    "do_inverted_index_compaction_seg_path_nullptr"));
869
943
        })
870
943
        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
943
        auto index_file_reader = std::make_unique<IndexFileReader>(
880
943
                fs,
881
943
                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path.value())},
882
943
                _cur_tablet_schema->get_inverted_index_storage_format(),
883
943
                rowset->rowset_meta()->inverted_index_file_info(seg_id), _tablet->tablet_id());
884
943
        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
885
943
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_init_inverted_index_file_reader",
886
943
                        {
887
943
                            st = Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
888
943
                                    "debug point: "
889
943
                                    "Compaction::do_inverted_index_compaction_init_inverted_index_"
890
943
                                    "file_reader error");
891
943
                        })
892
943
        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
943
        index_file_readers[m.second] = std::move(index_file_reader);
903
943
    }
904
905
    // dest index files
906
    // format: rowsetId_segmentId
907
218
    auto& inverted_index_file_writers =
908
218
            dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get())->index_file_writers();
909
218
    DBUG_EXECUTE_IF(
910
218
            "Compaction::do_inverted_index_compaction_inverted_index_file_writers_size_error",
911
218
            { inverted_index_file_writers.clear(); })
912
218
    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
218
    auto tmp_file_dir = ExecEnv::GetInstance()->get_tmp_file_dirs()->get_tmp_file_dir();
926
218
    auto index_tmp_path = tmp_file_dir / dest_rowset_id.to_string();
927
218
    LOG(INFO) << "start index compaction"
928
218
              << ". tablet=" << _tablet->tablet_id() << ", source index size=" << src_segment_num
929
218
              << ", destination index size=" << dest_segment_num << ".";
930
931
218
    Status status = Status::OK();
932
788
    for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
933
788
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
934
788
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
935
788
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_can_not_find_index_meta",
936
788
                        { index_metas.clear(); })
937
788
        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
796
        for (const auto& index_meta : index_metas) {
947
796
            std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
948
796
            try {
949
796
                std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>> src_idx_dirs(
950
796
                        src_segment_num);
951
3.68k
                for (int src_segment_id = 0; src_segment_id < src_segment_num; src_segment_id++) {
952
2.88k
                    auto res = index_file_readers[src_segment_id]->open(index_meta);
953
2.88k
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
954
2.88k
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
955
2.88k
                                "debug point: Compaction::open_index_file_reader error"));
956
2.88k
                    })
957
2.88k
                    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
2.88k
                    src_idx_dirs[src_segment_id] = std::move(res.value());
967
2.88k
                }
968
1.70k
                for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
969
907
                     dest_segment_id++) {
970
907
                    auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
971
907
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
972
907
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
973
907
                                "debug point: Compaction::open_inverted_index_file_writer error"));
974
907
                    })
975
907
                    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
907
                    dest_index_dirs[dest_segment_id] = res.value().get();
987
907
                }
988
796
                auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
989
796
                                         index_tmp_path.native(), trans_vec, dest_segment_num_rows);
990
796
                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
796
            } 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
796
        }
1002
788
    }
1003
1004
    // check index compaction status. If status is not ok, we should return error and end this compaction round.
1005
218
    if (!status.ok()) {
1006
1
        return status;
1007
1
    }
1008
218
    LOG(INFO) << "succeed to do index compaction"
1009
217
              << ". tablet=" << _tablet->tablet_id()
1010
217
              << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
1011
1012
217
    return Status::OK();
1013
218
}
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.78k
void Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
1037
7.78k
    for (const auto& index : _cur_tablet_schema->inverted_indexes()) {
1038
4.01k
        auto col_unique_ids = index->col_unique_ids();
1039
        // check if column unique ids is empty to avoid crash
1040
4.01k
        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.00k
        auto col_unique_id = col_unique_ids[0];
1047
4.00k
        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.00k
        if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
1054
2.29k
            continue;
1055
2.29k
        }
1056
1057
        // if index properties are different, index compaction maybe needs to be skipped.
1058
1.71k
        bool is_continue = false;
1059
1.71k
        std::optional<std::map<std::string, std::string>> first_properties;
1060
12.0k
        for (const auto& rowset : _input_rowsets) {
1061
12.0k
            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.0k
            auto it = std::find_if(tablet_indexs.begin(), tablet_indexs.end(),
1064
12.1k
                                   [&index](const auto& tablet_index) {
1065
12.1k
                                       return tablet_index->index_id() == index->index_id();
1066
12.1k
                                   });
1067
12.0k
            if (it != tablet_indexs.end()) {
1068
12.0k
                const auto* tablet_index = *it;
1069
12.0k
                auto properties = tablet_index->properties();
1070
12.0k
                if (!first_properties.has_value()) {
1071
1.71k
                    first_properties = properties;
1072
10.3k
                } else {
1073
10.3k
                    DBUG_EXECUTE_IF(
1074
10.3k
                            "Compaction::do_inverted_index_compaction_index_properties_different",
1075
10.3k
                            { properties.emplace("dummy_key", "dummy_value"); })
1076
10.3k
                    if (properties != first_properties.value()) {
1077
3
                        is_continue = true;
1078
3
                        break;
1079
3
                    }
1080
10.3k
                }
1081
12.0k
            } else {
1082
5
                is_continue = true;
1083
5
                break;
1084
5
            }
1085
12.0k
        }
1086
1.71k
        if (is_continue) {
1087
5
            continue;
1088
5
        }
1089
10.1k
        auto has_inverted_index = [&](const RowsetSharedPtr& src_rs) {
1090
10.1k
            auto* rowset = static_cast<BetaRowset*>(src_rs.get());
1091
10.1k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_is_skip_index_compaction",
1092
10.1k
                            { rowset->set_skip_index_compaction(col_unique_id); })
1093
10.1k
            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.1k
            auto fs = rowset->rowset_meta()->fs();
1101
10.1k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_get_fs_error",
1102
10.1k
                            { fs = nullptr; })
1103
10.1k
            if (!fs) {
1104
414
                LOG(WARNING) << "get fs failed, resource_id="
1105
414
                             << rowset->rowset_meta()->resource_id();
1106
414
                return false;
1107
414
            }
1108
1109
9.76k
            auto index_metas = rowset->tablet_schema()->inverted_indexs(col_unique_id);
1110
9.76k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_meta_nullptr",
1111
9.76k
                            { index_metas.clear(); })
1112
9.76k
            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
9.97k
            for (const auto& index_meta : index_metas) {
1118
13.3k
                for (auto i = 0; i < rowset->num_segments(); i++) {
1119
                    // TODO: inverted_index_path
1120
3.35k
                    auto seg_path = rowset->segment_path(i);
1121
3.35k
                    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_seg_path_nullptr", {
1122
3.35k
                        seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
1123
3.35k
                                "construct_skip_inverted_index_seg_path_nullptr"));
1124
3.35k
                    })
1125
3.35k
                    if (!seg_path) {
1126
0
                        LOG(WARNING) << seg_path.error();
1127
0
                        return false;
1128
0
                    }
1129
1130
3.35k
                    std::string index_file_path;
1131
3.35k
                    try {
1132
3.35k
                        auto index_file_reader = std::make_unique<IndexFileReader>(
1133
3.35k
                                fs,
1134
3.35k
                                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
1135
3.35k
                                        seg_path.value())},
1136
3.35k
                                _cur_tablet_schema->get_inverted_index_storage_format(),
1137
3.35k
                                rowset->rowset_meta()->inverted_index_file_info(i),
1138
3.35k
                                _tablet->tablet_id());
1139
3.35k
                        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
1140
3.35k
                        index_file_path = index_file_reader->get_index_file_path(index_meta);
1141
3.35k
                        DBUG_EXECUTE_IF(
1142
3.35k
                                "Compaction::construct_skip_inverted_index_index_file_reader_init_"
1143
3.35k
                                "status_not_ok",
1144
3.35k
                                {
1145
3.35k
                                    st = Status::Error<ErrorCode::INTERNAL_ERROR>(
1146
3.35k
                                            "debug point: "
1147
3.35k
                                            "construct_skip_inverted_index_index_file_reader_init_"
1148
3.35k
                                            "status_"
1149
3.35k
                                            "not_ok");
1150
3.35k
                                })
1151
3.35k
                        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.35k
                        auto result = index_file_reader->open(index_meta);
1158
3.35k
                        DBUG_EXECUTE_IF(
1159
3.35k
                                "Compaction::construct_skip_inverted_index_index_file_reader_open_"
1160
3.35k
                                "error",
1161
3.35k
                                {
1162
3.35k
                                    result = ResultError(
1163
3.35k
                                            Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1164
3.35k
                                                    "CLuceneError occur when open idx file"));
1165
3.35k
                                })
1166
3.35k
                        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.35k
                        auto reader = std::move(result.value());
1172
3.35k
                        std::vector<std::string> files;
1173
3.35k
                        reader->list(&files);
1174
3.35k
                        reader->close();
1175
3.35k
                        DBUG_EXECUTE_IF(
1176
3.35k
                                "Compaction::construct_skip_inverted_index_index_reader_close_"
1177
3.35k
                                "error",
1178
3.35k
                                { _CLTHROWA(CL_ERR_IO, "debug point: reader close error"); })
1179
1180
3.35k
                        DBUG_EXECUTE_IF(
1181
3.35k
                                "Compaction::construct_skip_inverted_index_index_files_count",
1182
3.35k
                                { 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.35k
                        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.35k
                    } 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.35k
                }
1200
9.97k
            }
1201
9.76k
            return true;
1202
9.76k
        };
1203
1204
1.70k
        bool all_have_inverted_index = std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1205
1.70k
                                                   std::move(has_inverted_index));
1206
1207
1.70k
        if (all_have_inverted_index) {
1208
1.29k
            ctx.columns_to_do_index_compaction.insert(col_unique_id);
1209
1.29k
        }
1210
1.70k
    }
1211
7.78k
}
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
147
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
147
    {
1245
147
        std::shared_lock meta_rlock(_tablet->get_header_lock());
1246
147
        if (_tablet->tablet_state() != TABLET_NOTREADY) {
1247
146
            return Status::OK();
1248
146
        }
1249
147
    }
1250
1
    OlapStopWatch watch;
1251
1
    std::vector<RowsetSharedPtr> rowsets;
1252
1
    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
1
    LOG(INFO) << "finish update delete bitmap for tablet: " << _tablet->tablet_id()
1262
1
              << ", rowsets: " << _input_rowsets.size() << ", cost: " << watch.get_elapse_time_us()
1263
1
              << "(us)";
1264
1
    return Status::OK();
1265
1
}
1266
1267
129
Status CompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1268
    // only do index compaction for dup_keys and unique_keys with mow enabled
1269
129
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1270
112
                                                _tablet->enable_unique_key_merge_on_write()) ||
1271
112
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1272
112
        construct_index_compaction_columns(ctx);
1273
112
    }
1274
129
    ctx.version = _output_version;
1275
129
    ctx.rowset_state = VISIBLE;
1276
129
    ctx.segments_overlap = NONOVERLAPPING;
1277
129
    ctx.tablet_schema = _cur_tablet_schema;
1278
129
    ctx.newest_write_timestamp = _newest_write_timestamp;
1279
129
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1280
129
    ctx.compaction_type = compaction_type();
1281
129
    ctx.allow_packed_file = false;
1282
129
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1283
129
    _pending_rs_guard = _engine.add_pending_rowset(ctx);
1284
129
    return Status::OK();
1285
129
}
1286
1287
88
Status CompactionMixin::modify_rowsets() {
1288
88
    std::vector<RowsetSharedPtr> output_rowsets;
1289
88
    output_rowsets.push_back(_output_rowset);
1290
1291
88
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1292
88
        _tablet->enable_unique_key_merge_on_write()) {
1293
50
        Version version = tablet()->max_version();
1294
50
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
1295
50
        std::unique_ptr<RowLocationSet> missed_rows;
1296
50
        if ((config::enable_missing_rows_correctness_check ||
1297
50
             config::enable_mow_compaction_correctness_check_core ||
1298
50
             config::enable_mow_compaction_correctness_check_fail) &&
1299
50
            !_allow_delete_in_cumu_compaction &&
1300
50
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1301
50
            missed_rows = std::make_unique<RowLocationSet>();
1302
50
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
1303
50
        }
1304
50
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1305
50
        if (config::enable_rowid_conversion_correctness_check &&
1306
50
            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
50
        std::size_t missed_rows_size = 0;
1316
50
        tablet()->calc_compaction_output_rowset_delete_bitmap(
1317
50
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1318
50
                location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1319
50
                &output_rowset_delete_bitmap);
1320
50
        if (missed_rows) {
1321
50
            missed_rows_size = missed_rows->size();
1322
50
            std::size_t merged_missed_rows_size = _stats.merged_rows;
1323
50
            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
50
            bool need_to_check_missed_rows = true;
1340
50
            {
1341
50
                std::shared_lock rlock(_tablet->get_header_lock());
1342
50
                need_to_check_missed_rows =
1343
50
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1344
536
                                    [&](const RowsetSharedPtr& rowset) {
1345
536
                                        return tablet()->rowset_exists_unlocked(rowset);
1346
536
                                    });
1347
50
            }
1348
1349
50
            if (_tablet->tablet_state() == TABLET_RUNNING &&
1350
50
                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
50
        }
1386
1387
50
        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
50
        {
1393
50
            std::lock_guard<std::mutex> wrlock_(tablet()->get_rowset_update_lock());
1394
50
            std::lock_guard wrlock(_tablet->get_header_lock());
1395
50
            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
50
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1402
50
            _engine.txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1403
50
                    *tablet(), &commit_tablet_txn_info_vec);
1404
1405
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1406
50
            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
50
            tablet()->calc_compaction_output_rowset_delete_bitmap(
1437
50
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1438
50
                    missed_rows.get(), location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1439
50
                    &output_rowset_delete_bitmap);
1440
1441
50
            if (location_map) {
1442
0
                RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1443
0
            }
1444
1445
50
            tablet()->merge_delete_bitmap(output_rowset_delete_bitmap);
1446
50
            RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1447
50
        }
1448
50
    } else {
1449
38
        std::lock_guard wrlock(_tablet->get_header_lock());
1450
38
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1451
38
        RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1452
38
    }
1453
1454
88
    if (config::tablet_rowset_stale_sweep_by_size &&
1455
88
        _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
88
    int64_t cur_max_version = 0;
1461
88
    {
1462
88
        std::shared_lock rlock(_tablet->get_header_lock());
1463
88
        cur_max_version = _tablet->max_version_unlocked();
1464
88
        tablet()->save_meta();
1465
88
    }
1466
88
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1467
88
        _tablet->enable_unique_key_merge_on_write()) {
1468
50
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1469
50
                tablet()->data_dir(), _tablet->tablet_id(), cur_max_version);
1470
50
        if (!st.ok()) {
1471
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1472
0
        }
1473
50
    }
1474
88
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset",
1475
88
                    { tablet()->delete_expired_stale_rowset(); });
1476
88
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
1477
88
    return Status::OK();
1478
88
}
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
78
void CompactionMixin::update_compaction_level() {
1496
78
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
1497
78
    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
78
}
1503
1504
9.47k
Status Compaction::check_correctness() {
1505
    // 1. check row number
1506
9.47k
    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.47k
    RETURN_IF_ERROR(vectorized::schema_util::VariantCompactionUtil::check_path_stats(
1515
9.47k
            _input_rowsets, _output_rowset, _tablet));
1516
9.47k
    return Status::OK();
1517
9.47k
}
1518
1519
198
int64_t CompactionMixin::get_compaction_permits() {
1520
198
    int64_t permits = 0;
1521
1.93k
    for (auto&& rowset : _input_rowsets) {
1522
1.93k
        permits += rowset->rowset_meta()->get_compaction_score();
1523
1.93k
    }
1524
198
    return permits;
1525
198
}
1526
1527
30
int64_t CompactionMixin::calc_input_rowsets_total_size() const {
1528
30
    int64_t input_rowsets_total_size = 0;
1529
88
    for (const auto& rowset : _input_rowsets) {
1530
88
        const auto& rowset_meta = rowset->rowset_meta();
1531
88
        auto total_size = rowset_meta->total_disk_size();
1532
88
        input_rowsets_total_size += total_size;
1533
88
    }
1534
30
    return input_rowsets_total_size;
1535
30
}
1536
1537
30
int64_t CompactionMixin::calc_input_rowsets_row_num() const {
1538
30
    int64_t input_rowsets_row_num = 0;
1539
88
    for (const auto& rowset : _input_rowsets) {
1540
88
        const auto& rowset_meta = rowset->rowset_meta();
1541
88
        auto total_size = rowset_meta->total_disk_size();
1542
88
        input_rowsets_row_num += total_size;
1543
88
    }
1544
30
    return input_rowsets_row_num;
1545
30
}
1546
1547
9.30k
void Compaction::_load_segment_to_cache() {
1548
    // Load new rowset's segments to cache.
1549
9.30k
    SegmentCacheHandle handle;
1550
9.30k
    auto st = SegmentLoader::instance()->load_segments(
1551
9.30k
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1552
9.30k
    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.30k
}
1558
1559
9.29k
Status CloudCompactionMixin::build_basic_info() {
1560
9.29k
    _output_version =
1561
9.29k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
1562
1563
9.29k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
1564
1565
9.29k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
1566
9.29k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
1567
75.2k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
1568
9.29k
    if (is_index_change_compaction()) {
1569
504
        RETURN_IF_ERROR(rebuild_tablet_schema());
1570
8.79k
    } else {
1571
8.79k
        _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
1572
8.79k
    }
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.35k
    if (_enable_vertical_compact_variant_subcolumns) {
1577
9.35k
        RETURN_IF_ERROR(
1578
9.35k
                vectorized::schema_util::VariantCompactionUtil::get_extended_compaction_schema(
1579
9.35k
                        _input_rowsets, _cur_tablet_schema));
1580
9.35k
    }
1581
9.29k
    return Status::OK();
1582
9.29k
}
1583
1584
9.31k
int64_t CloudCompactionMixin::get_compaction_permits() {
1585
9.31k
    int64_t permits = 0;
1586
74.2k
    for (auto&& rowset : _input_rowsets) {
1587
74.2k
        permits += rowset->rowset_meta()->get_compaction_score();
1588
74.2k
    }
1589
9.31k
    return permits;
1590
9.31k
}
1591
1592
CloudCompactionMixin::CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
1593
                                           const std::string& label)
1594
84.1k
        : Compaction(tablet, label), _engine(engine) {
1595
84.1k
    auto uuid = UUIDGenerator::instance()->next_uuid();
1596
84.1k
    std::stringstream ss;
1597
84.1k
    ss << uuid;
1598
84.1k
    _uuid = ss.str();
1599
84.1k
}
1600
1601
9.26k
Status CloudCompactionMixin::execute_compact_impl(int64_t permits) {
1602
9.26k
    OlapStopWatch watch;
1603
1604
9.26k
    RETURN_IF_ERROR(build_basic_info());
1605
1606
9.26k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
1607
9.26k
              << ", output_version=" << _output_version << ", permits: " << permits;
1608
1609
9.26k
    RETURN_IF_ERROR(merge_input_rowsets());
1610
1611
9.26k
    DBUG_EXECUTE_IF("CloudFullCompaction::modify_rowsets.wrong_rowset_id", {
1612
9.26k
        DCHECK(compaction_type() == ReaderType::READER_FULL_COMPACTION);
1613
9.26k
        RowsetId id;
1614
9.26k
        id.version = 2;
1615
9.26k
        id.hi = _output_rowset->rowset_meta()->rowset_id().hi + ((int64_t)(1) << 56);
1616
9.26k
        id.mi = _output_rowset->rowset_meta()->rowset_id().mi;
1617
9.26k
        id.lo = _output_rowset->rowset_meta()->rowset_id().lo;
1618
9.26k
        _output_rowset->rowset_meta()->set_rowset_id(id);
1619
9.26k
        LOG(INFO) << "[Debug wrong rowset id]:"
1620
9.26k
                  << _output_rowset->rowset_meta()->rowset_id().to_string();
1621
9.26k
    })
1622
1623
    // Currently, updates are only made in the time_series.
1624
9.26k
    update_compaction_level();
1625
1626
9.26k
    RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get(), _uuid,
1627
9.26k
                                                     _tablet->table_id()));
1628
1629
    // 4. modify rowsets in memory
1630
9.26k
    RETURN_IF_ERROR(modify_rowsets());
1631
1632
    // update compaction status data
1633
9.16k
    auto tablet = std::static_pointer_cast<CloudTablet>(_tablet);
1634
9.16k
    tablet->local_read_time_us.fetch_add(_stats.cloud_local_read_time);
1635
9.16k
    tablet->remote_read_time_us.fetch_add(_stats.cloud_remote_read_time);
1636
9.16k
    tablet->exec_compaction_time_us.fetch_add(watch.get_elapse_time_us());
1637
1638
9.16k
    return Status::OK();
1639
9.26k
}
1640
1641
9.26k
int64_t CloudCompactionMixin::initiator() const {
1642
9.26k
    return HashUtil::hash64(_uuid.data(), _uuid.size(), 0) & std::numeric_limits<int64_t>::max();
1643
9.26k
}
1644
1645
namespace cloud {
1646
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
1647
9.49k
                                    int64_t& truncated_size_bytes) {
1648
9.49k
    if (rowsets.empty()) {
1649
1
        kept_size_bytes = 0;
1650
1
        truncated_size_bytes = 0;
1651
1
        return 0;
1652
1
    }
1653
1654
9.49k
    int64_t max_size = config::compaction_txn_max_size_bytes;
1655
9.49k
    int64_t cumulative_meta_size = 0;
1656
9.49k
    size_t keep_count = 0;
1657
1658
86.1k
    for (size_t i = 0; i < rowsets.size(); ++i) {
1659
76.6k
        const auto& rs = rowsets[i];
1660
1661
        // Estimate rowset meta size using doris_rowset_meta_to_cloud
1662
76.6k
        auto cloud_meta = cloud::doris_rowset_meta_to_cloud(rs->rowset_meta()->get_rowset_pb(true));
1663
76.6k
        int64_t rowset_meta_size = cloud_meta.ByteSizeLong();
1664
1665
76.6k
        cumulative_meta_size += rowset_meta_size;
1666
1667
76.6k
        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.6k
        keep_count++;
1674
76.6k
    }
1675
1676
    // Ensure at least 1 rowset is kept
1677
9.49k
    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.49k
    int64_t truncated_total_size = 0;
1687
9.49k
    size_t truncated_count = rowsets.size() - keep_count;
1688
9.49k
    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.49k
    kept_size_bytes = cumulative_meta_size;
1698
9.49k
    truncated_size_bytes = truncated_total_size;
1699
9.49k
    return truncated_count;
1700
9.49k
}
1701
} // namespace cloud
1702
1703
8.97k
size_t CloudCompactionMixin::apply_txn_size_truncation_and_log(const std::string& compaction_name) {
1704
8.97k
    if (_input_rowsets.empty()) {
1705
1
        return 0;
1706
1
    }
1707
1708
8.97k
    int64_t original_count = _input_rowsets.size();
1709
8.97k
    int64_t original_start_version = _input_rowsets.front()->start_version();
1710
8.97k
    int64_t original_end_version = _input_rowsets.back()->end_version();
1711
1712
8.97k
    int64_t final_size = 0;
1713
8.97k
    int64_t truncated_size = 0;
1714
8.97k
    size_t truncated_count =
1715
8.97k
            cloud::truncate_rowsets_by_txn_size(_input_rowsets, final_size, truncated_size);
1716
1717
8.97k
    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.97k
    return truncated_count;
1734
8.97k
}
1735
1736
9.22k
Status CloudCompactionMixin::execute_compact() {
1737
9.22k
    int64_t profile_start_time_ms = UnixMillis();
1738
9.22k
    TEST_INJECTION_POINT("Compaction::do_compaction");
1739
9.22k
    int64_t permits = get_compaction_permits();
1740
9.22k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
1741
9.22k
            execute_compact_impl(permits), [&](const doris::Exception& ex) {
1742
9.22k
                auto st = garbage_collection();
1743
9.22k
                if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1744
9.22k
                    _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.22k
                    _engine.meta_mgr().remove_delete_bitmap_update_lock(
1750
9.22k
                            _tablet->table_id(), COMPACTION_DELETE_BITMAP_LOCK_ID, initiator(),
1751
9.22k
                            _tablet->tablet_id());
1752
9.22k
                }
1753
9.22k
                submit_profile_record(false, profile_start_time_ms, ex.what());
1754
9.28k
            });
1755
1756
9.28k
    DorisMetrics::instance()->remote_compaction_read_rows_total->increment(_input_row_num);
1757
9.28k
    DorisMetrics::instance()->remote_compaction_write_rows_total->increment(
1758
9.28k
            _output_rowset->num_rows());
1759
9.28k
    DorisMetrics::instance()->remote_compaction_write_bytes_total->increment(
1760
9.28k
            _output_rowset->total_disk_size());
1761
1762
9.28k
    _load_segment_to_cache();
1763
9.28k
    submit_profile_record(true, profile_start_time_ms);
1764
9.28k
    return Status::OK();
1765
9.22k
}
1766
1767
0
Status CloudCompactionMixin::modify_rowsets() {
1768
0
    return Status::OK();
1769
0
}
1770
1771
9.40k
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.8k
    for (const auto& rowset : std::ranges::reverse_view(_input_rowsets)) {
1782
21.8k
        const auto& resource_id = rowset->rowset_meta()->resource_id();
1783
1784
21.8k
        if (!resource_id.empty()) {
1785
7.24k
            ctx.storage_resource = *DORIS_TRY(rowset->rowset_meta()->remote_storage_resource());
1786
7.24k
            return Status::OK();
1787
7.24k
        }
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.5k
        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.5k
    }
1807
1808
2.15k
    return Status::OK();
1809
9.40k
}
1810
1811
9.40k
Status CloudCompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1812
    // only do index compaction for dup_keys and unique_keys with mow enabled
1813
9.40k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1814
8.89k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1815
8.89k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1816
7.67k
        construct_index_compaction_columns(ctx);
1817
7.67k
    }
1818
1819
    // Use the storage resource of the previous rowset.
1820
9.40k
    RETURN_IF_ERROR(set_storage_resource_from_input_rowsets(ctx));
1821
1822
9.40k
    ctx.txn_id = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
1823
9.40k
                 std::numeric_limits<int64_t>::max(); // MUST be positive
1824
9.40k
    ctx.txn_expiration = _expiration;
1825
1826
9.40k
    ctx.version = _output_version;
1827
9.40k
    ctx.rowset_state = VISIBLE;
1828
9.40k
    ctx.segments_overlap = NONOVERLAPPING;
1829
9.40k
    ctx.tablet_schema = _cur_tablet_schema;
1830
9.40k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1831
9.40k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1832
9.40k
    ctx.compaction_type = compaction_type();
1833
9.40k
    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.40k
    ctx.write_file_cache = should_cache_compaction_output();
1840
9.40k
    ctx.file_cache_ttl_sec = _tablet->ttl_seconds();
1841
9.40k
    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.40k
    ctx.compaction_output_write_index_only = should_enable_compaction_cache_index_only(
1845
9.40k
            ctx.write_file_cache, compaction_type(),
1846
9.40k
            config::enable_file_cache_write_base_compaction_index_only,
1847
9.40k
            config::enable_file_cache_write_cumu_compaction_index_only);
1848
1849
9.40k
    ctx.tablet = _tablet;
1850
9.40k
    ctx.job_id = _uuid;
1851
1852
9.40k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1853
9.40k
    RETURN_IF_ERROR(
1854
9.40k
            _engine.meta_mgr().prepare_rowset(*_output_rs_writer->rowset_meta().get(), _uuid));
1855
9.40k
    return Status::OK();
1856
9.40k
}
1857
1858
92
Status CloudCompactionMixin::garbage_collection() {
1859
92
    if (!config::enable_file_cache) {
1860
0
        return Status::OK();
1861
0
    }
1862
92
    if (_output_rs_writer) {
1863
92
        auto* beta_rowset_writer = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get());
1864
92
        DCHECK(beta_rowset_writer);
1865
92
        for (const auto& [_, file_writer] : beta_rowset_writer->get_file_writers()) {
1866
62
            auto file_key = io::BlockFileCache::hash(file_writer->path().filename().native());
1867
62
            auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1868
62
            file_cache->remove_if_cached_async(file_key);
1869
62
        }
1870
92
        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
92
    }
1878
92
    return Status::OK();
1879
92
}
1880
1881
9.37k
void CloudCompactionMixin::update_compaction_level() {
1882
    // for index change compaction, compaction level should not changed.
1883
    // because input rowset num is 1.
1884
9.37k
    if (is_index_change_compaction()) {
1885
502
        DCHECK(_input_rowsets.size() == 1);
1886
502
        _output_rowset->rowset_meta()->set_compaction_level(
1887
502
                _input_rowsets.back()->rowset_meta()->compaction_level());
1888
8.87k
    } else {
1889
8.87k
        auto compaction_policy = _tablet->tablet_meta()->compaction_policy();
1890
8.87k
        auto cumu_policy = _engine.cumu_compaction_policy(compaction_policy);
1891
8.90k
        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.87k
    }
1897
9.37k
}
1898
1899
// should skip hole rowsets, ortherwise the count will be wrong in ms
1900
9.37k
int64_t CloudCompactionMixin::num_input_rowsets() const {
1901
9.37k
    int64_t count = 0;
1902
75.7k
    for (const auto& r : _input_rowsets) {
1903
75.7k
        if (!r->is_hole_rowset()) {
1904
29.3k
            count++;
1905
29.3k
        }
1906
75.7k
    }
1907
9.37k
    return count;
1908
9.37k
}
1909
1910
9.42k
bool CloudCompactionMixin::should_cache_compaction_output() {
1911
9.42k
    if (config::enable_file_cache_write_index_file_only) {
1912
1
        return false;
1913
1
    }
1914
1915
9.42k
    if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1916
9.26k
        return true;
1917
9.26k
    }
1918
1919
159
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
1920
77
        double input_rowsets_hit_cache_ratio = 0.0;
1921
1922
77
        int64_t _input_rowsets_cached_size =
1923
77
                _input_rowsets_cached_data_size + _input_rowsets_cached_index_size;
1924
77
        if (_input_rowsets_total_size > 0) {
1925
63
            input_rowsets_hit_cache_ratio =
1926
63
                    double(_input_rowsets_cached_size) / double(_input_rowsets_total_size);
1927
63
        }
1928
1929
77
        LOG(INFO) << "CloudBaseCompaction should_cache_compaction_output"
1930
77
                  << ", tablet_id=" << _tablet->tablet_id()
1931
77
                  << ", input_rowsets_hit_cache_ratio=" << input_rowsets_hit_cache_ratio
1932
77
                  << ", _input_rowsets_cached_size=" << _input_rowsets_cached_size
1933
77
                  << ", _input_rowsets_total_size=" << _input_rowsets_total_size
1934
77
                  << ", enable_file_cache_keep_base_compaction_output="
1935
77
                  << config::enable_file_cache_keep_base_compaction_output
1936
77
                  << ", file_cache_keep_base_compaction_output_min_hit_ratio="
1937
77
                  << config::file_cache_keep_base_compaction_output_min_hit_ratio;
1938
1939
77
        if (config::enable_file_cache_keep_base_compaction_output) {
1940
1
            return true;
1941
1
        }
1942
1943
76
        if (input_rowsets_hit_cache_ratio >
1944
76
            config::file_cache_keep_base_compaction_output_min_hit_ratio) {
1945
56
            return true;
1946
56
        }
1947
76
    }
1948
102
    return false;
1949
159
}
1950
1951
#include "common/compile_check_end.h"
1952
} // namespace doris