Coverage Report

Created: 2026-03-12 17:15

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