Coverage Report

Created: 2026-07-23 15:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_cumulative_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 "cloud/cloud_cumulative_compaction.h"
19
20
#include <gen_cpp/cloud.pb.h>
21
22
#include <algorithm>
23
#include <random>
24
25
#include "cloud/cloud_meta_mgr.h"
26
#include "cloud/cloud_tablet_mgr.h"
27
#include "cloud/config.h"
28
#include "common/config.h"
29
#include "common/logging.h"
30
#include "common/status.h"
31
#include "cpp/sync_point.h"
32
#include "service/backend_options.h"
33
#include "storage/compaction/compaction.h"
34
#include "storage/compaction/cumulative_compaction_policy.h"
35
#include "util/debug_points.h"
36
#include "util/trace.h"
37
#include "util/uuid_generator.h"
38
39
namespace doris {
40
using namespace ErrorCode;
41
42
bvar::Adder<uint64_t> cumu_output_size("cumu_compaction", "output_size");
43
bvar::LatencyRecorder g_cu_compaction_hold_delete_bitmap_lock_time_ms(
44
        "cu_compaction_hold_delete_bitmap_lock_time_ms");
45
46
CloudCumulativeCompaction::CloudCumulativeCompaction(CloudStorageEngine& engine,
47
                                                     CloudTabletSPtr tablet)
48
11
        : CloudCompactionMixin(engine, tablet,
49
11
                               "BaseCompaction:" + std::to_string(tablet->tablet_id())) {}
50
51
11
CloudCumulativeCompaction::~CloudCumulativeCompaction() = default;
52
53
6
int64_t CloudCumulativeCompaction::_refresh_conflict_versions() {
54
6
    std::vector<std::shared_ptr<CloudCumulativeCompaction>> cumu_compactions;
55
6
    _engine.get_cumu_compaction(_tablet->tablet_id(), cumu_compactions);
56
7
    for (const auto& cumu : cumu_compactions) {
57
7
        _min_conflict_version =
58
7
                std::min(_min_conflict_version, cumu->_input_rowsets.front()->start_version());
59
7
        _max_conflict_version =
60
7
                std::max(_max_conflict_version, cumu->_input_rowsets.back()->end_version());
61
7
    }
62
6
    return _max_conflict_version;
63
6
}
64
65
3
Status CloudCumulativeCompaction::prepare_compact() {
66
3
    DBUG_EXECUTE_IF("CloudCumulativeCompaction.prepare_compact.sleep", { sleep(5); })
67
3
    Status st;
68
3
    Defer defer_set_st([&] {
69
3
        if (!st.ok()) {
70
0
            cloud_tablet()->set_last_cumu_compaction_status(st.to_string());
71
0
        }
72
3
    });
73
3
    if (_tablet->tablet_state() != TABLET_RUNNING &&
74
3
        (!config::enable_new_tablet_do_compaction ||
75
0
         static_cast<CloudTablet*>(_tablet.get())->alter_version() == -1)) {
76
0
        st = Status::InternalError("invalid tablet state. tablet_id={}", _tablet->tablet_id());
77
0
        return st;
78
0
    }
79
80
3
    _refresh_conflict_versions();
81
82
3
    bool need_sync_tablet = true;
83
3
    {
84
3
        std::shared_lock rlock(_tablet->get_header_lock());
85
        // If number of rowsets is equal to approximate_num_rowsets, it is very likely that this tablet has been
86
        // synchronized with meta-service.
87
3
        if (_tablet->tablet_meta()->all_rs_metas().size() >=
88
3
                    cloud_tablet()->fetch_add_approximate_num_rowsets(0) &&
89
3
            cloud_tablet()->last_sync_time_s > 0) {
90
3
            need_sync_tablet = false;
91
3
        }
92
3
    }
93
3
    if (need_sync_tablet) {
94
0
        st = cloud_tablet()->sync_rowsets();
95
0
        RETURN_IF_ERROR(st);
96
0
    }
97
98
    // pick rowsets to compact
99
3
    st = pick_rowsets_to_compact();
100
3
    if (!st.ok()) {
101
0
        if (_last_delete_version.first != -1) {
102
            // we meet a delete version, should increase the cumulative point to let base compaction handle the delete version.
103
            // plus 1 to skip the delete version.
104
            // NOTICE: after that, the cumulative point may be larger than max version of this tablet, but it doesn't matter.
105
0
            update_cumulative_point();
106
0
            if (!config::enable_sleep_between_delete_cumu_compaction) {
107
0
                st = Status::Error<CUMULATIVE_MEET_DELETE_VERSION>(
108
0
                        "cumulative compaction meet delete version");
109
0
            }
110
0
        }
111
0
        return st;
112
0
    }
113
114
8
    for (auto& rs : _input_rowsets) {
115
8
        _input_row_num += rs->num_rows();
116
8
        _input_segments += rs->num_segments();
117
8
        _input_rowsets_data_size += rs->data_disk_size();
118
8
        _input_rowsets_index_size += rs->index_disk_size();
119
8
        _input_rowsets_total_size += rs->total_disk_size();
120
8
    }
121
3
    LOG_INFO("start CloudCumulativeCompaction, tablet_id={}, range=[{}-{}]", _tablet->tablet_id(),
122
3
             _input_rowsets.front()->start_version(), _input_rowsets.back()->end_version())
123
3
            .tag("job_id", _uuid)
124
3
            .tag("input_rowsets", _input_rowsets.size())
125
3
            .tag("input_rows", _input_row_num)
126
3
            .tag("input_segments", _input_segments)
127
3
            .tag("input_rowsets_data_size", _input_rowsets_data_size)
128
3
            .tag("input_rowsets_index_size", _input_rowsets_index_size)
129
3
            .tag("input_rowsets_total_size", _input_rowsets_total_size)
130
3
            .tag("tablet_max_version", cloud_tablet()->max_version_unlocked())
131
3
            .tag("cumulative_point", cloud_tablet()->cumulative_layer_point())
132
3
            .tag("num_rowsets", cloud_tablet()->fetch_add_approximate_num_rowsets(0))
133
3
            .tag("cumu_num_rowsets", cloud_tablet()->fetch_add_approximate_cumu_num_rowsets(0));
134
3
    return st;
135
3
}
136
137
0
Status CloudCumulativeCompaction::request_global_lock() {
138
    // prepare compaction job
139
0
    cloud::TabletJobInfoPB job;
140
0
    auto idx = job.mutable_idx();
141
0
    idx->set_tablet_id(_tablet->tablet_id());
142
0
    idx->set_table_id(_tablet->table_id());
143
0
    idx->set_index_id(_tablet->index_id());
144
0
    idx->set_partition_id(_tablet->partition_id());
145
0
    auto compaction_job = job.add_compaction();
146
0
    compaction_job->set_id(_uuid);
147
0
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
148
0
                                  std::to_string(config::heartbeat_service_port));
149
0
    compaction_job->set_type(cloud::TabletCompactionJobPB::CUMULATIVE);
150
0
    compaction_job->set_base_compaction_cnt(_base_compaction_cnt);
151
0
    compaction_job->set_cumulative_compaction_cnt(_cumulative_compaction_cnt);
152
0
    using namespace std::chrono;
153
0
    int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
154
0
    _expiration = now + config::compaction_timeout_seconds;
155
0
    compaction_job->set_expiration(_expiration);
156
0
    compaction_job->set_lease(now + config::lease_compaction_interval_seconds * 4);
157
158
0
    compaction_job->add_input_versions(_input_rowsets.front()->start_version());
159
0
    compaction_job->add_input_versions(_input_rowsets.back()->end_version());
160
    // Set input version range to let meta-service check version range conflict
161
0
    compaction_job->set_check_input_versions_range(config::enable_parallel_cumu_compaction);
162
0
    cloud::StartTabletJobResponse resp;
163
0
    Status st = _engine.meta_mgr().prepare_tablet_job(job, &resp);
164
0
    if (!st.ok()) {
165
0
        if (resp.status().code() == cloud::STALE_TABLET_CACHE) {
166
            // set last_sync_time to 0 to force sync tablet next time
167
0
            cloud_tablet()->last_sync_time_s = 0;
168
0
        } else if (resp.status().code() == cloud::TABLET_NOT_FOUND) {
169
            // tablet not found
170
0
            cloud_tablet()->clear_cache();
171
0
        } else if (resp.status().code() == cloud::JOB_TABLET_BUSY) {
172
0
            LOG_WARNING("failed to prepare cumu compaction")
173
0
                    .tag("job_id", _uuid)
174
0
                    .tag("msg", resp.status().msg());
175
0
            return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>(
176
0
                    "cumu no suitable versions: job tablet busy");
177
0
        } else if (resp.status().code() == cloud::JOB_CHECK_ALTER_VERSION) {
178
0
            (static_cast<CloudTablet*>(_tablet.get()))->set_alter_version(resp.alter_version());
179
0
            std::stringstream ss;
180
0
            ss << "failed to prepare cumu compaction. Check compaction input versions "
181
0
                  "failed in schema change. "
182
0
                  "input_version_start="
183
0
               << compaction_job->input_versions(0)
184
0
               << " input_version_end=" << compaction_job->input_versions(1)
185
0
               << " schema_change_alter_version=" << resp.alter_version();
186
0
            std::string msg = ss.str();
187
0
            LOG(WARNING) << msg;
188
0
            return Status::InternalError(msg);
189
0
        }
190
0
    }
191
0
    return st;
192
0
}
193
194
0
Status CloudCumulativeCompaction::execute_compact() {
195
0
    TEST_SYNC_POINT_RETURN_WITH_VALUE("CloudCumulativeCompaction::execute_compact_impl",
196
0
                                      Status::OK(), this);
197
198
0
    SCOPED_ATTACH_TASK(_mem_tracker);
199
200
0
    using namespace std::chrono;
201
0
    auto start = steady_clock::now();
202
0
    Status st;
203
0
    Defer defer_set_st([&] {
204
0
        cloud_tablet()->set_last_cumu_compaction_status(st.to_string());
205
0
        if (!st.ok()) {
206
0
            cloud_tablet()->set_last_cumu_compaction_failure_time(UnixMillis());
207
0
        } else {
208
0
            cloud_tablet()->set_last_cumu_compaction_success_time(UnixMillis());
209
0
        }
210
0
    });
211
0
    st = CloudCompactionMixin::execute_compact();
212
0
    if (!st.ok()) {
213
0
        LOG(WARNING) << "fail to do " << compaction_name() << ". res=" << st
214
0
                     << ", tablet=" << _tablet->tablet_id()
215
0
                     << ", output_version=" << _output_version;
216
0
        return st;
217
0
    }
218
0
    LOG_INFO("finish CloudCumulativeCompaction, tablet_id={}, cost={}ms, range=[{}-{}]",
219
0
             _tablet->tablet_id(), duration_cast<milliseconds>(steady_clock::now() - start).count(),
220
0
             _input_rowsets.front()->start_version(), _input_rowsets.back()->end_version())
221
0
            .tag("job_id", _uuid)
222
0
            .tag("input_rowsets", _input_rowsets.size())
223
0
            .tag("input_rows", _input_row_num)
224
0
            .tag("input_segments", _input_segments)
225
0
            .tag("input_rowsets_data_size", _input_rowsets_data_size)
226
0
            .tag("input_rowsets_index_size", _input_rowsets_index_size)
227
0
            .tag("input_rowsets_total_size", _input_rowsets_total_size)
228
0
            .tag("output_rows", _output_rowset->num_rows())
229
0
            .tag("output_segments", _output_rowset->num_segments())
230
0
            .tag("output_rowset_data_size", _output_rowset->data_disk_size())
231
0
            .tag("output_rowset_index_size", _output_rowset->index_disk_size())
232
0
            .tag("output_rowset_total_size", _output_rowset->total_disk_size())
233
0
            .tag("tablet_max_version", _tablet->max_version_unlocked())
234
0
            .tag("cumulative_point", cloud_tablet()->cumulative_layer_point())
235
0
            .tag("num_rowsets", cloud_tablet()->fetch_add_approximate_num_rowsets(0))
236
0
            .tag("cumu_num_rowsets", cloud_tablet()->fetch_add_approximate_cumu_num_rowsets(0))
237
0
            .tag("local_read_time_us", _stats.cloud_local_read_time)
238
0
            .tag("remote_read_time_us", _stats.cloud_remote_read_time)
239
0
            .tag("local_read_bytes", _local_read_bytes_total)
240
0
            .tag("remote_read_bytes", _remote_read_bytes_total);
241
242
0
    _state = CompactionState::SUCCESS;
243
244
0
    DorisMetrics::instance()->cumulative_compaction_deltas_total->increment(_input_rowsets.size());
245
0
    DorisMetrics::instance()->cumulative_compaction_bytes_total->increment(
246
0
            _input_rowsets_total_size);
247
0
    cumu_output_size << _output_rowset->total_disk_size();
248
249
0
    st = Status::OK();
250
0
    return st;
251
0
}
252
253
0
Status CloudCumulativeCompaction::modify_rowsets() {
254
    // calculate new cumulative point
255
0
    int64_t prepare_max_conflict_version = _max_conflict_version;
256
0
    int64_t max_conflict_version = _refresh_conflict_versions();
257
0
    int64_t input_cumulative_point;
258
0
    bool output_already_passed;
259
0
    std::vector<RowsetSharedPtr> rowsets;
260
0
    {
261
0
        std::shared_lock rlock(_tablet->get_header_lock());
262
0
        input_cumulative_point = cloud_tablet()->cumulative_layer_point();
263
0
        DORIS_CHECK(input_cumulative_point <= _output_rowset->start_version() ||
264
0
                    input_cumulative_point > _output_rowset->end_version());
265
0
        output_already_passed = input_cumulative_point > _output_rowset->end_version();
266
0
        if (!output_already_passed && (input_cumulative_point < _output_rowset->start_version() ||
267
0
                                       max_conflict_version > _output_rowset->end_version())) {
268
0
            cloud_tablet()->traverse_rowsets_unlocked(
269
0
                    [&rowsets, input_cumulative_point,
270
0
                     output_start_version = _output_rowset->start_version(),
271
0
                     output_end_version = _output_rowset->end_version(),
272
0
                     max_conflict_version](const RowsetSharedPtr& rowset) {
273
0
                        if (rowset->start_version() < input_cumulative_point) {
274
0
                            return;
275
0
                        }
276
0
                        bool is_preceding = rowset->end_version() < output_start_version;
277
0
                        bool is_following = rowset->start_version() > output_end_version &&
278
0
                                            rowset->end_version() <= max_conflict_version;
279
0
                        if (is_preceding || is_following) {
280
0
                            rowsets.push_back(rowset);
281
0
                        }
282
0
                    });
283
0
        }
284
0
    }
285
0
    int64_t new_cumulative_point = input_cumulative_point;
286
0
    if (!output_already_passed) {
287
0
        rowsets.push_back(_output_rowset);
288
0
        std::sort(rowsets.begin(), rowsets.end(), Rowset::comparator);
289
0
        auto compaction_policy = cloud_tablet()->tablet_meta()->compaction_policy();
290
0
        new_cumulative_point =
291
0
                _engine.cumu_compaction_policy(compaction_policy)
292
0
                        ->calculate_cumulative_point(cloud_tablet(), rowsets, _output_rowset,
293
0
                                                     _last_delete_version, input_cumulative_point);
294
0
    }
295
0
    LOG_INFO("calculate cumulative point for CloudCumulativeCompaction")
296
0
            .tag("job_id", _uuid)
297
0
            .tag("tablet_id", _tablet->tablet_id())
298
0
            .tag("input_cumulative_point", input_cumulative_point)
299
0
            .tag("new_cumulative_point", new_cumulative_point)
300
0
            .tag("output_rowset_start_version", _output_rowset->start_version())
301
0
            .tag("output_rowset_end_version", _output_rowset->end_version())
302
0
            .tag("rowsets", rowsets.size())
303
0
            .tag("prepare_max_conflict_version", prepare_max_conflict_version)
304
0
            .tag("max_conflict_version", max_conflict_version);
305
    // commit compaction job
306
0
    cloud::TabletJobInfoPB job;
307
0
    auto idx = job.mutable_idx();
308
0
    idx->set_tablet_id(_tablet->tablet_id());
309
0
    idx->set_table_id(_tablet->table_id());
310
0
    idx->set_index_id(_tablet->index_id());
311
0
    idx->set_partition_id(_tablet->partition_id());
312
0
    auto compaction_job = job.add_compaction();
313
0
    compaction_job->set_id(_uuid);
314
0
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
315
0
                                  std::to_string(config::heartbeat_service_port));
