Coverage Report

Created: 2025-12-31 16:56

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
93
                    const RowsetSharedPtr& rhs) {
95
93
    size_t min_tidy_size = config::ordered_data_compaction_min_segment_size;
96
93
    if (rhs->num_segments() == 0) {
97
20
        return true;
98
20
    }
99
73
    if (rhs->is_segments_overlapping()) {
100
0
        return false;
101
0
    }
102
    // check segment size
103
73
    auto* beta_rowset = reinterpret_cast<BetaRowset*>(rhs.get());
104
73
    std::vector<size_t> segments_size;
105
73
    RETURN_FALSE_IF_ERROR(beta_rowset->get_segments_size(&segments_size));
106
80
    for (auto segment_size : segments_size) {
107
        // is segment is too small, need to do compaction
108
80
        if (segment_size < min_tidy_size) {
109
34
            return false;
110
34
        }
111
80
    }
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
220k
                  MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, label)),
132
220k
          _tablet(std::move(tablet)),
133
220k
          _is_vertical(config::enable_vertical_compaction),
134
220k
          _allow_delete_in_cumu_compaction(config::enable_delete_when_cumu_compaction),
135
          _enable_vertical_compact_variant_subcolumns(
136
220k
                  config::enable_vertical_compact_variant_subcolumns),
137
220k
          _enable_inverted_index_compaction(config::inverted_index_compaction_enable) {
138
220k
    init_profile(label);
139
220k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
140
220k
    _rowid_conversion = std::make_unique<RowIdConversion>();
141
220k
}
142
143
220k
Compaction::~Compaction() {
144
220k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
145
220k
    _output_rs_writer.reset();
146
220k
    _tablet.reset();
147
220k
    _input_rowsets.clear();
148
220k
    _output_rowset.reset();
149
220k
    _cur_tablet_schema.reset();
150
220k
    _rowid_conversion.reset();
151
220k
}
152
153
220k
void Compaction::init_profile(const std::string& label) {
154
220k
    _profile = std::make_unique<RuntimeProfile>(label);
155
156
220k
    _input_rowsets_data_size_counter =
157
220k
            ADD_COUNTER(_profile, "input_rowsets_data_size", TUnit::BYTES);
158
220k
    _input_rowsets_counter = ADD_COUNTER(_profile, "input_rowsets_count", TUnit::UNIT);
159
220k
    _input_row_num_counter = ADD_COUNTER(_profile, "input_row_num", TUnit::UNIT);
160
220k
    _input_segments_num_counter = ADD_COUNTER(_profile, "input_segments_num", TUnit::UNIT);
161
220k
    _merged_rows_counter = ADD_COUNTER(_profile, "merged_rows", TUnit::UNIT);
162
220k
    _filtered_rows_counter = ADD_COUNTER(_profile, "filtered_rows", TUnit::UNIT);
163
220k
    _output_rowset_data_size_counter =
164
220k
            ADD_COUNTER(_profile, "output_rowset_data_size", TUnit::BYTES);
165
220k
    _output_row_num_counter = ADD_COUNTER(_profile, "output_row_num", TUnit::UNIT);
166
220k
    _output_segments_num_counter = ADD_COUNTER(_profile, "output_segments_num", TUnit::UNIT);
167
220k
    _merge_rowsets_latency_timer = ADD_TIMER(_profile, "merge_rowsets_latency");
168
220k
}
169
170
17.7k
int64_t Compaction::merge_way_num() {
171
17.7k
    int64_t way_num = 0;
172
134k
    for (auto&& rowset : _input_rowsets) {
173
134k
        way_num += rowset->rowset_meta()->get_merge_way_num();
174
134k
    }
175
176
17.7k
    return way_num;
177
17.7k
}
178
179
17.9k
Status Compaction::merge_input_rowsets() {
180
17.9k
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
181
17.9k
    input_rs_readers.reserve(_input_rowsets.size());
182
135k
    for (auto& rowset : _input_rowsets) {
183
135k
        RowsetReaderSharedPtr rs_reader;
184
135k
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
185
135k
        input_rs_readers.push_back(std::move(rs_reader));
186
135k
    }
187
188
17.9k
    RowsetWriterContext ctx;
189
17.9k
    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
17.9k
    if (!ctx.columns_to_do_index_compaction.empty() ||
196
17.9k
        (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
197
17.4k
         _tablet->enable_unique_key_merge_on_write())) {
198
5.95k
        _stats.rowid_conversion = _rowid_conversion.get();
199
5.95k
    }
200
201
17.9k
    int64_t way_num = merge_way_num();
202
203
17.9k
    Status res;
204
17.9k
    {
205
17.9k
        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
17.9k
        if (_is_vertical && !_tablet->tablet_schema()->has_seq_map()) {
209
17.9k
            if (!_tablet->tablet_schema()->cluster_key_uids().empty()) {
210
179
                RETURN_IF_ERROR(update_delete_bitmap());
211
179
            }
212
17.9k
            res = Merger::vertical_merge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
213
17.9k
                                                 input_rs_readers, _output_rs_writer.get(),
214
17.9k
                                                 cast_set<uint32_t>(get_avg_segment_rows()),
215
17.9k
                                                 way_num, &_stats);
216
17.9k
        } else {
217
44
            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
44
            res = Merger::vmerge_rowsets(_tablet, compaction_type(), *_cur_tablet_schema,
222
44
                                         input_rs_readers, _output_rs_writer.get(), &_stats);
223
44
        }
224
225
17.9k
        _tablet->last_compaction_status = res;
226
17.9k
        if (!res.ok()) {
227
0
            return res;
228
0
        }
229
        // 2. Merge the remaining inverted index files of the string type
230
17.9k
        RETURN_IF_ERROR(do_inverted_index_compaction());
231
17.9k
    }
232
233
17.9k
    COUNTER_UPDATE(_merged_rows_counter, _stats.merged_rows);
234
17.9k
    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
17.9k
    RETURN_NOT_OK_STATUS_WITH_WARN(_output_rs_writer->build(_output_rowset),
238
17.9k
                                   fmt::format("rowset writer build failed. output_version: {}",
239
17.9k
                                               _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
17.9k
    if (_enable_vertical_compact_variant_subcolumns &&
246
17.9k
        (_cur_tablet_schema->num_variant_columns() > 0)) {
247
443
        _output_rowset->rowset_meta()->set_tablet_schema(
248
443
                _cur_tablet_schema->copy_without_variant_extracted_columns());
249
443
    }
250
251
    //RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get()));
252
17.9k
    set_delete_predicate_for_output_rowset();
253
254
17.9k
    _local_read_bytes_total = _stats.bytes_read_from_local;
255
17.9k
    _remote_read_bytes_total = _stats.bytes_read_from_remote;
256
17.9k
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(_local_read_bytes_total);
257
17.9k
    DorisMetrics::instance()->remote_compaction_read_bytes_total->increment(
258
17.9k
            _remote_read_bytes_total);
259
17.9k
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
260
17.9k
            _stats.cached_bytes_total);
261
262
17.9k
    COUNTER_UPDATE(_output_rowset_data_size_counter, _output_rowset->data_disk_size());
263
17.9k
    COUNTER_UPDATE(_output_row_num_counter, _output_rowset->num_rows());
264
17.9k
    COUNTER_UPDATE(_output_segments_num_counter, _output_rowset->num_segments());
265
266
17.9k
    return check_correctness();
267
17.9k
}
268
269
17.7k
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
17.7k
    if (_output_rowset->version().first > 2 &&
275
17.7k
        (_allow_delete_in_cumu_compaction || is_index_change_compaction())) {
276
159
        DeletePredicatePB delete_predicate;
277
159
        std::accumulate(_input_rowsets.begin(), _input_rowsets.end(), &delete_predicate,
278
160
                        [](DeletePredicatePB* delete_predicate, const RowsetSharedPtr& rs) {
279
160
                            if (rs->rowset_meta()->has_delete_predicate()) {
280
3
                                delete_predicate->MergeFrom(rs->rowset_meta()->delete_predicate());
281
3
                            }
282
160
                            return delete_predicate;
283
160
                        });
284
        // now version in delete_predicate is deprecated
285
159
        if (!delete_predicate.in_predicates().empty() ||
286
159
            !delete_predicate.sub_predicates_v2().empty() ||
287
159
            !delete_predicate.sub_predicates().empty()) {
288
3
            _output_rowset->rowset_meta()->set_delete_predicate(std::move(delete_predicate));
289
3
        }
290
159
    }
