Coverage Report

Created: 2025-09-10 18:13

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