316
0
    compaction_job->set_type(cloud::TabletCompactionJobPB::CUMULATIVE);
317
0
    compaction_job->set_input_cumulative_point(input_cumulative_point);
318
0
    compaction_job->set_output_cumulative_point(new_cumulative_point);
319
0
    compaction_job->set_num_input_rows(_input_row_num);
320
0
    compaction_job->set_num_output_rows(_output_rowset->num_rows());
321
0
    compaction_job->set_size_input_rowsets(_input_rowsets_total_size);
322
0
    compaction_job->set_size_output_rowsets(_output_rowset->total_disk_size());
323
0
    compaction_job->set_num_input_segments(_input_segments);
324
0
    compaction_job->set_num_output_segments(_output_rowset->num_segments());
325
0
    compaction_job->set_num_input_rowsets(num_input_rowsets());
326
0
    compaction_job->set_num_output_rowsets(1);
327
0
    compaction_job->add_input_versions(_input_rowsets.front()->start_version());
328
0
    compaction_job->add_input_versions(_input_rowsets.back()->end_version());
329
0
    compaction_job->add_output_versions(_output_rowset->end_version());
330
0
    compaction_job->add_txn_id(_output_rowset->txn_id());
331
0
    compaction_job->add_output_rowset_ids(_output_rowset->rowset_id().to_string());
