Coverage Report

Created: 2025-12-16 22:04

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