Coverage Report

Created: 2026-07-23 18:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_base_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_base_compaction.h"
19
20
#include <gen_cpp/cloud.pb.h>
21
22
#include <algorithm>
23
#include <boost/container_hash/hash.hpp>
24
25
#include "cloud/cloud_meta_mgr.h"
26
#include "cloud/config.h"
27
#include "common/config.h"
28
#include "core/value/vdatetime_value.h"
29
#include "cpp/sync_point.h"
30
#include "service/backend_options.h"
31
#include "storage/compaction/compaction.h"
32
#include "storage/task/engine_checksum_task.h"
33
#include "util/thread.h"
34
#include "util/uuid_generator.h"
35
36
namespace doris {
37
using namespace ErrorCode;
38
39
bvar::Adder<uint64_t> base_output_size("base_compaction", "output_size");
40
bvar::Adder<uint64_t> base_input_cached_size("base_compaction", "input_cached_size");
41
bvar::Adder<uint64_t> base_input_size("base_compaction", "input_size");
42
bvar::LatencyRecorder g_base_compaction_hold_delete_bitmap_lock_time_ms(
43
        "base_compaction_hold_delete_bitmap_lock_time_ms");
44
45
CloudBaseCompaction::CloudBaseCompaction(CloudStorageEngine& engine, CloudTabletSPtr tablet)
46
3.17k
        : CloudCompactionMixin(engine, tablet,
47
3.17k
                               "BaseCompaction:" + std::to_string(tablet->tablet_id())) {}
48
49
3.17k
CloudBaseCompaction::~CloudBaseCompaction() = default;
50
51
3.16k
Status CloudBaseCompaction::prepare_compact() {
52
3.16k
    Status st;
53
3.16k
    Defer defer_set_st([&] {
54
3.16k
        if (!st.ok()) {
55
3.11k
            cloud_tablet()->set_last_base_compaction_status(st.to_string());
56
3.11k
            cloud_tablet()->set_last_base_compaction_failure_time(UnixMillis());
57
3.11k
        }
58
3.16k
    });
59
3.16k
    if (_tablet->tablet_state() != TABLET_RUNNING) {
60
0
        st = Status::InternalError("invalid tablet state. tablet_id={}", _tablet->tablet_id());
61
0
        return st;
62
0
    }
63
64
3.16k
    bool need_sync_tablet = true;
65
3.16k
    {
66
3.16k
        std::shared_lock rlock(_tablet->get_header_lock());
67
        // If number of rowsets is equal to approximate_num_rowsets, it is very likely that this tablet has been
68
        // synchronized with meta-service.
69
3.16k
        if (_tablet->tablet_meta()->all_rs_metas().size() >=
70
3.16k
                    cloud_tablet()->fetch_add_approximate_num_rowsets(0) &&
71
3.16k
            cloud_tablet()->last_sync_time_s > 0) {
72
3.15k
            need_sync_tablet = false;
73
3.15k
        }
74
3.16k
    }
75
3.16k
    if (need_sync_tablet) {
76
17
        st = cloud_tablet()->sync_rowsets();
77
17
        RETURN_IF_ERROR(st);
78
17
    }
79
80
3.16k
    st = pick_rowsets_to_compact();
81
3.16k
    RETURN_IF_ERROR(st);
82
83
438
    for (auto& rs : _input_rowsets) {
84
438
        _input_row_num += rs->num_rows();
85
438
        _input_segments += rs->num_segments();
86
438
        _input_rowsets_data_size += rs->data_disk_size();
87
438
        _input_rowsets_index_size += rs->index_disk_size();
88
438
        _input_rowsets_total_size += rs->total_disk_size();
89
438
        _input_rowsets_cached_data_size += rs->approximate_cached_data_size();
90
438
        _input_rowsets_cached_index_size += rs->approximate_cache_index_size();
91
438
    }
92
49
    LOG_INFO("start CloudBaseCompaction, tablet_id={}, range=[{}-{}]", _tablet->tablet_id(),
93
49
             _input_rowsets.front()->start_version(), _input_rowsets.back()->end_version())
94
49
            .tag("job_id", _uuid)
95
49
            .tag("input_rowsets", _input_rowsets.size())
96
49
            .tag("input_rows", _input_row_num)
97
49
            .tag("input_segments", _input_segments)
98
49
            .tag("input_rowsets_data_size", _input_rowsets_data_size)
99
49
            .tag("input_rowsets_index_size", _input_rowsets_index_size)
100
49
            .tag("input_rowsets_total_size", _input_rowsets_total_size)
101
49
            .tag("input_rowsets_cached_data_size", _input_rowsets_cached_data_size)
102
49
            .tag("input_rowsets_cached_index_size", _input_rowsets_cached_index_size);
103
49
    base_input_cached_size << (_input_rowsets_cached_data_size + _input_rowsets_cached_index_size);
104
49
    base_input_size << _input_rowsets_total_size;
105
49
    return Status::OK();
106
3.16k
}
107
108
49
Status CloudBaseCompaction::request_global_lock() {
109
    // prepare compaction job
110
49
    cloud::TabletJobInfoPB job;
111
49
    auto idx = job.mutable_idx();
112
49
    idx->set_tablet_id(_tablet->tablet_id());
113
49
    idx->set_table_id(_tablet->table_id());
114
49
    idx->set_index_id(_tablet->index_id());
115
49
    idx->set_partition_id(_tablet->partition_id());
116
49
    auto compaction_job = job.add_compaction();
117
49
    compaction_job->set_id(_uuid);
118
49
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
119
49
                                  std::to_string(config::heartbeat_service_port));
120
49
    compaction_job->set_type(cloud::TabletCompactionJobPB::BASE);
121
49
    compaction_job->set_base_compaction_cnt(_base_compaction_cnt);
122
49
    compaction_job->set_cumulative_compaction_cnt(_cumulative_compaction_cnt);
123
49
    compaction_job->add_input_versions(_input_rowsets.front()->start_version());
124
49
    compaction_job->add_input_versions(_input_rowsets.back()->end_version());
125
49
    using namespace std::chrono;
126
49
    int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
127
49
    _expiration = now + config::compaction_timeout_seconds;
128
49
    compaction_job->set_expiration(_expiration);
129
49
    compaction_job->set_lease(now + config::lease_compaction_interval_seconds * 4);
130
49
    cloud::StartTabletJobResponse resp;
131
49
    auto st = _engine.meta_mgr().prepare_tablet_job(job, &resp);
132
49
    cloud_tablet()->set_last_base_compaction_status(st.to_string());
133
49
    if (resp.has_alter_version()) {
134
0
        (static_cast<CloudTablet*>(_tablet.get()))->set_alter_version(resp.alter_version());
135
0
    }
136
49
    if (!st.ok()) {
137
0
        cloud_tablet()->set_last_base_compaction_failure_time(UnixMillis());
138
0
        if (resp.status().code() == cloud::STALE_TABLET_CACHE) {
139
            // set last_sync_time to 0 to force sync tablet next time
140
0
            cloud_tablet()->last_sync_time_s = 0;
141
0
        } else if (resp.status().code() == cloud::TABLET_NOT_FOUND) {
142
            // tablet not found
143
0
            cloud_tablet()->clear_cache();
144
0
        } else if (resp.status().code() == cloud::JOB_CHECK_ALTER_VERSION) {
145
0
            auto* cloud_tablet = (static_cast<CloudTablet*>(_tablet.get()));
146
0
            std::stringstream ss;
147
0
            ss << "failed to prepare cumu compaction. Check compaction input versions "
148
0
                  "failed in schema change. The input version end must "
149
0
                  "less than or equal to alter_version."
150
0
                  "current alter version in BE is not correct."
151
0
                  "input_version_start="
152
0
               << compaction_job->input_versions(0)
153
0
               << " input_version_end=" << compaction_job->input_versions(1)
154
0
               << " current alter_version=" << cloud_tablet->alter_version()
155
0
               << " schema_change_alter_version=" << resp.alter_version();
156
0
            std::string msg = ss.str();
157
0
            LOG(WARNING) << msg;
158
0
            return Status::InternalError(msg);
159
0
        }
160
0
    }
161
49
    return st;
162
49
}
163
164
3.16k
void CloudBaseCompaction::_filter_input_rowset() {
165
    // if dup_key and no delete predicate
166
    // we skip big files to save resources
167
3.16k
    if (_tablet->keys_type() != KeysType::DUP_KEYS) {
168
403
        return;
169
403
    }
170
3.98k
    for (auto& rs : _input_rowsets) {
171
3.98k
        if (rs->rowset_meta()->has_delete_predicate()) {
172
1.72k
            return;
173
1.72k
        }
174
3.98k
    }
175
1.04k
    int64_t max_size = config::base_compaction_dup_key_max_file_size_mbytes * 1024 * 1024;
176
    // first find a proper rowset for start
177
1.04k
    auto rs_iter = _input_rowsets.begin();
178
1.04k
    while (rs_iter != _input_rowsets.end()) {
179
543
        if ((*rs_iter)->rowset_meta()->total_disk_size() >= max_size) {
180
0
            rs_iter = _input_rowsets.erase(rs_iter);
181
543
        } else {
182
543
            break;
183
543
        }
184
543
    }
185
1.04k
}
186
187
3.16k
Status CloudBaseCompaction::pick_rowsets_to_compact() {
188
3.16k
    _input_rowsets.clear();
189
3.16k
    {
190
3.16k
        std::shared_lock rlock(_tablet->get_header_lock());
191
3.16k
        _base_compaction_cnt = cloud_tablet()->base_compaction_cnt();
192
3.16k
        _cumulative_compaction_cnt = cloud_tablet()->cumulative_compaction_cnt();
193
3.16k
        _input_rowsets = cloud_tablet()->pick_candidate_rowsets_to_base_compaction_unlocked();
194
3.16k
    }
195
3.16k
    if (auto st = check_version_continuity(_input_rowsets); !st.ok()) {
196
0
        DCHECK(false) << st;
197
0
        return st;
198
0
    }
199
3.16k
    _filter_input_rowset();
200
3.16k
    if (_input_rowsets.size() <= 1) {
201
1.41k
        return Status::Error<BE_NO_SUITABLE_VERSION>(
202
1.41k
                "insufficent compaction input rowset, #rowsets={}", _input_rowsets.size());
203
1.41k
    }
204
205
1.75k
    if (_input_rowsets.size() == 2 && _input_rowsets[0]->end_version() == 1) {
206
        // the tablet is with rowset: [0-1], [2-y]
207
        // and [0-1] has no data. in this situation, no need to do base compaction.
208
0
        return Status::Error<BE_NO_SUITABLE_VERSION>("no suitable versions for compaction");
209
0
    }
210
211
1.75k
    int score = 0;
212
1.75k
    int rowset_cnt = 0;
213
1.75k
    int64_t max_compaction_score = _tablet->keys_type() == KeysType::UNIQUE_KEYS &&
214
1.75k
                                                   _tablet->enable_unique_key_merge_on_write()
215
1.75k
                                           ? config::mow_base_compaction_max_compaction_score
216
1.75k
                                           : config::base_compaction_max_compaction_score;
217
7.53k
    while (rowset_cnt < _input_rowsets.size()) {
218
5.78k
        score += _input_rowsets[rowset_cnt++]->rowset_meta()->get_compaction_score();
219
5.78k
        if (score > max_compaction_score) {
220
5
            break;
221
5
        }
222
5.78k
    }
223
1.75k
    _input_rowsets.resize(rowset_cnt);
224
225
    // 1. cumulative rowset must reach base_compaction_min_rowset_num threshold
226
1.75k
    if (_input_rowsets.size() > config::base_compaction_min_rowset_num) {
227
25
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
228
0
                    << ", num_cumulative_rowsets=" << _input_rowsets.size() - 1
229
0
                    << ", base_compaction_num_cumulative_rowsets="
230
0
                    << config::base_compaction_min_rowset_num;
231
25
        apply_txn_size_truncation_and_log("CloudBaseCompaction");
232
25
        return Status::OK();
233
25
    }
234
235
    // 2. the ratio between base rowset and all input cumulative rowsets reaches the threshold
236
    // `_input_rowsets` has been sorted by end version, so we consider `_input_rowsets[0]` is the base rowset.
237
1.73k
    int64_t base_size = _input_rowsets.front()->data_disk_size();
238
1.73k
    int64_t cumulative_total_size = 0;
239
5.42k
    for (auto it = _input_rowsets.begin() + 1; it != _input_rowsets.end(); ++it) {
240
3.68k
        cumulative_total_size += (*it)->data_disk_size();
241
3.68k
    }
242
243
1.73k
    double base_cumulative_delta_ratio = config::base_compaction_min_data_ratio;
244
1.73k
    if (base_size == 0) {
245
        // base_size == 0 means this may be a base version [0-1], which has no data.
246
        // set to 1 to void divide by zero
247
1.28k
        base_size = 1;
248
1.28k
    }
249
1.73k
    double cumulative_base_ratio = static_cast<double>(cumulative_total_size) / base_size;
250
251
1.73k
    if (cumulative_base_ratio > base_cumulative_delta_ratio) {
252
24
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
253
0
                    << ", cumulative_total_size=" << cumulative_total_size
254
0
                    << ", base_size=" << base_size
255
0
                    << ", cumulative_base_ratio=" << cumulative_base_ratio
256
0
                    << ", policy_ratio=" << base_cumulative_delta_ratio;
257
24
        apply_txn_size_truncation_and_log("CloudBaseCompaction");
258
24
        return Status::OK();
259
24
    }
260
261
    // 3. the interval since last base compaction reaches the threshold
262
1.70k
    int64_t base_creation_time = _input_rowsets[0]->creation_time();
263
1.70k
    int64_t interval_threshold = config::base_compaction_interval_seconds_since_last_operation;
264
1.70k
    int64_t interval_since_last_base_compaction = time(nullptr) - base_creation_time;
265
1.70k
    if (interval_since_last_base_compaction > interval_threshold) {
266
0
        VLOG_NOTICE << "satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
267
0
                    << ", interval_since_last_base_compaction="
268
0
                    << interval_since_last_base_compaction
269
0
                    << ", interval_threshold=" << interval_threshold;
270
0
        apply_txn_size_truncation_and_log("CloudBaseCompaction");
271
0
        return Status::OK();
272
0
    }
273
274
1.70k
    VLOG_NOTICE << "don't satisfy the base compaction policy. tablet=" << _tablet->tablet_id()
275
0
                << ", num_cumulative_rowsets=" << _input_rowsets.size() - 1
276
0
                << ", cumulative_base_ratio=" << cumulative_base_ratio
277
0
                << ", interval_since_last_base_compaction=" << interval_since_last_base_compaction;
278
1.70k
    return Status::Error<BE_NO_SUITABLE_VERSION>("no suitable versions for compaction");
279
1.70k
}
280
281
49
Status CloudBaseCompaction::execute_compact() {
282
49
#ifndef __APPLE__
283
49
    if (config::enable_base_compaction_idle_sched) {
284
49
        Thread::set_idle_sched();
285
49
    }
286
49
#endif
287
288
49
    SCOPED_ATTACH_TASK(_mem_tracker);
289
290
49
    using namespace std::chrono;
291
49
    auto start = steady_clock::now();
292
49
    Status st;
293
49
    Defer defer_set_st([&] {
294
49
        cloud_tablet()->set_last_base_compaction_status(st.to_string());
295
49
        if (!st.ok()) {
296
0
            cloud_tablet()->set_last_base_compaction_failure_time(UnixMillis());
297
49
        } else {
298
49
            cloud_tablet()->set_last_base_compaction_success_time(UnixMillis());
299
49
        }
300
49
    });
301
49
    st = CloudCompactionMixin::execute_compact();
302
49
    if (!st.ok()) {
303
0
        LOG(WARNING) << "fail to do " << compaction_name() << ". res=" << st
304
0
                     << ", tablet=" << _tablet->tablet_id()
305
0
                     << ", output_version=" << _output_version;
306
0
        return st;
307
0
    }
308
49
    LOG_INFO("finish CloudBaseCompaction, tablet_id={}, cost={}ms range=[{}-{}]",
309
49
             _tablet->tablet_id(), duration_cast<milliseconds>(steady_clock::now() - start).count(),
310
49
             _input_rowsets.front()->start_version(), _input_rowsets.back()->end_version())
311
49
            .tag("job_id", _uuid)
312
49
            .tag("input_rowsets", _input_rowsets.size())
313
49
            .tag("input_rows", _input_row_num)
314
49
            .tag("input_segments", _input_segments)
315
49
            .tag("input_rowsets_data_size", _input_rowsets_data_size)
316
49
            .tag("input_rowsets_index_size", _input_rowsets_index_size)
317
49
            .tag("input_rowsets_total", _input_rowsets_total_size)
318
49
            .tag("output_rows", _output_rowset->num_rows())
319
49
            .tag("output_segments", _output_rowset->num_segments())
320
49
            .tag("output_rowset_data_size", _output_rowset->data_disk_size())
321
49
            .tag("output_rowset_index_size", _output_rowset->index_disk_size())
322
49
            .tag("output_rowset_total_size", _output_rowset->total_disk_size())
323
49
            .tag("local_read_time_us", _stats.cloud_local_read_time)
324
49
            .tag("remote_read_time_us", _stats.cloud_remote_read_time)
325
49
            .tag("local_read_bytes", _local_read_bytes_total)
326
49
            .tag("remote_read_bytes", _remote_read_bytes_total);
327
328
    //_compaction_succeed = true;
329
49
    _state = CompactionState::SUCCESS;
330
331
49
    DorisMetrics::instance()->base_compaction_deltas_total->increment(_input_rowsets.size());
332
49
    DorisMetrics::instance()->base_compaction_bytes_total->increment(_input_rowsets_total_size);
333
49
    base_output_size << _output_rowset->total_disk_size();
334
335
49
    st = Status::OK();
336
49
    return st;
337
49
}
338
339
49
Status CloudBaseCompaction::modify_rowsets() {
340
    // commit compaction job
341
49
    cloud::TabletJobInfoPB job;
342
49
    auto idx = job.mutable_idx();
343
49
    idx->set_tablet_id(_tablet->tablet_id());
344
49
    idx->set_table_id(_tablet->table_id());
345
49
    idx->set_index_id(_tablet->index_id());
346
49
    idx->set_partition_id(_tablet->partition_id());
347
49
    auto compaction_job = job.add_compaction();
348
49
    compaction_job->set_id(_uuid);
349
49
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
350
49
                                  std::to_string(config::heartbeat_service_port));
