Coverage Report

Created: 2026-02-09 17:54

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