332
0
    compaction_job->set_index_size_input_rowsets(_input_rowsets_index_size);
333
0
    compaction_job->set_segment_size_input_rowsets(_input_rowsets_data_size);
334
0
    compaction_job->set_index_size_output_rowsets(_output_rowset->index_disk_size());
335
0
    compaction_job->set_segment_size_output_rowsets(_output_rowset->data_disk_size());
336
337
0
    DBUG_EXECUTE_IF("CloudCumulativeCompaction::modify_rowsets.enable_spin_wait", {
338
0
        LOG(INFO) << "CloudCumulativeCompaction::modify_rowsets.enable_spin_wait, start";
339
0
        while (DebugPoints::instance()->is_enable(
340
0
                "CloudCumulativeCompaction::modify_rowsets.block")) {
341
0
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
342
0
        }
343
0
        LOG(INFO) << "CloudCumulativeCompaction::modify_rowsets.enable_spin_wait, exit";
344
0
    });
345
346
    // Block only NOTREADY tablets (SC new tablets) before compaction commit.
347
    // RUNNING tablets (system tables, base tablets) are not affected.
348
0
    DBUG_EXECUTE_IF("CloudCumulativeCompaction::modify_rowsets.block_notready", {
349
0
        if (_tablet->tablet_state() == TABLET_NOTREADY) {
350
0
            LOG(INFO) << "block NOTREADY tablet compaction before commit"
351
0
                      << ", tablet_id=" << _tablet->tablet_id() << ", output=["
352
0
                      << _input_rowsets.front()->start_version() << "-"
353
0
                      << _input_rowsets.back()->end_version() << "]";
354
0
            while (DebugPoints::instance()->is_enable(
355
0
                    "CloudCumulativeCompaction::modify_rowsets.block_notready")) {
356
0
                std::this_thread::sleep_for(std::chrono::milliseconds(50));
357
0
            }
358
0
            LOG(INFO) << "release NOTREADY tablet compaction, tablet_id=" << _tablet->tablet_id();
359
0
        }
360
0
    });
