Coverage Report

Created: 2026-02-11 17:09

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