351
49
    compaction_job->set_type(cloud::TabletCompactionJobPB::BASE);
352
49
    compaction_job->set_input_cumulative_point(cloud_tablet()->cumulative_layer_point());
353
49
    compaction_job->set_output_cumulative_point(cloud_tablet()->cumulative_layer_point());
354
49
    compaction_job->set_num_input_rows(_input_row_num);
355
49
    compaction_job->set_num_output_rows(_output_rowset->num_rows());
356
49
    compaction_job->set_size_input_rowsets(_input_rowsets_total_size);
357
49
    compaction_job->set_size_output_rowsets(_output_rowset->total_disk_size());
358
49
    compaction_job->set_num_input_segments(_input_segments);
359
49
    compaction_job->set_num_output_segments(_output_rowset->num_segments());
360
49
    compaction_job->set_num_input_rowsets(num_input_rowsets());
361
49
    compaction_job->set_num_output_rowsets(1);
362
49
    compaction_job->add_input_versions(_input_rowsets.front()->start_version());
363
49
    compaction_job->add_input_versions(_input_rowsets.back()->end_version());
364
49
    compaction_job->add_output_versions(_output_rowset->end_version());
365
49
    compaction_job->add_txn_id(_output_rowset->txn_id());
366
49
    compaction_job->add_output_rowset_ids(_output_rowset->rowset_id().to_string());
