Coverage Report

Created: 2026-04-01 15:56

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