291
17.7k
}
292
293
17.7k
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
17.7k
    const auto& meta = _tablet->tablet_meta();
299
17.7k
    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
17.7k
    return std::min(config::vertical_compaction_max_segment_size /
307
17.7k
                            (_input_rowsets_data_size / (_input_row_num + 1) + 1),
308
17.7k
                    _input_row_num + 1);
309
17.7k
}
310
311
CompactionMixin::CompactionMixin(StorageEngine& engine, TabletSharedPtr tablet,
312
                                 const std::string& label)
313
82.1k
        : Compaction(tablet, label), _engine(engine) {}
314
315
82.1k
CompactionMixin::~CompactionMixin() {
316
82.1k
    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
82.1k
}
326
327
746k
Tablet* CompactionMixin::tablet() {
328
746k
    return static_cast<Tablet*>(_tablet.get());
329
746k
}
330
331
12
Status CompactionMixin::do_compact_ordered_rowsets() {
332
12
    RETURN_IF_ERROR(build_basic_info(true));
333
12
    RowsetWriterContext ctx;
334
12
    RETURN_IF_ERROR(construct_output_rowset_writer(ctx));
335
336
12
    LOG(INFO) << "start to do ordered data compaction, tablet=" << _tablet->tablet_id()
337
12
              << ", output_version=" << _output_version;
338
    // link data to new rowset
339
12
    auto seg_id = 0;
340
12
    bool segments_key_bounds_truncated {false};
341
12
    std::vector<KeyBoundsPB> segment_key_bounds;
342
46
    for (auto rowset : _input_rowsets) {
343
46
        RETURN_IF_ERROR(rowset->link_files_to(tablet()->tablet_path(),
344
46
                                              _output_rs_writer->rowset_id(), seg_id));
345
46
        seg_id += rowset->num_segments();
346
46
        segments_key_bounds_truncated |= rowset->is_segments_key_bounds_truncated();
347
46
        std::vector<KeyBoundsPB> key_bounds;
348
46
        RETURN_IF_ERROR(rowset->get_segments_key_bounds(&key_bounds));
349
46
        segment_key_bounds.insert(segment_key_bounds.end(), key_bounds.begin(), key_bounds.end());
350
46
    }
351
    // build output rowset
352
12
    RowsetMetaSharedPtr rowset_meta = std::make_shared<RowsetMeta>();
353
12
    rowset_meta->set_num_rows(_input_row_num);
354
12
    rowset_meta->set_total_disk_size(_input_rowsets_data_size + _input_rowsets_index_size);
355
12
    rowset_meta->set_data_disk_size(_input_rowsets_data_size);
356
12
    rowset_meta->set_index_disk_size(_input_rowsets_index_size);
357
12
    rowset_meta->set_empty(_input_row_num == 0);
358
12
    rowset_meta->set_num_segments(_input_num_segments);
359
12
    rowset_meta->set_segments_overlap(NONOVERLAPPING);
360
12
    rowset_meta->set_rowset_state(VISIBLE);
361
12
    rowset_meta->set_segments_key_bounds_truncated(segments_key_bounds_truncated);
362
12
    rowset_meta->set_segments_key_bounds(segment_key_bounds);
363
364
12
    _output_rowset = _output_rs_writer->manual_build(rowset_meta);
365
366
    // 2. check variant column path stats
367
12
    RETURN_IF_ERROR(vectorized::schema_util::VariantCompactionUtil::check_path_stats(
368
12
            _input_rowsets, _output_rowset, _tablet));
369
12
    return Status::OK();
370
12
}
371
372
75
Status CompactionMixin::build_basic_info(bool is_ordered_compaction) {
373
326
    for (auto& rowset : _input_rowsets) {
374
326
        const auto& rowset_meta = rowset->rowset_meta();
375
326
        auto index_size = rowset_meta->index_disk_size();
376
326
        auto total_size = rowset_meta->total_disk_size();
377
326
        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
326
        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
326
        _input_rowsets_data_size += data_size;
391
326
        _input_rowsets_index_size += index_size;
392
326
        _input_rowsets_total_size += total_size;
393
326
        _input_row_num += rowset->num_rows();
394
326
        _input_num_segments += rowset->num_segments();
395
326
    }
396
75
    COUNTER_UPDATE(_input_rowsets_data_size_counter, _input_rowsets_data_size);
397
75
    COUNTER_UPDATE(_input_row_num_counter, _input_row_num);
398
75
    COUNTER_UPDATE(_input_segments_num_counter, _input_num_segments);
399
400
75
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::build_basic_info",
401
75
                                      Status::OK());
402
403
75
    _output_version =
404
75
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
405
406
75
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
407
408
75
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
409
75
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
410
460
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
411
75
    _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
77
    if (_enable_vertical_compact_variant_subcolumns && !is_ordered_compaction) {
417
71
        RETURN_IF_ERROR(
418
71
                vectorized::schema_util::VariantCompactionUtil::get_extended_compaction_schema(
419
71
                        _input_rowsets, _cur_tablet_schema));
420
71
    }
421
75
    return Status::OK();
422
75
}
423
424
89
bool CompactionMixin::handle_ordered_data_compaction() {
425
89
    if (!config::enable_ordered_data_compaction) {
426
0
        return false;
427
0
    }
428
89
    if (compaction_type() == ReaderType::READER_COLD_DATA_COMPACTION ||
429
89
        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
89
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
434
89
        _tablet->enable_unique_key_merge_on_write()) {
435
37
        return false;
436
37
    }
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
52
         compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION)) {
448
0
        for (auto& rowset : _input_rowsets) {
449
0
            if (rowset->rowset_meta()->has_delete_predicate()) {
450
0
                return false;
451
0
            }
452
0
        }
453
0
    }
454
455
    // check if rowsets are tidy so we can just modify meta and do link
456
    // files to handle compaction
457
52
    auto input_size = _input_rowsets.size();
458
52
    std::string pre_max_key;
