Coverage Report

Created: 2025-07-28 18:41

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