361
362
0
    DBUG_EXECUTE_IF("CloudCumulativeCompaction::modify_rowsets.random_sleep", {
363
0
        auto probability = dp->param("probability", dp->param("percent", 0.0));
364
0
        DORIS_CHECK(probability >= 0.0 && probability <= 1.0);
365
0
        static thread_local std::mt19937 gen(std::random_device {}());
366
0
        std::bernoulli_distribution inject_sleep {probability};
367
0
        if (inject_sleep(gen)) {
368
0
            auto max_sleep_ms = dp->param<int64_t>(
369
0
                    "max_sleep_ms", dp->param<int64_t>("max_sleep_time_ms",
370
0
                                                       dp->param<int64_t>("max_sleep_time", 0)));
371
0
            DORIS_CHECK(max_sleep_ms >= 0);
372
0
            std::uniform_int_distribution<int64_t> sleep_dist(0, max_sleep_ms);
373
0
            auto sleep_ms = sleep_dist(gen);
374
0
            LOG(INFO) << "CloudCumulativeCompaction::modify_rowsets.random_sleep"
375
0
                      << ", tablet_id=" << _tablet->tablet_id() << ", sleep_ms=" << sleep_ms
376
0
                      << ", probability=" << probability;
377
0
            std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
378
0
        }
379
0
    });
380
381
0
    DBUG_EXECUTE_IF("CloudCumulativeCompaction::modify_rowsets.random_fail", {
382
0
        auto probability = dp->param("probability", dp->param("percent", 0.0));
383
0
        DORIS_CHECK(probability >= 0.0 && probability <= 1.0);
384
0
        static thread_local std::mt19937 gen(std::random_device {}());
385
0
        std::bernoulli_distribution inject_fail {probability};
386
0
        if (inject_fail(gen)) {
387
0
            LOG(WARNING) << "CloudCumulativeCompaction::modify_rowsets.random_fail"
388
0
                         << ", tablet_id=" << _tablet->tablet_id()
389
0
                         << ", probability=" << probability;
390
0
            return Status::InternalError(
391
0
                    "debug cloud cumulative compaction modify rowsets random failed");
392
0
        }
393
0
    });
394
395
0
    DeleteBitmapPtr output_rowset_delete_bitmap = nullptr;
396
0
    int64_t initiator = this->initiator();
397
0
    int64_t get_delete_bitmap_lock_start_time = 0;