459
52
    bool pre_rs_key_bounds_truncated {false};
460
105
    for (auto i = 0; i < input_size; ++i) {
461
93
        if (!is_rowset_tidy(pre_max_key, pre_rs_key_bounds_truncated, _input_rowsets[i])) {
462
40
            if (i <= input_size / 2) {
463
40
                return false;
464
40
            } else {
465
0
                _input_rowsets.resize(i);
466
0
                break;
467
0
            }
468
40
        }
469
93
    }
470
    // most rowset of current compaction is nonoverlapping
471
    // just handle nonoverlappint rowsets
472
12
    auto st = do_compact_ordered_rowsets();
473
12
    if (!st.ok()) {
474
0
        LOG(WARNING) << "failed to compact ordered rowsets: " << st;
475
0
        _pending_rs_guard.drop();
476
0
    }
477
478
12
    return st.ok();
479
52
}
480
481
77
Status CompactionMixin::execute_compact() {
482
77
    uint32_t checksum_before;
483
77
    uint32_t checksum_after;
484
77
    bool enable_compaction_checksum = config::enable_compaction_checksum;
485
77
    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
77
    auto* data_dir = tablet()->data_dir();
492
77
    int64_t permits = get_compaction_permits();
493
77
    data_dir->disks_compaction_score_increment(permits);
494
77
    data_dir->disks_compaction_num_increment(1);
495
496
78
    auto record_compaction_stats = [&](const doris::Exception& ex) {
497
78
        _tablet->compaction_count.fetch_add(1, std::memory_order_relaxed);
498
78
        data_dir->disks_compaction_score_increment(-permits);
499
78
        data_dir->disks_compaction_num_increment(-1);
500
78
    };
501
502
77
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(execute_compact_impl(permits), record_compaction_stats);
503
77
    record_compaction_stats(doris::Exception());
504
505
77
    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
77
    DorisMetrics::instance()->local_compaction_read_rows_total->increment(_input_row_num);
517
77
    DorisMetrics::instance()->local_compaction_read_bytes_total->increment(
518
77
            _input_rowsets_total_size);
519
520
77
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact", Status::OK());
521
522
77
    DorisMetrics::instance()->local_compaction_write_rows_total->increment(
523
77
            _output_rowset->num_rows());
524
77
    DorisMetrics::instance()->local_compaction_write_bytes_total->increment(
525
77
            _output_rowset->total_disk_size());
526
527
77
    _load_segment_to_cache();
528
77
    return Status::OK();
529
77
}
530
531
77
Status CompactionMixin::execute_compact_impl(int64_t permits) {
532
77
    OlapStopWatch watch;
533
534
77
    if (handle_ordered_data_compaction()) {
535
6
        RETURN_IF_ERROR(modify_rowsets());
536
6
        LOG(INFO) << "succeed to do ordered data " << compaction_name()
537
6
                  << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
538
6
                  << ", disk=" << tablet()->data_dir()->path()
539
6
                  << ", segments=" << _input_num_segments << ", input_row_num=" << _input_row_num
540
6
                  << ", output_row_num=" << _output_rowset->num_rows()
541
6
                  << ", input_rowsets_data_size=" << _input_rowsets_data_size
542
6
                  << ", input_rowsets_index_size=" << _input_rowsets_index_size
543
6
                  << ", input_rowsets_total_size=" << _input_rowsets_total_size
544
6
                  << ", output_rowset_data_size=" << _output_rowset->data_disk_size()
545
6
                  << ", output_rowset_index_size=" << _output_rowset->index_disk_size()
546
6
                  << ", output_rowset_total_size=" << _output_rowset->total_disk_size()
547
6
                  << ". elapsed time=" << watch.get_elapse_second() << "s.";
548
6
        _state = CompactionState::SUCCESS;
549
6
        return Status::OK();
550
6
    }
551
71
    RETURN_IF_ERROR(build_basic_info());
552
553
71
    TEST_SYNC_POINT_RETURN_WITH_VALUE("compaction::CompactionMixin::execute_compact_impl",
554
71
                                      Status::OK());
555
556
71
    VLOG_DEBUG << "dump tablet schema: " << _cur_tablet_schema->dump_structure();
557
558
71
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
559
71
              << ", output_version=" << _output_version << ", permits: " << permits;
560
561
71
    RETURN_IF_ERROR(merge_input_rowsets());
562
563
    // Currently, updates are only made in the time_series.
564
71
    update_compaction_level();
565
566
71
    RETURN_IF_ERROR(modify_rowsets());
567
568
71
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
569
71
    DCHECK(cumu_policy);
570
71
    LOG(INFO) << "succeed to do " << compaction_name() << " is_vertical=" << _is_vertical
571
71
              << ". tablet=" << _tablet->tablet_id() << ", output_version=" << _output_version
572
71
              << ", current_max_version=" << tablet()->max_version().second
573
71
              << ", disk=" << tablet()->data_dir()->path()
574
71
              << ", input_segments=" << _input_num_segments << ", input_rowsets_data_size="
575
71
              << PrettyPrinter::print_bytes(_input_rowsets_data_size)
576
71
              << ", input_rowsets_index_size="
577
71
              << PrettyPrinter::print_bytes(_input_rowsets_index_size)
578
71
              << ", input_rowsets_total_size="
579
71
              << PrettyPrinter::print_bytes(_input_rowsets_total_size)
580
71
              << ", output_rowset_data_size="
581
71
              << PrettyPrinter::print_bytes(_output_rowset->data_disk_size())
582
71
              << ", output_rowset_index_size="
583
71
              << PrettyPrinter::print_bytes(_output_rowset->index_disk_size())
584
71
              << ", output_rowset_total_size="
585
71
              << PrettyPrinter::print_bytes(_output_rowset->total_disk_size())
586
71
              << ", input_row_num=" << _input_row_num
587
71
              << ", output_row_num=" << _output_rowset->num_rows()
588
71
              << ", filtered_row_num=" << _stats.filtered_rows
589
71
              << ", merged_row_num=" << _stats.merged_rows
590
71
              << ". elapsed time=" << watch.get_elapse_second()
591
71
              << "s. cumulative_compaction_policy=" << cumu_policy->name()
592
71
              << ", compact_row_per_second="
593
71
              << cast_set<double>(_input_row_num) / watch.get_elapse_second();
594
595
71
    _state = CompactionState::SUCCESS;
596
597
71
    return Status::OK();
598
71
}
599
600
17.9k
Status Compaction::do_inverted_index_compaction() {
601
17.9k
    const auto& ctx = _output_rs_writer->context();
602
17.9k
    if (!_enable_inverted_index_compaction || _input_row_num <= 0 ||
603
17.9k
        ctx.columns_to_do_index_compaction.empty()) {
604
17.7k
        return Status::OK();
605
17.7k
    }
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.28k
    for (auto&& rs : _input_rowsets) {
719
1.28k
        rs_id_to_rowset_map.emplace(rs->rowset_id(), rs.get());
720
1.28k
    }
721
722
    // src index dirs
723
239
    std::vector<std::unique_ptr<IndexFileReader>> index_file_readers(src_segment_num);
724
826
    for (const auto& m : src_seg_to_id_map) {
725
826
        const auto& [rowset_id, seg_id] = m.first;
726
727
826
        auto find_it = rs_id_to_rowset_map.find(rowset_id);
728
826
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_find_rowset_error",
729
826
                        { find_it = rs_id_to_rowset_map.end(); })
730
826
        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
826
        auto* rowset = find_it->second;
740
826
        auto fs = rowset->rowset_meta()->fs();
741
826
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_get_fs_error", { fs = nullptr; })
742
826
        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
826
        auto seg_path = rowset->segment_path(seg_id);
751
826
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_seg_path_nullptr", {
752
826
            seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
753
826
                    "do_inverted_index_compaction_seg_path_nullptr"));
