Coverage Report

Created: 2025-04-21 15:34

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