Coverage Report

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