754
826
        })
755
826
        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
826
        auto index_file_reader = std::make_unique<IndexFileReader>(
765
826
                fs,
766
826
                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(seg_path.value())},
767
826
                _cur_tablet_schema->get_inverted_index_storage_format(),
768
826
                rowset->rowset_meta()->inverted_index_file_info(seg_id));
769
826
        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
770
826
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_init_inverted_index_file_reader",
771
826
                        {
772
826
                            st = Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
773
826
                                    "debug point: "
774
826
                                    "Compaction::do_inverted_index_compaction_init_inverted_index_"
775
826
                                    "file_reader error");
776
826
                        })
777
826
        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
826
        index_file_readers[m.second] = std::move(index_file_reader);
788
826
    }
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
809
    for (auto&& column_uniq_id : ctx.columns_to_do_index_compaction) {
818
809
        auto col = _cur_tablet_schema->column_by_uid(column_uniq_id);
819
809
        auto index_metas = _cur_tablet_schema->inverted_indexs(col);
820
809
        DBUG_EXECUTE_IF("Compaction::do_inverted_index_compaction_can_not_find_index_meta",
821
809
                        { index_metas.clear(); })
822
809
        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
810
        for (const auto& index_meta : index_metas) {
832
810
            std::vector<lucene::store::Directory*> dest_index_dirs(dest_segment_num);
833
810
            try {
834
810
                std::vector<std::unique_ptr<DorisCompoundReader, DirectoryDeleter>> src_idx_dirs(
835
810
                        src_segment_num);
836
3.53k
                for (int src_segment_id = 0; src_segment_id < src_segment_num; src_segment_id++) {
837
2.72k
                    auto res = index_file_readers[src_segment_id]->open(index_meta);
838
2.72k
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_reader", {
839
2.72k
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
840
2.72k
                                "debug point: Compaction::open_index_file_reader error"));
841
2.72k
                    })
842
2.72k
                    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.72k
                    src_idx_dirs[src_segment_id] = std::move(res.value());
852
2.72k
                }
853
1.73k
                for (int dest_segment_id = 0; dest_segment_id < dest_segment_num;
854
921
                     dest_segment_id++) {
855
921
                    auto res = inverted_index_file_writers[dest_segment_id]->open(index_meta);
856
921
                    DBUG_EXECUTE_IF("Compaction::open_inverted_index_file_writer", {
857
921
                        res = ResultError(Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
858
921
                                "debug point: Compaction::open_inverted_index_file_writer error"));
859
921
                    })
860
921
                    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
921
                    dest_index_dirs[dest_segment_id] = res.value().get();
872
921
                }
873
810
                auto st = compact_column(index_meta->index_id(), src_idx_dirs, dest_index_dirs,
874
810
                                         index_tmp_path.native(), trans_vec, dest_segment_num_rows);
875
810
                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
810
            } 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
810
        }
887
809
    }
888
889
    // check index compaction status. If status is not ok, we should return error and end this compaction round.
890
239
    if (!status.ok()) {
891
1
        return status;
892
1
    }
893
239
    LOG(INFO) << "succeed to do index compaction"
894
238
              << ". tablet=" << _tablet->tablet_id()
895
238
              << ". elapsed time=" << inverted_watch.get_elapse_second() << "s.";
896
897
238
    return Status::OK();
898
239
}
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
16.0k
void Compaction::construct_index_compaction_columns(RowsetWriterContext& ctx) {
922
16.0k
    for (const auto& index : _cur_tablet_schema->inverted_indexes()) {
923
4.06k
        auto col_unique_ids = index->col_unique_ids();
924
        // check if column unique ids is empty to avoid crash
925
4.06k
        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.06k
        auto col_unique_id = col_unique_ids[0];
932
4.06k
        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.06k
        if (!field_is_slice_type(_cur_tablet_schema->column_by_uid(col_unique_id).type())) {
939
2.34k
            continue;
940
2.34k
        }
941
942
        // if index properties are different, index compaction maybe needs to be skipped.
943
1.71k
        bool is_continue = false;
944
1.71k
        std::optional<std::map<std::string, std::string>> first_properties;
945
11.9k
        for (const auto& rowset : _input_rowsets) {
946
11.9k
            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
11.9k
            auto it = std::find_if(tablet_indexs.begin(), tablet_indexs.end(),
949
11.9k
                                   [&index](const auto& tablet_index) {
950
11.9k
                                       return tablet_index->index_id() == index->index_id();
951
11.9k
                                   });
952
11.9k
            if (it != tablet_indexs.end()) {
953
11.9k
                const auto* tablet_index = *it;
954
11.9k
                auto properties = tablet_index->properties();
955
11.9k
                if (!first_properties.has_value()) {
956
1.71k
                    first_properties = properties;
957
10.2k
                } else {
958
10.2k
                    DBUG_EXECUTE_IF(
959
10.2k
                            "Compaction::do_inverted_index_compaction_index_properties_different",
960
10.2k
                            { properties.emplace("dummy_key", "dummy_value"); })
961
10.2k
                    if (properties != first_properties.value()) {
962
3
                        is_continue = true;
963
3
                        break;
964
3
                    }
965
10.2k
                }
966
18.4E
            } else {
967
18.4E
                is_continue = true;
968
18.4E
                break;
969
18.4E
            }
970
11.9k
        }
971
1.71k
        if (is_continue) {
972
5
            continue;
973
5
        }
974
10.2k
        auto has_inverted_index = [&](const RowsetSharedPtr& src_rs) {
975
10.2k
            auto* rowset = static_cast<BetaRowset*>(src_rs.get());
976
10.2k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_is_skip_index_compaction",
977
10.2k
                            { rowset->set_skip_index_compaction(col_unique_id); })
978
10.2k
            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.2k
            auto fs = rowset->rowset_meta()->fs();
986
10.2k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_get_fs_error",
987
10.2k
                            { fs = nullptr; })
988
10.2k
            if (!fs) {
989
365
                LOG(WARNING) << "get fs failed, resource_id="
990
365
                             << rowset->rowset_meta()->resource_id();
991
365
                return false;
992
365
            }
993
994
9.90k
            auto index_metas = rowset->tablet_schema()->inverted_indexs(col_unique_id);
995
9.90k
            DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_index_meta_nullptr",
996
9.90k
                            { index_metas.clear(); })
997
9.90k
            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
