Coverage Report

Created: 2026-02-03 14:27

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