Coverage Report

Created: 2025-12-30 11:22

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