9.91k
            for (const auto& index_meta : index_metas) {
1003
12.8k
                for (auto i = 0; i < rowset->num_segments(); i++) {
1004
                    // TODO: inverted_index_path
1005
2.98k
                    auto seg_path = rowset->segment_path(i);
1006
2.98k
                    DBUG_EXECUTE_IF("Compaction::construct_skip_inverted_index_seg_path_nullptr", {
1007
2.98k
                        seg_path = ResultError(Status::Error<ErrorCode::INTERNAL_ERROR>(
1008
2.98k
                                "construct_skip_inverted_index_seg_path_nullptr"));
1009
2.98k
                    })
1010
2.98k
                    if (!seg_path) {
1011
0
                        LOG(WARNING) << seg_path.error();
1012
0
                        return false;
1013
0
                    }
1014
1015
2.98k
                    std::string index_file_path;
1016
2.98k
                    try {
1017
2.98k
                        auto index_file_reader = std::make_unique<IndexFileReader>(
1018
2.98k
                                fs,
1019
2.98k
                                std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
1020
2.98k
                                        seg_path.value())},
1021
2.98k
                                _cur_tablet_schema->get_inverted_index_storage_format(),
1022
2.98k
                                rowset->rowset_meta()->inverted_index_file_info(i));
1023
2.98k
                        auto st = index_file_reader->init(config::inverted_index_read_buffer_size);
1024
2.98k
                        index_file_path = index_file_reader->get_index_file_path(index_meta);
1025
2.98k
                        DBUG_EXECUTE_IF(
1026
2.98k
                                "Compaction::construct_skip_inverted_index_index_file_reader_init_"
1027
2.98k
                                "status_not_ok",
1028
2.98k
                                {
1029
2.98k
                                    st = Status::Error<ErrorCode::INTERNAL_ERROR>(
1030
2.98k
                                            "debug point: "
1031
2.98k
                                            "construct_skip_inverted_index_index_file_reader_init_"
1032
2.98k
                                            "status_"
1033
2.98k
                                            "not_ok");
1034
2.98k
                                })
1035
2.98k
                        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
2.98k
                        auto result = index_file_reader->open(index_meta);
1042
2.98k
                        DBUG_EXECUTE_IF(
1043
2.98k
                                "Compaction::construct_skip_inverted_index_index_file_reader_open_"
1044
2.98k
                                "error",
1045
2.98k
                                {
1046
2.98k
                                    result = ResultError(
1047
2.98k
                                            Status::Error<ErrorCode::INVERTED_INDEX_CLUCENE_ERROR>(
1048
2.98k
                                                    "CLuceneError occur when open idx file"));
1049
2.98k
                                })
1050
2.98k
                        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
2.98k
                        auto reader = std::move(result.value());
1056
2.98k
                        std::vector<std::string> files;
1057
2.98k
                        reader->list(&files);
1058
2.98k
                        reader->close();
1059
2.98k
                        DBUG_EXECUTE_IF(
1060
2.98k
                                "Compaction::construct_skip_inverted_index_index_reader_close_"
1061
2.98k
                                "error",
1062
2.98k
                                { _CLTHROWA(CL_ERR_IO, "debug point: reader close error"); })
1063
1064
2.98k
                        DBUG_EXECUTE_IF(
1065
2.98k
                                "Compaction::construct_skip_inverted_index_index_files_count",
1066
2.98k
                                { files.clear(); })
1067
1068
                        // why is 3?
1069
                        // slice type index file at least has 3 files: null_bitmap, segments_N, segments.gen
1070
2.98k
                        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
2.98k
                    } 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
2.98k
                }
1084
9.91k
            }
1085
9.90k
            return true;
1086
9.90k
        };
1087
1088
1.70k
        bool all_have_inverted_index = std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1089
1.70k
                                                   std::move(has_inverted_index));
1090
1091
1.70k
        if (all_have_inverted_index) {
1092
1.34k
            ctx.columns_to_do_index_compaction.insert(col_unique_id);
1093
1.34k
        }
1094
1.70k
    }
1095
16.0k
}
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
179
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
179
    {
1129
179
        std::shared_lock meta_rlock(_tablet->get_header_lock());
1130
179
        if (_tablet->tablet_state() != TABLET_NOTREADY) {
1131
179
            return Status::OK();
1132
179
        }
1133
179
    }
1134
0
    OlapStopWatch watch;
1135
0
    std::vector<RowsetSharedPtr> rowsets;
1136
0
    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
0
    LOG(INFO) << "finish update delete bitmap for tablet: " << _tablet->tablet_id()
1146
0
              << ", rowsets: " << _input_rowsets.size() << ", cost: " << watch.get_elapse_time_us()
1147
0
              << "(us)";
1148
0
    return Status::OK();
1149
0
}
1150
1151
118
Status CompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1152
    // only do index compaction for dup_keys and unique_keys with mow enabled
1153
118
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1154
101
                                                _tablet->enable_unique_key_merge_on_write()) ||
1155
101
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1156
83
        construct_index_compaction_columns(ctx);
1157
83
    }
1158
118
    ctx.version = _output_version;
1159
118
    ctx.rowset_state = VISIBLE;
1160
118
    ctx.segments_overlap = NONOVERLAPPING;
1161
118
    ctx.tablet_schema = _cur_tablet_schema;
1162
118
    ctx.newest_write_timestamp = _newest_write_timestamp;
1163
118
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1164
118
    ctx.compaction_type = compaction_type();
1165
118
    ctx.allow_packed_file = false;
1166
118
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1167
118
    _pending_rs_guard = _engine.add_pending_rowset(ctx);
1168
118
    return Status::OK();
