Coverage Report

Created: 2025-06-11 12:44

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