Coverage Report

Created: 2025-09-14 17:16

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