Coverage Report

Created: 2025-07-25 11:59

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