367
49
    compaction_job->set_index_size_input_rowsets(_input_rowsets_index_size);
368
49
    compaction_job->set_segment_size_input_rowsets(_input_rowsets_data_size);
369
49
    compaction_job->set_index_size_output_rowsets(_output_rowset->index_disk_size());
370
49
    compaction_job->set_segment_size_output_rowsets(_output_rowset->data_disk_size());
371
372
49
    DeleteBitmapPtr output_rowset_delete_bitmap = nullptr;
373
49
    int64_t get_delete_bitmap_lock_start_time = 0;
374
49
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
375
49
        _tablet->enable_unique_key_merge_on_write()) {
376
7
        int64_t initiator = this->initiator();
377
7
        RETURN_IF_ERROR(cloud_tablet()->calc_delete_bitmap_for_compaction(
378
7
                _input_rowsets, _output_rowset, *_rowid_conversion, compaction_type(),
379
7
                _stats.merged_rows, _stats.filtered_rows, initiator, output_rowset_delete_bitmap,
380
7
                _allow_delete_in_cumu_compaction, get_delete_bitmap_lock_start_time));
381
7
        LOG_INFO("update delete bitmap in CloudBaseCompaction, tablet_id={}, range=[{}-{}]",
382
7
                 _tablet->tablet_id(), _input_rowsets.front()->start_version(),
383
7
                 _input_rowsets.back()->end_version())
384
7
                .tag("job_id", _uuid)
385
7
                .tag("initiator", initiator)
386
7
                .tag("input_rowsets", _input_rowsets.size())
387
7
                .tag("input_rows", _input_row_num)
388
7
                .tag("input_segments", _input_segments)
389
7
                .tag("num_output_delete_bitmap", output_rowset_delete_bitmap->delete_bitmap.size());
390
7
        compaction_job->set_delete_bitmap_lock_initiator(initiator);
391
7
    }
