Coverage Report

Created: 2025-03-12 00:38

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