Coverage Report

Created: 2026-03-25 17:32

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