Coverage Report

Created: 2026-07-28 01:20

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