398
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
399
0
        _tablet->enable_unique_key_merge_on_write()) {
400
0
        RETURN_IF_ERROR(cloud_tablet()->calc_delete_bitmap_for_compaction(
401
0
                _input_rowsets, _output_rowset, *_rowid_conversion, compaction_type(),
402
0
                _stats.merged_rows, _stats.filtered_rows, initiator, output_rowset_delete_bitmap,
403
0
                _allow_delete_in_cumu_compaction, get_delete_bitmap_lock_start_time));
404
0
        LOG_INFO("update delete bitmap in CloudCumulativeCompaction, tablet_id={}, range=[{}-{}]",
405
0
                 _tablet->tablet_id(), _input_rowsets.front()->start_version(),
406
0
                 _input_rowsets.back()->end_version())
407
0
                .tag("job_id", _uuid)
408
0
                .tag("initiator", initiator)
409
0
                .tag("input_rowsets", _input_rowsets.size())
410
0
                .tag("input_rows", _input_row_num)
411
0
                .tag("input_segments", _input_segments)
412
0
                .tag("number_output_delete_bitmap",
413
0
                     output_rowset_delete_bitmap->delete_bitmap.size());
414
0
        compaction_job->set_delete_bitmap_lock_initiator(initiator);
415
0
    }
416
417
0
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.trigger_abort_job_failed", {
418
0
        LOG(INFO) << "CumulativeCompaction.modify_rowsets.trigger_abort_job_failed for tablet_id"
419
0
                  << cloud_tablet()->tablet_id();
420
0
        return Status::InternalError(
421
0
                "CumulativeCompaction.modify_rowsets.trigger_abort_job_failed for tablet_id {}",
422
0
                cloud_tablet()->tablet_id());
423
0
    });
424
0
    cloud::FinishTabletJobResponse resp;
425
0
    auto st = _engine.meta_mgr().commit_tablet_job(job, &resp);
426
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
427
0
        _tablet->enable_unique_key_merge_on_write()) {
428
0
        int64_t hold_delete_bitmap_lock_time_ms =
429
0
                (MonotonicMicros() - get_delete_bitmap_lock_start_time) / 1000;
430
0
        g_cu_compaction_hold_delete_bitmap_lock_time_ms << hold_delete_bitmap_lock_time_ms;
431
0
    }
432
0
    if (resp.has_alter_version()) {
433
0
        (static_cast<CloudTablet*>(_tablet.get()))->set_alter_version(resp.alter_version());
434
0
    }
435
0
    if (!st.ok()) {
436
0
        if (resp.status().code() == cloud::TABLET_NOT_FOUND) {
437
0
            cloud_tablet()->clear_cache();
438
0
        } else if (resp.status().code() == cloud::JOB_CHECK_ALTER_VERSION) {
439
0
            std::stringstream ss;
440
0
            ss << "failed to prepare cumu compaction. Check compaction input versions "
441
0
                  "failed in schema change. "
442
0
                  "input_version_start="
443
0
               << compaction_job->input_versions(0)
444
0
               << " input_version_end=" << compaction_job->input_versions(1)
445
0
               << " schema_change_alter_version=" << resp.alter_version();
446
0
            std::string msg = ss.str();
447
0
            LOG(WARNING) << msg;
448
0
            return Status::InternalError(msg);
449
0
        }
450
0
        return st;
451
0
    }
452
453
0
    auto& stats = resp.stats();
454
0
    LOG(INFO) << "tablet stats=" << stats.ShortDebugString();
455
0
    {
456
0
        std::unique_lock wrlock(_tablet->get_header_lock());
457
        // clang-format off
458
0
        cloud_tablet()->set_last_base_compaction_success_time(std::max(cloud_tablet()->last_base_compaction_success_time(), stats.last_base_compaction_time_ms()));
459
0
        cloud_tablet()->set_last_cumu_compaction_success_time(std::max(cloud_tablet()->last_cumu_compaction_success_time(), stats.last_cumu_compaction_time_ms()));
460
0
        cloud_tablet()->set_last_full_compaction_success_time(std::max(cloud_tablet()->last_full_compaction_success_time(), stats.last_full_compaction_time_ms()));
461
        // clang-format on
462
0
        if (cloud_tablet()->cumulative_compaction_cnt() >= stats.cumulative_compaction_cnt()) {
463
            // This could happen while calling `sync_tablet_rowsets` during `commit_tablet_job`, or parallel cumu compactions which are
464
            // committed later increase tablet.cumulative_compaction_cnt (see CloudCompactionTest.parallel_cumu_compaction)
465
0
            return Status::OK();
466
0
        }
467
        // Try to make output rowset visible immediately in tablet cache, instead of waiting for next synchronization from meta-service.
468
0
        if (stats.cumulative_point() > cloud_tablet()->cumulative_layer_point() &&
469
0
            stats.cumulative_compaction_cnt() != cloud_tablet()->cumulative_compaction_cnt() + 1) {
470
            // This could happen when there are multiple parallel cumu compaction committed, tablet cache lags several
471
            // cumu compactions behind meta-service (stats.cumulative_compaction_cnt > tablet.cumulative_compaction_cnt + 1).
472
            // If `cumu_point` of the tablet cache also falls behind, MUST ONLY synchronize tablet cache from meta-service,
473
            // otherwise may cause the tablet to be unable to synchronize the rowset meta changes generated by other cumu compaction.
474
0
            return Status::OK();
475
0
        }
476
0
        if (_input_rowsets.size() == 1) {
477
0
            DCHECK_EQ(_output_rowset->version(), _input_rowsets[0]->version());
478
            // MUST NOT move input rowset to stale path
479
0
            cloud_tablet()->add_rowsets({_output_rowset}, true, wrlock, true);
480
0
        } else {
481
0
            cloud_tablet()->delete_rowsets(_input_rowsets, wrlock);
482
0
            cloud_tablet()->add_rowsets({_output_rowset}, false, wrlock);
483
0
        }
484
        // ATTN: MUST NOT update `base_compaction_cnt` which are used when sync rowsets, otherwise may cause
485
        // the tablet to be unable to synchronize the rowset meta changes generated by base compaction.
486
0
        cloud_tablet()->set_cumulative_compaction_cnt(stats.cumulative_compaction_cnt());
487
0
        cloud_tablet()->set_cumulative_layer_point(stats.cumulative_point());
488
0
        if (output_rowset_delete_bitmap) {
489
0
            _tablet->tablet_meta()->delete_bitmap().merge(*output_rowset_delete_bitmap);
490
0
        }
491
0
        if (stats.base_compaction_cnt() >= cloud_tablet()->base_compaction_cnt()) {
492
0
            cloud_tablet()->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
493
0
                                                    stats.num_rows(), stats.data_size());
494
0
        }
