Coverage Report

Created: 2026-04-10 18:24

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