Coverage Report

Created: 2026-01-05 10:23

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