495
0
    }
496
    // agg delete bitmap for pre rowsets
497
0
    if (config::enable_agg_and_remove_pre_rowsets_delete_bitmap &&
498
0
        _tablet->keys_type() == KeysType::UNIQUE_KEYS &&
499
0
        _tablet->enable_unique_key_merge_on_write() && _input_rowsets.size() != 1) {
500
0
        OlapStopWatch watch;
501
0
        std::vector<RowsetSharedPtr> pre_rowsets {};
502
0
        {
503
0
            std::shared_lock rlock(_tablet->get_header_lock());
504
0
            for (const auto& it2 : cloud_tablet()->rowset_map()) {
505
0
                if (it2.first.second < _output_rowset->start_version()) {
506
0
                    pre_rowsets.emplace_back(it2.second);
507
0
                }
508
0
            }
509
0
        }
510
0
        std::sort(pre_rowsets.begin(), pre_rowsets.end(), Rowset::comparator);
511
0
        auto pre_rowsets_delete_bitmap = std::make_shared<DeleteBitmap>(_tablet->tablet_id());
512
0
        std::map<std::string, int64_t> pre_rowset_to_versions;
513
0
        cloud_tablet()->agg_delete_bitmap_for_compaction(
514
0
                _output_rowset->start_version(), _output_rowset->end_version(), pre_rowsets,
515
0
                pre_rowsets_delete_bitmap, pre_rowset_to_versions);
516
        // update delete bitmap to ms
517
0
        DBUG_EXECUTE_IF(
518
0
                "CumulativeCompaction.modify_rowsets.cloud_update_delete_bitmap_without_lock.block",
519
0
                DBUG_BLOCK);
520
0
        auto status = _engine.meta_mgr().cloud_update_delete_bitmap_without_lock(
521
0
                *cloud_tablet(), pre_rowsets_delete_bitmap.get(), pre_rowset_to_versions,
522
0
                cloud_tablet()->table_id(), _output_rowset->start_version(),
523
0
                _output_rowset->end_version());
524
0
        if (!status.ok()) {
525
0
            LOG(WARNING) << "failed to agg pre rowsets delete bitmap to ms. tablet_id="
526
0
                         << _tablet->tablet_id() << ", pre rowset num=" << pre_rowsets.size()
527
0
                         << ", output version=" << _output_rowset->version().to_string()
528
0
                         << ", status=" << status.to_string();
529
0
        } else {
530
0
            LOG(INFO) << "agg pre rowsets delete bitmap to ms. tablet_id=" << _tablet->tablet_id()
531
0
                      << ", pre rowset num=" << pre_rowsets.size()
532
0
                      << ", output version=" << _output_rowset->version().to_string()
533
0
                      << ", cost(us)=" << watch.get_elapse_time_us();
534
0
        }
535
0
    }
536
0
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.delete_expired_stale_rowset", {
537
0
        LOG(INFO) << "delete_expired_stale_rowsets for tablet=" << _tablet->tablet_id();
538
0
        _engine.tablet_mgr().vacuum_stale_rowsets(CountDownLatch(1));
539
0
    });
540
541
0
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
542
0
    return Status::OK();
543
0
}
544
545
0
Status CloudCumulativeCompaction::garbage_collection() {
546
0
    RETURN_IF_ERROR(CloudCompactionMixin::garbage_collection());
547
0
    cloud::TabletJobInfoPB job;
548
0
    auto idx = job.mutable_idx();
549
0
    idx->set_tablet_id(_tablet->tablet_id());
550
0
    idx->set_table_id(_tablet->table_id());
551
0
    idx->set_index_id(_tablet->index_id());
552
0
    idx->set_partition_id(_tablet->partition_id());
553
0
    auto compaction_job = job.add_compaction();
554
0
    compaction_job->set_id(_uuid);
555
0
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
556
0
                                  std::to_string(config::heartbeat_service_port));
557
0
    compaction_job->set_type(cloud::TabletCompactionJobPB::CUMULATIVE);
558
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
559
0
        _tablet->enable_unique_key_merge_on_write()) {
560
0
        compaction_job->set_delete_bitmap_lock_initiator(this->initiator());
561
0
    }
562
0
    DBUG_EXECUTE_IF("CumulativeCompaction.modify_rowsets.trigger_abort_job_failed", {
563
0
        LOG(INFO) << "CumulativeCompaction.modify_rowsets.abort_job_failed for tablet_id"
564
0
                  << cloud_tablet()->tablet_id();
565
0
        return Status::InternalError(
566
0
                "CumulativeCompaction.modify_rowsets.abort_job_failed for tablet_id {}",
567
0
                cloud_tablet()->tablet_id());
568
0
    });
569
0
    auto st = _engine.meta_mgr().abort_tablet_job(job);
