Coverage Report

Created: 2026-01-23 05:59

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