Coverage Report

Created: 2024-11-21 23:45

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