Coverage Report

Created: 2026-06-09 15:07

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