392
393
49
    cloud::FinishTabletJobResponse resp;
394
49
    auto st = _engine.meta_mgr().commit_tablet_job(job, &resp);
395
49
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
396
49
        _tablet->enable_unique_key_merge_on_write()) {
397
7
        int64_t hold_delete_bitmap_lock_time_ms =
398
7
                (MonotonicMicros() - get_delete_bitmap_lock_start_time) / 1000;
399
7
        g_base_compaction_hold_delete_bitmap_lock_time_ms << hold_delete_bitmap_lock_time_ms;
400
7
    }
401
49
    if (!st.ok()) {
402
0
        if (resp.status().code() == cloud::TABLET_NOT_FOUND) {
403
0
            cloud_tablet()->clear_cache();
404
0
        } else if (resp.status().code() == cloud::JOB_CHECK_ALTER_VERSION) {
405
0
            auto* cloud_tablet = (static_cast<CloudTablet*>(_tablet.get()));
406
0
            std::stringstream ss;
407
0
            ss << "failed to prepare cumu compaction. Check compaction input versions "
408
0
                  "failed in schema change. The input version end must "
409
0
                  "less than or equal to alter_version."
410
0
                  "current alter version in BE is not correct."
411
0
                  "input_version_start="
412
0
               << compaction_job->input_versions(0)
413
0
               << " input_version_end=" << compaction_job->input_versions(1)
414
0
               << " current alter_version=" << cloud_tablet->alter_version()
415
0
               << " schema_change_alter_version=" << resp.alter_version();
416
0
            std::string msg = ss.str();
417
0
            LOG(WARNING) << msg;
418
0
            cloud_tablet->set_alter_version(resp.alter_version());
419
0
            return Status::InternalError(msg);
420
0
        }
421
0
        return st;
422
0
    }