570
0
    if (!st.ok()) {
571
0
        LOG_WARNING("failed to abort compaction job")
572
0
                .tag("job_id", _uuid)
573
0
                .tag("tablet_id", _tablet->tablet_id())
574
0
                .error(st);
575
0
    }
576
0
    return st;
577
0
}
578
579
3
Status CloudCumulativeCompaction::pick_rowsets_to_compact() {
580
3
    _input_rowsets.clear();
581
582
3
    int64_t min_conflict_version = _min_conflict_version;
583
3
    int64_t max_conflict_version = _max_conflict_version;
584
3
    int64_t max_score = config::cumulative_compaction_max_deltas;
585
3
    double process_memory_usage =
586
3
            cast_set<double>(doris::GlobalMemoryArbitrator::process_memory_usage());
587
3
    bool memory_usage_high =
588
3
            process_memory_usage > cast_set<double>(MemInfo::soft_mem_limit()) * 0.8;
589
3
    if (cloud_tablet()->last_compaction_status.is<ErrorCode::MEM_LIMIT_EXCEEDED>() ||
590
3
        memory_usage_high) {
591
0
        max_score = std::max(config::cumulative_compaction_max_deltas /
592
0
                                     config::cumulative_compaction_max_deltas_factor,
593
0
                             config::cumulative_compaction_min_deltas + 1);
594
0
    }
595
596
3
    auto compaction_policy = cloud_tablet()->tablet_meta()->compaction_policy();
597
5
    auto pick_from_candidates = [&](std::vector<RowsetSharedPtr>& candidates) {
598
5
        _input_rowsets.clear();
599
5
        _last_delete_version = Version {-1, -1};
600
601
5
        if (candidates.empty()) {
602
1
            return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>(
603
1
                    "no suitable versions: candidate rowsets empty");
604
1
        }
605
4
        std::sort(candidates.begin(), candidates.end(), Rowset::comparator);
606
4
        if (auto st = check_version_continuity(candidates); !st.ok()) {
607
0
            DCHECK(false) << st;
608
0
            return st;
609
0
        }
610
611
4
        size_t compaction_score = 0;
612
4
        _engine.cumu_compaction_policy(compaction_policy)
613
4
                ->pick_input_rowsets(cloud_tablet(), candidates, max_score,
614
4
                                     config::cumulative_compaction_min_deltas, &_input_rowsets,
615
4
                                     &_last_delete_version, &compaction_score);
616
617
4
        if (_input_rowsets.empty()) {
618
1
            return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>(
619
1
                    "no suitable versions: input rowsets empty");
620
3
        } else if (_input_rowsets.size() == 1 &&
621
3
                   !_input_rowsets.front()->rowset_meta()->is_segments_overlapping()) {
622
0
            VLOG_DEBUG << "there is only one rowset and not overlapping. tablet_id="
623
0
                       << _tablet->tablet_id() << ", version=" << _input_rowsets.front()->version();
624
0
            _input_rowsets.clear();
625
0
            return Status::Error<CUMULATIVE_NO_SUITABLE_VERSION>(
626
0
                    "no suitable versions: only one rowset and not overlapping");
627
0
        }
628
3
        return Status::OK();
629
4
    };
630
631
5
    auto pick_from_version_range = [&](int64_t start_version, int64_t end_version) {
632
5
        std::vector<RowsetSharedPtr> candidates;
633
5
        {
634
5
            std::shared_lock rlock(_tablet->get_header_lock());
635
5
            _base_compaction_cnt = cloud_tablet()->base_compaction_cnt();
636
5
            _cumulative_compaction_cnt = cloud_tablet()->cumulative_compaction_cnt();
637
5
            int64_t range_start_version =
638
5
                    std::max(std::max(cloud_tablet()->cumulative_layer_point(), start_version),
639
5
                             cloud_tablet()->alter_version() + 1);
640
            // Get candidate rowsets from the selected non-conflicting version range.
641
5
            cloud_tablet()->traverse_rowsets_unlocked(
642
39
                    [&candidates, range_start_version, end_version](const RowsetSharedPtr& rs) {
643
39
                        if (rs->start_version() >= range_start_version &&
644
39
                            rs->start_version() < end_version) {
645
9
                            candidates.push_back(rs);
646
9
                        }
647
39
                    });
648
5
        }
649
5
        return pick_from_candidates(candidates);
650
5
    };
651
652
    // pick_from_version_range clamps the lower bound by cumulative point and alter version.
653
3
    auto st = pick_from_version_range(0, min_conflict_version);
654
3
    if (!st.ok()) {
655
2
        if (!st.is<CUMULATIVE_NO_SUITABLE_VERSION>() ||
656
2
            min_conflict_version == std::numeric_limits<int64_t>::max()) {
657
0
            return st;
658
0
        }
659
2
        st = pick_from_version_range(max_conflict_version + 1, std::numeric_limits<int64_t>::max());
660
2
        RETURN_IF_ERROR(st);
661
2
    }
662
663
3
    apply_txn_size_truncation_and_log("CloudCumulativeCompaction");
664
3
    return Status::OK();
665
3
}
666
667
0
void CloudCumulativeCompaction::update_cumulative_point() {
668
0
    cloud::TabletJobInfoPB job;
669
0
    auto idx = job.mutable_idx();
670
0
    idx->set_tablet_id(_tablet->tablet_id());
671
0
    idx->set_table_id(_tablet->table_id());
672
0
    idx->set_index_id(_tablet->index_id());
673
0
    idx->set_partition_id(_tablet->partition_id());
674
0
    auto compaction_job = job.add_compaction();
675
0
    compaction_job->set_id(_uuid);
676
0
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
677
0
                                  std::to_string(config::heartbeat_service_port));
