Coverage Report

Created: 2026-07-02 13:17

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