423
49
    auto& stats = resp.stats();
424
49
    LOG(INFO) << "tablet stats=" << stats.ShortDebugString();
425
426
49
    {
427
49
        std::unique_lock wrlock(_tablet->get_header_lock());
428
        // clang-format off
429
49
        cloud_tablet()->set_last_base_compaction_success_time(std::max(cloud_tablet()->last_base_compaction_success_time(), stats.last_base_compaction_time_ms()));
430
49
        cloud_tablet()->set_last_cumu_compaction_success_time(std::max(cloud_tablet()->last_cumu_compaction_success_time(), stats.last_cumu_compaction_time_ms()));
431
49
        cloud_tablet()->set_last_full_compaction_success_time(std::max(cloud_tablet()->last_full_compaction_success_time(), stats.last_full_compaction_time_ms()));
432
        // clang-format on
433
49
        if (cloud_tablet()->base_compaction_cnt() >= stats.base_compaction_cnt()) {
434
            // This could happen while calling `sync_tablet_rowsets` during `commit_tablet_job`
435
0
            return Status::OK();
436
0
        }
437
        // Try to make output rowset visible immediately in tablet cache, instead of waiting for next synchronization from meta-service.
438
49
        cloud_tablet()->delete_rowsets(_input_rowsets, wrlock);
439
49
        cloud_tablet()->add_rowsets({_output_rowset}, false, wrlock);
440
        // ATTN: MUST NOT update `cumu_compaction_cnt` or `cumu_point` which are used when sync rowsets, otherwise may cause
441
        // the tablet to be unable to synchronize the rowset meta changes generated by cumu compaction.
442
49
        cloud_tablet()->set_base_compaction_cnt(stats.base_compaction_cnt());
443
49
        if (output_rowset_delete_bitmap) {
444
7
            _tablet->tablet_meta()->delete_bitmap().merge(*output_rowset_delete_bitmap);
445
7
        }
446
49
        if (stats.cumulative_compaction_cnt() >= cloud_tablet()->cumulative_compaction_cnt()) {
447
49
            cloud_tablet()->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
448
49
                                                    stats.num_rows(), stats.data_size());
449
49
        }