1169
118
}
1170
1171
77
Status CompactionMixin::modify_rowsets() {
1172
77
    std::vector<RowsetSharedPtr> output_rowsets;
1173
77
    output_rowsets.push_back(_output_rowset);
1174
1175
77
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1176
77
        _tablet->enable_unique_key_merge_on_write()) {
1177
35
        Version version = tablet()->max_version();
1178
35
        DeleteBitmap output_rowset_delete_bitmap(_tablet->tablet_id());
1179
35
        std::unique_ptr<RowLocationSet> missed_rows;
1180
35
        if ((config::enable_missing_rows_correctness_check ||
1181
35
             config::enable_mow_compaction_correctness_check_core ||
1182
35
             config::enable_mow_compaction_correctness_check_fail) &&
1183
37
            !_allow_delete_in_cumu_compaction &&
1184
37
            compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1185
35
            missed_rows = std::make_unique<RowLocationSet>();
1186
35
            LOG(INFO) << "RowLocation Set inited succ for tablet:" << _tablet->tablet_id();
1187
35
        }
1188
35
        std::unique_ptr<std::map<RowsetSharedPtr, RowLocationPairList>> location_map;
1189
35
        if (config::enable_rowid_conversion_correctness_check &&
1190
35
            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
35
        std::size_t missed_rows_size = 0;
1200
35
        tablet()->calc_compaction_output_rowset_delete_bitmap(
1201
35
                _input_rowsets, *_rowid_conversion, 0, version.second + 1, missed_rows.get(),
1202
35
                location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1203
35
                &output_rowset_delete_bitmap);
1204
37
        if (missed_rows) {
1205
37
            missed_rows_size = missed_rows->size();
1206
37
            std::size_t merged_missed_rows_size = _stats.merged_rows;
1207
37
            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
37
            bool need_to_check_missed_rows = true;
1224
37
            {
1225
37
                std::shared_lock rlock(_tablet->get_header_lock());
1226
37
                need_to_check_missed_rows =
1227
37
                        std::all_of(_input_rowsets.begin(), _input_rowsets.end(),
1228
212
                                    [&](const RowsetSharedPtr& rowset) {
1229
212
                                        return tablet()->rowset_exists_unlocked(rowset);
1230
212
                                    });
1231
37
            }
1232
1233
37
            if (_tablet->tablet_state() == TABLET_RUNNING &&
1234
37
                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
37
        }
1270
1271
35
        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
35
        {
1277
35
            std::lock_guard<std::mutex> wrlock_(tablet()->get_rowset_update_lock());
1278
35
            std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1279
35
            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
35
            CommitTabletTxnInfoVec commit_tablet_txn_info_vec {};
1286
35
            _engine.txn_manager()->get_all_commit_tablet_txn_info_by_tablet(
1287
35
                    *tablet(), &commit_tablet_txn_info_vec);
1288
1289
            // Step2: calculate all rowsets' delete bitmaps which are published during compaction.
1290
35
            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
35
            tablet()->calc_compaction_output_rowset_delete_bitmap(
1321
35
                    _input_rowsets, *_rowid_conversion, version.second, UINT64_MAX,
1322
35
                    missed_rows.get(), location_map.get(), _tablet->tablet_meta()->delete_bitmap(),
1323
35
                    &output_rowset_delete_bitmap);
1324
1325
35
            if (location_map) {
1326
0
                RETURN_IF_ERROR(tablet()->check_rowid_conversion(_output_rowset, *location_map));
1327
0
            }
1328
1329
35
            tablet()->merge_delete_bitmap(output_rowset_delete_bitmap);
1330
35
            RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1331
35
        }
1332
42
    } else {
1333
42
        std::lock_guard<std::shared_mutex> wrlock(_tablet->get_header_lock());
1334
42
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1335
42
        RETURN_IF_ERROR(tablet()->modify_rowsets(output_rowsets, _input_rowsets, true));
1336
42
    }
1337
1338
77
    if (config::tablet_rowset_stale_sweep_by_size &&
1339
77
        _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
77
    int64_t cur_max_version = 0;
1345
77
    {
1346
77
        std::shared_lock rlock(_tablet->get_header_lock());
1347
77
        cur_max_version = _tablet->max_version_unlocked();
1348
77
        tablet()->save_meta();
1349
77
    }
1350
77
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1351
77
        _tablet->enable_unique_key_merge_on_write()) {
1352
37
        auto st = TabletMetaManager::remove_old_version_delete_bitmap(
1353
37
                tablet()->data_dir(), _tablet->tablet_id(), cur_max_version);
1354
37
        if (!st.ok()) {
1355
0
            LOG(WARNING) << "failed to remove old version delete bitmap, st: " << st;
1356
0
        }
1357
37
    }
1358
77
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset",
1359
77
                    { tablet()->delete_expired_stale_rowset(); });
1360
77
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
1361
77
    return Status::OK();
1362
77
}
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
67
void CompactionMixin::update_compaction_level() {
1380
67
    auto* cumu_policy = tablet()->cumulative_compaction_policy();
1381
71
    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
67
}
1387
1388
17.8k
Status Compaction::check_correctness() {
1389
    // 1. check row number
1390
17.8k
    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
17.8k
    RETURN_IF_ERROR(vectorized::schema_util::VariantCompactionUtil::check_path_stats(
1399
17.8k
            _input_rowsets, _output_rowset, _tablet));
1400
17.8k
    return Status::OK();
1401
17.8k
}
1402
1403
176
int64_t CompactionMixin::get_compaction_permits() {
1404
176
    int64_t permits = 0;
1405
1.27k
    for (auto&& rowset : _input_rowsets) {
1406
1.27k
        permits += rowset->rowset_meta()->get_compaction_score();
1407
1.27k
    }
1408
176
    return permits;
1409
176
}
1410
1411
69
int64_t CompactionMixin::calc_input_rowsets_total_size() const {
1412
69
    int64_t input_rowsets_total_size = 0;
1413
286
    for (const auto& rowset : _input_rowsets) {
1414
286
        const auto& rowset_meta = rowset->rowset_meta();
1415
286
        auto total_size = rowset_meta->total_disk_size();
1416
286
        input_rowsets_total_size += total_size;
1417
286
    }
1418
69
    return input_rowsets_total_size;
1419
69
}
1420
1421
69
int64_t CompactionMixin::calc_input_rowsets_row_num() const {
1422
69
    int64_t input_rowsets_row_num = 0;
1423
286
    for (const auto& rowset : _input_rowsets) {
1424
286
        const auto& rowset_meta = rowset->rowset_meta();
1425
286
        auto total_size = rowset_meta->total_disk_size();
1426
286
        input_rowsets_row_num += total_size;
1427
286
    }
1428
69
    return input_rowsets_row_num;
1429
69
}
1430
1431
17.5k
void Compaction::_load_segment_to_cache() {
1432
    // Load new rowset's segments to cache.
1433
17.5k
    SegmentCacheHandle handle;
1434
17.5k
    auto st = SegmentLoader::instance()->load_segments(
1435
17.5k
            std::static_pointer_cast<BetaRowset>(_output_rowset), &handle, true);
1436
17.5k
    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
17.5k
}
1442
1443
17.6k
Status CloudCompactionMixin::build_basic_info() {
1444
17.6k
    _output_version =
1445
17.6k
            Version(_input_rowsets.front()->start_version(), _input_rowsets.back()->end_version());
1446
1447
17.6k
    _newest_write_timestamp = _input_rowsets.back()->newest_write_timestamp();
1448
1449
17.6k
    std::vector<RowsetMetaSharedPtr> rowset_metas(_input_rowsets.size());
1450
17.6k
    std::transform(_input_rowsets.begin(), _input_rowsets.end(), rowset_metas.begin(),
1451
130k
                   [](const RowsetSharedPtr& rowset) { return rowset->rowset_meta(); });
1452
17.6k
    if (is_index_change_compaction()) {
1453
499
        RETURN_IF_ERROR(rebuild_tablet_schema());
1454
17.1k
    } else {
1455
17.1k
        _cur_tablet_schema = _tablet->tablet_schema_with_merged_max_schema_version(rowset_metas);
1456
17.1k
    }
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
17.7k
    if (_enable_vertical_compact_variant_subcolumns) {
1461
17.7k
        RETURN_IF_ERROR(
1462
17.7k
                vectorized::schema_util::VariantCompactionUtil::get_extended_compaction_schema(
1463
17.7k
                        _input_rowsets, _cur_tablet_schema));
1464
17.7k
    }
1465
17.6k
    return Status::OK();
1466
17.6k
}
1467
1468
17.5k
int64_t CloudCompactionMixin::get_compaction_permits() {
1469
17.5k
    int64_t permits = 0;
1470
132k
    for (auto&& rowset : _input_rowsets) {
1471
132k
        permits += rowset->rowset_meta()->get_compaction_score();
1472
132k
    }
1473
17.5k
    return permits;
1474
17.5k
}
1475
1476
CloudCompactionMixin::CloudCompactionMixin(CloudStorageEngine& engine, CloudTabletSPtr tablet,
1477
                                           const std::string& label)
