Coverage Report

Created: 2026-02-12 05:02

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