678
0
    compaction_job->set_type(cloud::TabletCompactionJobPB::EMPTY_CUMULATIVE);
679
0
    compaction_job->set_base_compaction_cnt(_base_compaction_cnt);
680
0
    compaction_job->set_cumulative_compaction_cnt(_cumulative_compaction_cnt);
681
0
    int64_t now = time(nullptr);
682
0
    compaction_job->set_lease(now + config::lease_compaction_interval_seconds);
683
    // No need to set expiration time, since there is no output rowset
684
0
    cloud::StartTabletJobResponse start_resp;
685
0
    auto st = _engine.meta_mgr().prepare_tablet_job(job, &start_resp);
686
0
    if (!st.ok()) {
687
0
        if (start_resp.status().code() == cloud::STALE_TABLET_CACHE) {
688
            // set last_sync_time to 0 to force sync tablet next time
689
0
            cloud_tablet()->last_sync_time_s = 0;
690
0
        } else if (start_resp.status().code() == cloud::TABLET_NOT_FOUND) {
691
            // tablet not found
692
0
            cloud_tablet()->clear_cache();
693
0
        }
694
0
        LOG_WARNING("failed to update cumulative point to meta srv")
695
0
                .tag("job_id", _uuid)
696
0
                .tag("tablet_id", _tablet->tablet_id())
697
0
                .error(st);
698
0
        return;
699
0
    }
700
0
    int64_t input_cumulative_point = cloud_tablet()->cumulative_layer_point();
701
0
    int64_t output_cumulative_point = _last_delete_version.first + 1;
702
0
    compaction_job->set_input_cumulative_point(input_cumulative_point);
703
0
    compaction_job->set_output_cumulative_point(output_cumulative_point);
704
0
    cloud::FinishTabletJobResponse finish_resp;
705
0
    st = _engine.meta_mgr().commit_tablet_job(job, &finish_resp);
706
0
    if (!st.ok()) {
707
0
        if (finish_resp.status().code() == cloud::TABLET_NOT_FOUND) {
708
0
            cloud_tablet()->clear_cache();
709
0
        }
710
0
        LOG_WARNING("failed to update cumulative point to meta srv")
711
0
                .tag("job_id", _uuid)
712
0
                .tag("tablet_id", _tablet->tablet_id())
713
0
                .error(st);
714
0
        return;
715
0
    }
716
0
    LOG_INFO("do empty cumulative compaction to update cumulative point")
717
0
            .tag("job_id", _uuid)
718
0
            .tag("tablet_id", _tablet->tablet_id())
719
0
            .tag("input_cumulative_point", input_cumulative_point)
720
0
            .tag("output_cumulative_point", output_cumulative_point);
721
0
    auto& stats = finish_resp.stats();
722
0
    LOG(INFO) << "tablet stats=" << stats.ShortDebugString();
723
0
    {
724
0
        std::lock_guard wrlock(_tablet->get_header_lock());
725
        // clang-format off
726
0
        cloud_tablet()->set_last_base_compaction_success_time(std::max(cloud_tablet()->last_base_compaction_success_time(), stats.last_base_compaction_time_ms()));
727
0
        cloud_tablet()->set_last_cumu_compaction_success_time(std::max(cloud_tablet()->last_cumu_compaction_success_time(), stats.last_cumu_compaction_time_ms()));
728
        // clang-format on
729
0
        if (cloud_tablet()->cumulative_compaction_cnt() >= stats.cumulative_compaction_cnt()) {
730
            // This could happen while calling `sync_tablet_rowsets` during `commit_tablet_job`
731
0
            return;
732
0
        }
733
        // ATTN: MUST NOT update `base_compaction_cnt` which are used when sync rowsets, otherwise may cause
734
        // the tablet to be unable to synchronize the rowset meta changes generated by base compaction.
735
0
        cloud_tablet()->set_cumulative_compaction_cnt(cloud_tablet()->cumulative_compaction_cnt() +
736
0
                                                      1);
737
0
        cloud_tablet()->set_cumulative_layer_point(stats.cumulative_point());
738
0
        if (stats.base_compaction_cnt() >= cloud_tablet()->base_compaction_cnt()) {
739
0
            cloud_tablet()->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
740
0
                                                    stats.num_rows(), stats.data_size());
741
0
        }
742
0
    }
743
0
}
744
745
0
void CloudCumulativeCompaction::do_lease() {
746
0
    TEST_INJECTION_POINT_RETURN_WITH_VOID("CloudCumulativeCompaction::do_lease");
747
0
    if (_state == CompactionState::SUCCESS) {
748
0
        return;
749
0
    }
750
0
    cloud::TabletJobInfoPB job;
751
0
    auto idx = job.mutable_idx();
752
0
    idx->set_tablet_id(_tablet->tablet_id());
753
0
    idx->set_table_id(_tablet->table_id());
754
0
    idx->set_index_id(_tablet->index_id());
755
0
    idx->set_partition_id(_tablet->partition_id());
756
0
    auto compaction_job = job.add_compaction();
757
0
    compaction_job->set_id(_uuid);
758
0
    using namespace std::chrono;
759
0
    int64_t lease_time = duration_cast<seconds>(system_clock::now().time_since_epoch()).count() +
760
0
                         config::lease_compaction_interval_seconds * 4;
761
0
    compaction_job->set_lease(lease_time);
762
0
    auto st = _engine.meta_mgr().lease_tablet_job(job);
763
0
    if (!st.ok()) {
764
0
        LOG_WARNING("failed to lease compaction job")
765
0
                .tag("job_id", _uuid)
766
0
                .tag("tablet_id", _tablet->tablet_id())
767
0
                .error(st);
768
0
    }
769
0
}
770
771
} // namespace doris