1478
138k
        : Compaction(tablet, label), _engine(engine) {
1479
138k
    auto uuid = UUIDGenerator::instance()->next_uuid();
1480
138k
    std::stringstream ss;
1481
138k
    ss << uuid;
1482
138k
    _uuid = ss.str();
1483
138k
}
1484
1485
17.7k
Status CloudCompactionMixin::execute_compact_impl(int64_t permits) {
1486
17.7k
    OlapStopWatch watch;
1487
1488
17.7k
    RETURN_IF_ERROR(build_basic_info());
1489
1490
17.7k
    LOG(INFO) << "start " << compaction_name() << ". tablet=" << _tablet->tablet_id()
1491
17.7k
              << ", output_version=" << _output_version << ", permits: " << permits;
1492
1493
17.7k
    RETURN_IF_ERROR(merge_input_rowsets());
1494
1495
17.7k
    DBUG_EXECUTE_IF("CloudFullCompaction::modify_rowsets.wrong_rowset_id", {
1496
17.7k
        DCHECK(compaction_type() == ReaderType::READER_FULL_COMPACTION);
1497
17.7k
        RowsetId id;
1498
17.7k
        id.version = 2;
1499
17.7k
        id.hi = _output_rowset->rowset_meta()->rowset_id().hi + ((int64_t)(1) << 56);
1500
17.7k
        id.mi = _output_rowset->rowset_meta()->rowset_id().mi;
1501
17.7k
        id.lo = _output_rowset->rowset_meta()->rowset_id().lo;
1502
17.7k
        _output_rowset->rowset_meta()->set_rowset_id(id);
1503
17.7k
        LOG(INFO) << "[Debug wrong rowset id]:"
1504
17.7k
                  << _output_rowset->rowset_meta()->rowset_id().to_string();
1505
17.7k
    })
1506
1507
    // Currently, updates are only made in the time_series.
1508
17.7k
    update_compaction_level();
1509
1510
17.7k
    RETURN_IF_ERROR(_engine.meta_mgr().commit_rowset(*_output_rowset->rowset_meta().get(), _uuid));
1511
1512
    // 4. modify rowsets in memory
1513
17.7k
    RETURN_IF_ERROR(modify_rowsets());
1514
1515
    // update compaction status data
1516
17.6k
    auto tablet = std::static_pointer_cast<CloudTablet>(_tablet);
1517
17.6k
    tablet->local_read_time_us.fetch_add(_stats.cloud_local_read_time);
1518
17.6k
    tablet->remote_read_time_us.fetch_add(_stats.cloud_remote_read_time);
1519
17.6k
    tablet->exec_compaction_time_us.fetch_add(watch.get_elapse_time_us());
1520
1521
17.6k
    return Status::OK();
1522
17.7k
}
1523
1524
17.1k
int64_t CloudCompactionMixin::initiator() const {
1525
17.1k
    return HashUtil::hash64(_uuid.data(), _uuid.size(), 0) & std::numeric_limits<int64_t>::max();
1526
17.1k
}
1527
1528
namespace cloud {
1529
size_t truncate_rowsets_by_txn_size(std::vector<RowsetSharedPtr>& rowsets, int64_t& kept_size_bytes,
1530
18.1k
                                    int64_t& truncated_size_bytes) {
1531
18.1k
    if (rowsets.empty()) {
1532
1
        kept_size_bytes = 0;
1533
1
        truncated_size_bytes = 0;
1534
1
        return 0;
1535
1
    }
1536
1537
18.1k
    int64_t max_size = config::compaction_txn_max_size_bytes;
1538
18.1k
    int64_t cumulative_meta_size = 0;
1539
18.1k
    size_t keep_count = 0;
1540
1541
155k
    for (size_t i = 0; i < rowsets.size(); ++i) {
1542
137k
        const auto& rs = rowsets[i];
1543
1544
        // Estimate rowset meta size using doris_rowset_meta_to_cloud
1545
137k
        auto cloud_meta = cloud::doris_rowset_meta_to_cloud(rs->rowset_meta()->get_rowset_pb(true));
1546
137k
        int64_t rowset_meta_size = cloud_meta.ByteSizeLong();
1547
1548
137k
        cumulative_meta_size += rowset_meta_size;
1549
1550
137k
        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
137k
        keep_count++;
1557
137k
    }
1558
1559
    // Ensure at least 1 rowset is kept
1560
18.1k
    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
18.1k
    int64_t truncated_total_size = 0;
1570
18.1k
    size_t truncated_count = rowsets.size() - keep_count;
1571
18.1k
    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
18.1k
    kept_size_bytes = cumulative_meta_size;
1581
18.1k
    truncated_size_bytes = truncated_total_size;
1582
18.1k
    return truncated_count;
1583
18.1k
}
1584
} // namespace cloud
1585
1586
17.5k
size_t CloudCompactionMixin::apply_txn_size_truncation_and_log(const std::string& compaction_name) {
1587
17.5k
    if (_input_rowsets.empty()) {
1588
1
        return 0;
1589
1
    }
1590
1591
17.5k
    int64_t original_count = _input_rowsets.size();
1592
17.5k
    int64_t original_start_version = _input_rowsets.front()->start_version();
1593
17.5k
    int64_t original_end_version = _input_rowsets.back()->end_version();
1594
1595
17.5k
    int64_t final_size = 0;
1596
17.5k
    int64_t truncated_size = 0;
1597
17.5k
    size_t truncated_count =
1598
17.5k
            cloud::truncate_rowsets_by_txn_size(_input_rowsets, final_size, truncated_size);
1599
1600
17.5k
    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
17.5k
    return truncated_count;
1617
17.5k
}
1618
1619
17.4k
Status CloudCompactionMixin::execute_compact() {
1620
17.4k
    TEST_INJECTION_POINT("Compaction::do_compaction");
1621
17.4k
    int64_t permits = get_compaction_permits();
1622
17.4k
    HANDLE_EXCEPTION_IF_CATCH_EXCEPTION(
1623
17.4k
            execute_compact_impl(permits), [&](const doris::Exception& ex) {
1624
17.4k
                auto st = garbage_collection();
1625
17.4k
                if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1626
17.4k
                    _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
17.4k
                    _engine.meta_mgr().remove_delete_bitmap_update_lock(
1632
17.4k
                            _tablet->table_id(), COMPACTION_DELETE_BITMAP_LOCK_ID, initiator(),
1633
17.4k
                            _tablet->tablet_id());
1634
17.4k
                }
1635
17.6k
            });
1636
1637
17.6k
    DorisMetrics::instance()->remote_compaction_read_rows_total->increment(_input_row_num);
1638
17.6k
    DorisMetrics::instance()->remote_compaction_write_rows_total->increment(
1639
17.6k
            _output_rowset->num_rows());
1640
17.6k
    DorisMetrics::instance()->remote_compaction_write_bytes_total->increment(
1641
17.6k
            _output_rowset->total_disk_size());
1642
1643
17.6k
    _load_segment_to_cache();
1644
17.6k
    return Status::OK();
