Coverage Report

Created: 2025-11-13 13:02

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