Coverage Report

Created: 2025-10-16 19:56

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