1645
17.4k
}
1646
1647
0
Status CloudCompactionMixin::modify_rowsets() {
1648
0
    return Status::OK();
1649
0
}
1650
1651
17.8k
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
61.8k
    for (const auto& rowset : std::ranges::reverse_view(_input_rowsets)) {
1662
61.8k
        const auto& resource_id = rowset->rowset_meta()->resource_id();
1663
1664
61.8k
        if (!resource_id.empty()) {
1665
9.94k
            ctx.storage_resource = *DORIS_TRY(rowset->rowset_meta()->remote_storage_resource());
1666
9.94k
            return Status::OK();
1667
9.94k
        }
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
51.9k
        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
51.9k
    }
1687
1688
7.87k
    return Status::OK();
1689
17.8k
}
1690
1691
17.8k
Status CloudCompactionMixin::construct_output_rowset_writer(RowsetWriterContext& ctx) {
1692
    // only do index compaction for dup_keys and unique_keys with mow enabled
1693
17.8k
    if (_enable_inverted_index_compaction && (((_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
1694
17.3k
                                                _tablet->enable_unique_key_merge_on_write()) ||
1695
17.3k
                                               _tablet->keys_type() == KeysType::DUP_KEYS))) {
1696
16.0k
        construct_index_compaction_columns(ctx);
1697
16.0k
    }
1698
1699
    // Use the storage resource of the previous rowset.
1700
17.8k
    RETURN_IF_ERROR(set_storage_resource_from_input_rowsets(ctx));
1701
1702
17.8k
    ctx.txn_id = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
1703
17.8k
                 std::numeric_limits<int64_t>::max(); // MUST be positive
1704
17.8k
    ctx.txn_expiration = _expiration;
1705
1706
17.8k
    ctx.version = _output_version;
1707
17.8k
    ctx.rowset_state = VISIBLE;
1708
17.8k
    ctx.segments_overlap = NONOVERLAPPING;
1709
17.8k
    ctx.tablet_schema = _cur_tablet_schema;
1710
17.8k
    ctx.newest_write_timestamp = _newest_write_timestamp;
1711
17.8k
    ctx.write_type = DataWriteType::TYPE_COMPACTION;
1712
17.8k
    ctx.compaction_type = compaction_type();
1713
17.8k
    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
17.8k
    ctx.write_file_cache = should_cache_compaction_output();
1720
17.8k
    ctx.file_cache_ttl_sec = _tablet->ttl_seconds();
1721
17.8k
    ctx.approximate_bytes_to_write = _input_rowsets_total_size;
1722
17.8k
    ctx.tablet = _tablet;
1723
1724
17.8k
    _output_rs_writer = DORIS_TRY(_tablet->create_rowset_writer(ctx, _is_vertical));
1725
17.8k
    RETURN_IF_ERROR(
1726
17.8k
            _engine.meta_mgr().prepare_rowset(*_output_rs_writer->rowset_meta().get(), _uuid));
1727
17.8k
    return Status::OK();
1728
17.8k
}
1729
1730
99
Status CloudCompactionMixin::garbage_collection() {
1731
99
    if (!config::enable_file_cache) {
1732
0
        return Status::OK();
1733
0
    }
1734
99
    if (_output_rs_writer) {
1735
99
        auto* beta_rowset_writer = dynamic_cast<BaseBetaRowsetWriter*>(_output_rs_writer.get());
1736
99
        DCHECK(beta_rowset_writer);
1737
99
        for (const auto& [_, file_writer] : beta_rowset_writer->get_file_writers()) {
1738
66
            auto file_key = io::BlockFileCache::hash(file_writer->path().filename().native());
1739
66
            auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1740
66
            file_cache->remove_if_cached_async(file_key);
1741
66
        }
1742
99
        for (const auto& [_, index_writer] : beta_rowset_writer->index_file_writers()) {
1743
1
            for (const auto& file_name : index_writer->get_index_file_names()) {
1744
1
                auto file_key = io::BlockFileCache::hash(file_name);
1745
1
                auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
1746
1
                file_cache->remove_if_cached_async(file_key);
1747
1
            }
1748
1
        }
1749
99
    }
1750
99
    return Status::OK();
1751
99
}
1752
1753
17.6k
void CloudCompactionMixin::update_compaction_level() {
1754
    // for index change compaction, compaction level should not changed.
1755
    // because input rowset num is 1.
1756
17.6k
    if (is_index_change_compaction()) {
1757
502
        DCHECK(_input_rowsets.size() == 1);
1758
502
        _output_rowset->rowset_meta()->set_compaction_level(
1759
502
                _input_rowsets.back()->rowset_meta()->compaction_level());
1760
17.1k
    } else {
1761
17.1k
        auto compaction_policy = _tablet->tablet_meta()->compaction_policy();
1762
17.1k
        auto cumu_policy = _engine.cumu_compaction_policy(compaction_policy);
1763
17.3k
        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
17.1k
    }
1769
17.6k
}
1770
1771
// should skip hole rowsets, ortherwise the count will be wrong in ms
1772
17.5k
int64_t CloudCompactionMixin::num_input_rowsets() const {
1773
17.5k
    int64_t count = 0;
1774
132k
    for (const auto& r : _input_rowsets) {
1775
132k
        if (!r->is_hole_rowset()) {
1776
37.3k
            count++;
1777
37.3k
        }
1778
132k
    }
1779
17.5k
    return count;
1780
17.5k
}
1781
1782
17.8k
bool CloudCompactionMixin::should_cache_compaction_output() {
1783
17.8k
    if (compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1784
17.7k
        return true;
1785
17.7k
    }
1786
1787
169
    if (compaction_type() == ReaderType::READER_BASE_COMPACTION) {
1788
85
        double input_rowsets_hit_cache_ratio = 0.0;
1789
1790
85
        int64_t _input_rowsets_cached_size =
1791
85
                _input_rowsets_cached_data_size + _input_rowsets_cached_index_size;
1792
85
        if (_input_rowsets_total_size > 0) {
1793
70
            input_rowsets_hit_cache_ratio =
1794
70
                    double(_input_rowsets_cached_size) / double(_input_rowsets_total_size);
1795
70
        }
1796
1797
85
        LOG(INFO) << "CloudBaseCompaction should_cache_compaction_output"
1798
85
                  << ", tablet_id=" << _tablet->tablet_id()
1799
85
                  << ", input_rowsets_hit_cache_ratio=" << input_rowsets_hit_cache_ratio
1800
85
                  << ", _input_rowsets_cached_size=" << _input_rowsets_cached_size
1801
85
                  << ", _input_rowsets_total_size=" << _input_rowsets_total_size
1802
85
                  << ", enable_file_cache_keep_base_compaction_output="
1803
85
                  << config::enable_file_cache_keep_base_compaction_output
1804
85
                  << ", file_cache_keep_base_compaction_output_min_hit_ratio="
1805
85
                  << config::file_cache_keep_base_compaction_output_min_hit_ratio;
1806
1807
85
        if (config::enable_file_cache_keep_base_compaction_output) {
1808
0
            return true;
1809
0
        }
1810
1811
85
        if (input_rowsets_hit_cache_ratio >
1812
85
            config::file_cache_keep_base_compaction_output_min_hit_ratio) {
1813
34
            return true;
1814
34
        }
1815
85
    }
1816
135
    return false;
1817
169
}
1818
1819
#include "common/compile_check_end.h"
1820
} // namespace doris