450
49
    }
451
0
    _tablet->prefill_dbm_agg_cache_after_compaction(_output_rowset);
452
49
    return Status::OK();
453
49
}
454
455
0
Status CloudBaseCompaction::garbage_collection() {
456
0
    RETURN_IF_ERROR(CloudCompactionMixin::garbage_collection());
457
0
    cloud::TabletJobInfoPB job;
458
0
    auto idx = job.mutable_idx();
459
0
    idx->set_tablet_id(_tablet->tablet_id());
460
0
    idx->set_table_id(_tablet->table_id());
461
0
    idx->set_index_id(_tablet->index_id());
462
0
    idx->set_partition_id(_tablet->partition_id());
463
0
    auto compaction_job = job.add_compaction();
464
0
    compaction_job->set_id(_uuid);
465
0
    compaction_job->set_initiator(BackendOptions::get_localhost() + ':' +
466
0
                                  std::to_string(config::heartbeat_service_port));
467
0
    compaction_job->set_type(cloud::TabletCompactionJobPB::BASE);
468
0
    if (_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
469
0
        _tablet->enable_unique_key_merge_on_write()) {
470
0
        compaction_job->set_delete_bitmap_lock_initiator(this->initiator());
471
0
    }
472
0
    auto st = _engine.meta_mgr().abort_tablet_job(job);
473
0
    if (!st.ok()) {
474
0
        LOG_WARNING("failed to abort compaction job")
475
0
                .tag("job_id", _uuid)
476
0
                .tag("tablet_id", _tablet->tablet_id())
477
0
                .error(st);
478
0
    }
479
0
    return st;
480
0
}
481
482
0
void CloudBaseCompaction::do_lease() {
483
0
    cloud::TabletJobInfoPB job;
484
0
    if (_state == CompactionState::SUCCESS) {
485
0
        return;
486
0
    }
487
0
    auto idx = job.mutable_idx();
488
0
    idx->set_tablet_id(_tablet->tablet_id());
489
0
    idx->set_table_id(_tablet->table_id());
490
0
    idx->set_index_id(_tablet->index_id());
491
0
    idx->set_partition_id(_tablet->partition_id());
492
0
    auto compaction_job = job.add_compaction();
493
0
    compaction_job->set_id(_uuid);
494
0
    using namespace std::chrono;
495
0
    int64_t lease_time = duration_cast<seconds>(system_clock::now().time_since_epoch()).count() +
496
0
                         config::lease_compaction_interval_seconds * 4;
497
0
    compaction_job->set_lease(lease_time);
498
0
    auto st = _engine.meta_mgr().lease_tablet_job(job);
499
0
    if (!st.ok()) {
500
0
        LOG_WARNING("failed to lease compaction job")
501
0
                .tag("job_id", _uuid)
502
0
                .tag("tablet_id", _tablet->tablet_id())
503
0
                .error(st);
504
0
    }
505
0
}
506
507
} // namespace doris