Coverage Report

Created: 2026-08-14 13:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_tablet_mgr.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_tablet_mgr.h"
19
20
#include <bthread/countdown_event.h>
21
22
#include <chrono>
23
24
#include "cloud/cloud_cluster_info.h"
25
#include "cloud/cloud_meta_mgr.h"
26
#include "cloud/cloud_storage_engine.h"
27
#include "cloud/cloud_tablet.h"
28
#include "cloud/config.h"
29
#include "common/status.h"
30
#include "cpp/sync_point.h"
31
#include "runtime/memory/cache_policy.h"
32
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
33
#include "util/debug_points.h"
34
#include "util/lru_cache.h"
35
#include "util/stack_util.h"
36
37
namespace doris {
38
uint64_t g_tablet_report_inactive_duration_ms = 0;
39
bvar::Adder<uint64_t> g_base_compaction_not_frozen_tablet_num(
40
        "base_compaction_not_frozen_tablet_num");
41
bvar::Adder<uint64_t> g_cumu_compaction_not_frozen_tablet_num(
42
        "cumu_compaction_not_frozen_tablet_num");
43
namespace {
44
45
// port from
46
// https://github.com/golang/groupcache/blob/master/singleflight/singleflight.go
47
template <typename Key, typename Val>
48
class SingleFlight {
49
public:
50
8
    SingleFlight() = default;
51
52
    SingleFlight(const SingleFlight&) = delete;
53
    void operator=(const SingleFlight&) = delete;
54
55
    using Loader = std::function<Val(const Key&)>;
56
57
    // Do executes and returns the results of the given function, making
58
    // sure that only one execution is in-flight for a given key at a
59
    // time. If a duplicate comes in, the duplicate caller waits for the
60
    // original to complete and receives the same results.
61
125k
    Val load(const Key& key, Loader loader) {
62
125k
        std::unique_lock lock(_call_map_mtx);
63
64
125k
        auto it = _call_map.find(key);
65
125k
        if (it != _call_map.end()) {
66
82
            auto call = it->second;
67
82
            lock.unlock();
68
82
            if (int ec = call->event.wait(); ec != 0) {
69
0
                throw std::system_error(std::error_code(ec, std::system_category()),
70
0
                                        "CountdownEvent wait failed");
71
0
            }
72
82
            return call->val;
73
82
        }
74
125k
        auto call = std::make_shared<Call>();
75
125k
        _call_map.emplace(key, call);
76
125k
        lock.unlock();
77
78
125k
        call->val = loader(key);
79
125k
        call->event.signal();
80
81
125k
        lock.lock();
82
125k
        _call_map.erase(key);
83
125k
        lock.unlock();
84
85
125k
        return call->val;
86
125k
    }
87
88
private:
89
    // `Call` is an in-flight or completed `load` call
90
    struct Call {
91
        bthread::CountdownEvent event;
92
        Val val;
93
    };
94
95
    std::mutex _call_map_mtx;
96
    std::unordered_map<Key, std::shared_ptr<Call>> _call_map;
97
};
98
99
// tablet_id -> load tablet function
100
SingleFlight<int64_t, Result<std::shared_ptr<CloudTablet>>> s_singleflight_load_tablet;
101
102
} // namespace
103
104
// tablet_id -> cached tablet
105
// This map owns all cached tablets. The lifetime of tablet can be longer than the LRU handle.
106
// It's also used for scenarios where users want to access the tablet by `tablet_id` without changing the LRU order.
107
// TODO(plat1ko): multi shard to increase concurrency
108
class CloudTabletMgr::TabletMap {
109
public:
110
124k
    void put(std::shared_ptr<CloudTablet> tablet) {
111
124k
        std::lock_guard lock(_mtx);
112
124k
        _map[tablet->tablet_id()] = std::move(tablet);
113
124k
    }
114
115
25.5k
    void erase(CloudTablet* tablet) {
116
25.5k
        std::lock_guard lock(_mtx);
117
25.5k
        auto it = _map.find(tablet->tablet_id());
118
        // According to the implementation of `LRUCache`, `deleter` may be called after a tablet
119
        // with same tablet id insert into cache and `TabletMap`. So we MUST check if the tablet
120
        // instance to be erased is the same one in the map.
121
25.8k
        if (it != _map.end() && it->second.get() == tablet) {
122
25.8k
            _map.erase(it);
123
25.8k
        }
124
25.5k
    }
125
126
24
    std::shared_ptr<CloudTablet> get(int64_t tablet_id) {
127
24
        std::lock_guard lock(_mtx);
128
24
        if (auto it = _map.find(tablet_id); it != _map.end()) {
129
2
            return it->second;
130
2
        }
131
22
        return nullptr;
132
24
    }
133
134
16.0k
    size_t size() { return _map.size(); }
135
136
16.0k
    void traverse(std::function<void(const std::shared_ptr<CloudTablet>&)> visitor) {
137
16.0k
        std::lock_guard lock(_mtx);
138
510M
        for (auto& [_, tablet] : _map) {
139
510M
            visitor(tablet);
140
510M
        }
141
16.0k
    }
142
143
private:
144
    std::mutex _mtx;
145
    std::unordered_map<int64_t, std::shared_ptr<CloudTablet>> _map;
146
};
147
148
// TODO(plat1ko): Prune cache
149
CloudTabletMgr::CloudTabletMgr(CloudStorageEngine& engine)
150
252
        : _engine(engine),
151
252
          _tablet_map(std::make_unique<TabletMap>()),
152
252
          _cache(std::make_unique<LRUCachePolicy>(
153
252
                  CachePolicy::CacheType::CLOUD_TABLET_CACHE, config::tablet_cache_capacity,
154
252
                  LRUCacheType::NUMBER, /*sweep time*/ 0, config::tablet_cache_shards,
155
252
                  /*element_count_capacity*/ 0, /*enable_prune*/ false,
156
252
                  /*is_lru_k*/ false)) {}
157
158
251
CloudTabletMgr::~CloudTabletMgr() = default;
159
160
3.11M
void set_tablet_access_time_ms(CloudTablet* tablet) {
161
3.11M
    using namespace std::chrono;
162
3.11M
    int64_t now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
163
3.11M
    tablet->last_access_time_ms = now;
164
3.11M
}
165
166
Result<std::shared_ptr<CloudTablet>> CloudTabletMgr::get_tablet(int64_t tablet_id, bool warmup_data,
167
                                                                bool sync_delete_bitmap,
168
                                                                SyncRowsetStats* sync_stats,
169
                                                                bool force_use_only_cached,
170
1.54M
                                                                bool cache_on_miss) {
171
1.54M
    DBUG_EXECUTE_IF("CloudTabletMgr::get_tablet.block", DBUG_BLOCK);
172
    // LRU value type. `Value`'s lifetime MUST NOT be longer than `CloudTabletMgr`
173
1.54M
    class Value : public LRUCacheValueBase {
174
1.54M
    public:
175
1.54M
        Value(const std::shared_ptr<CloudTablet>& tablet, TabletMap& tablet_map)
176
1.54M
                : tablet(tablet), tablet_map(tablet_map) {}
177
1.54M
        ~Value() override { tablet_map.erase(tablet.get()); }
178
179
        // FIXME(plat1ko): The ownership of tablet seems to belong to 'TabletMap', while `Value`
180
        // only requires a reference.
181
1.54M
        std::shared_ptr<CloudTablet> tablet;
182
1.54M
        TabletMap& tablet_map;
183
1.54M
    };
184
185
18.4E
    VLOG_DEBUG << "get_tablet tablet_id=" << tablet_id << " stack: " << get_stack_trace();
186
187
1.54M
    auto tablet_id_str = std::to_string(tablet_id);
188
1.54M
    CacheKey key(tablet_id_str);
189
1.54M
    auto* handle = _cache->lookup(key);
190
191
1.54M
    if (handle == nullptr) {
192
#ifdef BE_TEST
193
        if (auto tablet = _tablet_map->get(tablet_id); tablet != nullptr) {
194
            set_tablet_access_time_ms(tablet.get());
195
            return tablet;
196
        }
197
#endif
198
125k
        if (force_use_only_cached) {
199
2
            LOG(INFO) << "tablet=" << tablet_id
200
2
                      << "does not exists in local tablet cache, because param "
201
2
                         "force_use_only_cached=true, "
202
2
                         "treat it as an error";
203
2
            return ResultError(Status::InternalError(
204
2
                    "tablet={} does not exists in local tablet cache, because param "
205
2
                    "force_use_only_cached=true, "
206
2
                    "treat it as an error",
207
2
                    tablet_id));
208
2
        }
209
125k
        TEST_SYNC_POINT("CloudTabletMgr::get_tablet.not_found_in_cache");
210
125k
        if (sync_stats) {
211
15.5k
            ++sync_stats->tablet_meta_cache_miss;
212
15.5k
        }
213
        // Insert into cache and tablet_map inside SingleFlight lambda to ensure
214
        // only the leader caller does this. Moving these outside the lambda causes
215
        // a race condition: when multiple concurrent callers share the same CloudTablet*
216
        // from SingleFlight, each creates a competing LRU cache entry. Delayed Value
217
        // destructors then erase the tablet_map entry (the raw pointer safety check
218
        // passes since all callers share the same pointer), and the tablet permanently
219
        // disappears from tablet_map. Subsequent get_tablet() calls hit the LRU cache
220
        // directly (cache hit path) which never re-inserts into tablet_map, making the
221
        // tablet invisible to the compaction scheduler.
222
125k
        auto load_tablet = [this, &key, warmup_data, sync_delete_bitmap, sync_stats, cache_on_miss](
223
125k
                                   int64_t tablet_id) -> Result<std::shared_ptr<CloudTablet>> {
224
125k
            TabletMetaSharedPtr tablet_meta;
225
125k
            auto start = std::chrono::steady_clock::now();
226
125k
            auto st = _engine.meta_mgr().get_tablet_meta(tablet_id, &tablet_meta);
227
125k
            auto end = std::chrono::steady_clock::now();
228
125k
            if (sync_stats) {
229
15.4k
                sync_stats->get_remote_tablet_meta_rpc_ns +=
230
15.4k
                        std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
231
15.4k
            }
232
125k
            if (!st.ok()) {
233
110
                LOG(WARNING) << "failed to tablet " << tablet_id << ": " << st;
234
110
                return ResultError(st);
235
110
            }
236
237
125k
            auto tablet = std::make_shared<CloudTablet>(_engine, std::move(tablet_meta));
238
            // MUST sync stats to let compaction scheduler work correctly
239
125k
            SyncOptions options;
240
125k
            options.warmup_delta_data = warmup_data;
241
125k
            options.sync_delete_bitmap = sync_delete_bitmap;
242
125k
            st = _engine.meta_mgr().sync_tablet_rowsets(tablet.get(), options, sync_stats);
243
125k
            if (!st.ok()) {
244
0
                LOG(WARNING) << "failed to sync tablet " << tablet_id << ": " << st;
245
0
                return ResultError(st);
246
0
            }
247
248
125k
            if (!cache_on_miss) {
249
0
                set_tablet_access_time_ms(tablet.get());
250
0
                return tablet;
251
0
            }
252
253
125k
            auto value = std::make_unique<Value>(tablet, *_tablet_map);
254
125k
            auto* insert_handle = _cache->insert(key, value.release(), 1, sizeof(CloudTablet),
255
125k
                                                 CachePriority::NORMAL);
256
125k
            auto ret = std::shared_ptr<CloudTablet>(tablet.get(),
257
125k
                                                    [this, insert_handle](CloudTablet* tablet_ptr) {
258
125k
                                                        set_tablet_access_time_ms(tablet_ptr);
259
125k
                                                        _cache->release(insert_handle);
260
125k
                                                    });
261
125k
            _tablet_map->put(std::move(tablet));
262
125k
            return ret;
263
125k
        };
264
265
125k
        auto load_result = s_singleflight_load_tablet.load(tablet_id, std::move(load_tablet));
266
125k
        if (!load_result.has_value()) {
267
100
            return ResultError(Status::InternalError("failed to get tablet {}, msg={}", tablet_id,
268
100
                                                     load_result.error()));
269
100
        }
270
125k
        auto tablet = load_result.value();
271
125k
        set_tablet_access_time_ms(tablet.get());
272
125k
        return tablet;
273
125k
    }
274
1.42M
    if (sync_stats) {
275
1.01M
        ++sync_stats->tablet_meta_cache_hit;
276
1.01M
    }
277
1.42M
    CloudTablet* tablet_raw_ptr = reinterpret_cast<Value*>(_cache->value(handle))->tablet.get();
278
1.42M
    set_tablet_access_time_ms(tablet_raw_ptr);
279
1.43M
    auto tablet = std::shared_ptr<CloudTablet>(tablet_raw_ptr, [this, handle](CloudTablet* tablet) {
280
1.43M
        set_tablet_access_time_ms(tablet);
281
1.43M
        _cache->release(handle);
282
1.43M
    });
283
1.42M
    return tablet;
284
1.54M
}
285
286
0
bool CloudTabletMgr::peek_tablet_meta(int64_t tablet_id, TabletMetaSharedPtr* tablet_meta) {
287
0
    if (tablet_meta == nullptr) {
288
0
        return false;
289
0
    }
290
0
    auto tablet = _tablet_map->get(tablet_id);
291
0
    if (!tablet) {
292
0
        return false;
293
0
    }
294
0
    *tablet_meta = tablet->tablet_meta();
295
0
    return true;
296
0
}
297
298
198
void CloudTabletMgr::erase_tablet(int64_t tablet_id) {
299
198
    auto tablet_id_str = std::to_string(tablet_id);
300
198
    CacheKey key(tablet_id_str.data(), tablet_id_str.size());
301
198
    _cache->erase(key);
302
198
}
303
304
10
void CloudTabletMgr::vacuum_stale_rowsets(const CountDownLatch& stop_latch) {
305
10
    LOG_INFO("begin to vacuum stale rowsets");
306
10
    std::vector<std::shared_ptr<CloudTablet>> tablets_to_vacuum;
307
10
    tablets_to_vacuum.reserve(_tablet_map->size());
308
522k
    _tablet_map->traverse([&tablets_to_vacuum](auto&& t) {
309
522k
        if (t->has_stale_rowsets()) {
310
9.53k
            tablets_to_vacuum.push_back(t);
311
9.53k
        }
312
522k
    });
313
10
    int num_vacuumed = 0;
314
9.53k
    for (auto& t : tablets_to_vacuum) {
315
9.53k
        if (stop_latch.count() <= 0) {
316
0
            break;
317
0
        }
318
319
9.53k
        num_vacuumed += t->delete_expired_stale_rowsets();
320
9.53k
    }
321
10
    LOG_INFO("finish vacuum stale rowsets")
322
10
            .tag("num_vacuumed", num_vacuumed)
323
10
            .tag("num_tablets", tablets_to_vacuum.size());
324
325
10
    {
326
10
        LOG_INFO("begin to remove unused rowsets");
327
10
        std::vector<std::shared_ptr<CloudTablet>> tablets_to_remove_unused_rowsets;
328
10
        tablets_to_remove_unused_rowsets.reserve(_tablet_map->size());
329
522k
        _tablet_map->traverse([&tablets_to_remove_unused_rowsets](auto&& t) {
330
522k
            if (t->need_remove_unused_rowsets()) {
331
4.88k
                tablets_to_remove_unused_rowsets.push_back(t);
332
4.88k
            }
333
522k
        });
334
4.88k
        for (auto& t : tablets_to_remove_unused_rowsets) {
335
4.88k
            t->remove_unused_rowsets();
336
4.88k
        }
337
10
        LOG_INFO("finish remove unused rowsets")
338
10
                .tag("num_tablets", tablets_to_remove_unused_rowsets.size());
339
10
        if (config::enable_check_agg_and_remove_pre_rowsets_delete_bitmap) {
340
0
            int64_t max_useless_rowset_count = 0;
341
0
            int64_t tablet_id_with_max_useless_rowset_count = 0;
342
0
            int64_t max_useless_rowset_version_count = 0;
343
0
            int64_t tablet_id_with_max_useless_rowset_version_count = 0;
344
0
            OlapStopWatch watch;
345
0
            _tablet_map->traverse([&](auto&& tablet) {
346
0
                int64_t useless_rowset_count = 0;
347
0
                int64_t useless_rowset_version_count = 0;
348
0
                tablet->check_agg_delete_bitmap_for_stale_rowsets(useless_rowset_count,
349
0
                                                                  useless_rowset_version_count);
350
0
                if (useless_rowset_count > max_useless_rowset_count) {
351
0
                    max_useless_rowset_count = useless_rowset_count;
352
0
                    tablet_id_with_max_useless_rowset_count = tablet->tablet_id();
353
0
                }
354
0
                if (useless_rowset_version_count > max_useless_rowset_version_count) {
355
0
                    max_useless_rowset_version_count = useless_rowset_version_count;
356
0
                    tablet_id_with_max_useless_rowset_version_count = tablet->tablet_id();
357
0
                }
358
0
            });
359
0
            g_max_rowsets_with_useless_delete_bitmap.set_value(max_useless_rowset_count);
360
0
            g_max_rowsets_with_useless_delete_bitmap_version.set_value(
361
0
                    max_useless_rowset_version_count);
362
0
            LOG(INFO) << "finish check_agg_delete_bitmap_for_stale_rowsets, cost(us)="
363
0
                      << watch.get_elapse_time_us()
364
0
                      << ". max useless rowset count=" << max_useless_rowset_count
365
0
                      << ", tablet_id=" << tablet_id_with_max_useless_rowset_count
366
0
                      << ", max useless rowset version count=" << max_useless_rowset_version_count
367
0
                      << ", tablet_id=" << tablet_id_with_max_useless_rowset_version_count;
368
0
        }
369
10
    }
370
10
    {
371
10
        _tablet_map->traverse(
372
522k
                [](auto&& tablet) { tablet->clear_unused_visible_pending_rowsets(); });
373
10
    }
374
10
}
375
376
15.9k
std::vector<std::weak_ptr<CloudTablet>> CloudTabletMgr::get_weak_tablets() {
377
15.9k
    std::vector<std::weak_ptr<CloudTablet>> weak_tablets;
378
15.9k
    weak_tablets.reserve(_tablet_map->size());
379
508M
    _tablet_map->traverse([&weak_tablets](auto& t) { weak_tablets.push_back(t); });
380
15.9k
    return weak_tablets;
381
15.9k
}
382
383
5
void CloudTabletMgr::sync_tablets(const CountDownLatch& stop_latch) {
384
5
    LOG_INFO("begin to sync tablets");
385
5
    int64_t last_sync_time_bound = ::time(nullptr) - config::tablet_sync_interval_s;
386
387
5
    auto weak_tablets = get_weak_tablets();
388
389
    // sort by last_sync_time
390
114k
    static auto cmp = [](const auto& a, const auto& b) { return a.first < b.first; };
391
5
    std::multiset<std::pair<int64_t, std::weak_ptr<CloudTablet>>, decltype(cmp)>
392
5
            sync_time_tablet_set(cmp);
393
394
285k
    for (auto& weak_tablet : weak_tablets) {
395
285k
        if (auto tablet = weak_tablet.lock()) {
396
285k
            int64_t last_sync_time = tablet->last_sync_time_s;
397
285k
            if (last_sync_time <= last_sync_time_bound) {
398
7.15k
                sync_time_tablet_set.emplace(last_sync_time, weak_tablet);
399
7.15k
            }
400
285k
        }
401
285k
    }
402
403
5
    int num_sync = 0;
404
7.15k
    for (auto&& [_, weak_tablet] : sync_time_tablet_set) {
405
7.15k
        if (stop_latch.count() <= 0) {
406
0
            break;
407
0
        }
408
409
7.15k
        if (auto tablet = weak_tablet.lock()) {
410
5.87k
            if (tablet->last_sync_time_s > last_sync_time_bound) {
411
0
                continue;
412
0
            }
413
414
5.87k
            ++num_sync;
415
5.87k
            auto st = tablet->sync_meta();
416
5.87k
            if (!st) {
417
0
                LOG_WARNING("failed to sync tablet meta {}", tablet->tablet_id()).error(st);
418
0
                if (st.is<ErrorCode::NOT_FOUND>()) {
419
0
                    continue;
420
0
                }
421
0
            }
422
5.87k
            SyncOptions options;
423
5.87k
            options.query_version = -1;
424
5.87k
            options.merge_schema = true;
425
5.87k
            st = tablet->sync_rowsets(options);
426
5.87k
            if (!st) {
427
0
                LOG_WARNING("failed to sync tablet rowsets {}", tablet->tablet_id()).error(st);
428
0
            }
429
5.87k
        }
430
7.15k
    }
431
5
    LOG_INFO("finish sync tablets").tag("num_sync", num_sync);
432
5
}
433
434
Status CloudTabletMgr::get_topn_tablets_to_compact(
435
        int n, CompactionType compaction_type, const std::function<bool(CloudTablet*)>& filter_out,
436
15.8k
        std::vector<std::shared_ptr<CloudTablet>>* tablets, CompactionScoreStats* score_stats) {
437
15.8k
    DCHECK(compaction_type == CompactionType::BASE_COMPACTION ||
438
15.8k
           compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
439
15.8k
           compaction_type == CompactionType::CUMU_BINLOG_COMPACTION);
440
15.8k
    *score_stats = {};
441
15.8k
    score_stats->scanned = true;
442
15.8k
    int64_t max_score_tablet_id = 0;
443
    // clang-format off
444
504M
    auto score = [compaction_type](CloudTablet* t) {
445
504M
        if (compaction_type == CompactionType::CUMU_BINLOG_COMPACTION && !t->is_row_binlog_tablet()) {
446
2
            return int64_t {0};
447
2
        }
448
504M
        if (compaction_type != CompactionType::CUMU_BINLOG_COMPACTION && t->is_row_binlog_tablet()) {
449
0
            return int64_t {0};
450
0
        }
451
504M
        return compaction_type == CompactionType::BASE_COMPACTION ? t->get_cloud_base_compaction_score()
452
504M
               : (compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
453
453M
                  compaction_type == CompactionType::CUMU_BINLOG_COMPACTION) ? t->get_cloud_cumu_compaction_score()
454
453M
               : 0;
455
504M
    };
456
457
15.8k
    using namespace std::chrono;
458
15.8k
    auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
459
420M
    auto skip = [now, compaction_type](CloudTablet* t) {
460
420M
        auto* cloud_cluster_info = static_cast<CloudClusterInfo*>(ExecEnv::GetInstance()->cluster_info());
461
462
420M
        if (config::enable_standby_passive_compaction && cloud_cluster_info->is_in_standby()) {
463
0
            if (t->fetch_add_approximate_num_rowsets(0) < config::max_tablet_version_num * config::standby_compaction_version_ratio) {
464
0
                return true;
465
0
            }
466
0
        }
467
468
        // Compaction read-write separation: skip tablets that should be compacted by other clusters.
469
        // Placed after standby check so standby invariants (version count threshold) are preserved.
470
420M
        if (cloud_cluster_info->should_skip_compaction(t)) {
471
0
            return true;
472
0
        }
473
474
420M
        int32_t max_version_config = t->max_version_config();
475
420M
        if (compaction_type == CompactionType::BASE_COMPACTION) {
476
50.1M
            bool is_recent_failure = now - t->last_base_compaction_failure_time() < config::min_compaction_failure_interval_ms;
477
50.1M
            bool is_frozen = (now - t->last_load_time_ms > config::compaction_load_max_freeze_interval_s * 1000
478
50.1M
                   && now - t->last_base_compaction_success_time_ms < config::base_compaction_freeze_interval_s * 1000
479
50.1M
                   && t->fetch_add_approximate_num_rowsets(0) < max_version_config / 2);
480
50.1M
            g_base_compaction_not_frozen_tablet_num << !is_frozen;
481
50.1M
            return is_recent_failure || is_frozen;
482
50.1M
        }
483
484
        // If tablet has too many rowsets but not be compacted for a long time, compaction should be performed
485
        // regardless of whether there is a load job recently.
486
370M
        bool is_recent_failure = now - t->last_cumu_compaction_failure_time() < config::min_compaction_failure_interval_ms;
487
370M
        bool is_recent_no_suitable_version = now - t->last_cumu_no_suitable_version_ms < config::min_compaction_failure_interval_ms;
488
370M
        bool is_frozen = (now - t->last_load_time_ms > config::compaction_load_max_freeze_interval_s * 1000
489
370M
               && now - t->last_cumu_compaction_success_time_ms < config::cumu_compaction_interval_s * 1000
490
370M
               && t->fetch_add_approximate_num_rowsets(0) < max_version_config / 2);
491
370M
        g_cumu_compaction_not_frozen_tablet_num << !is_frozen;
492
370M
        return is_recent_failure || is_recent_no_suitable_version || is_frozen;
493
420M
    };
494
    // We don't schedule tablets that are disabled for compaction
495
427M
    auto disable = [](CloudTablet* t) { return t->tablet_meta()->tablet_schema()->disable_auto_compaction(); };
496
497
15.8k
    auto [num_filtered, num_disabled, num_skipped] = std::make_tuple(0, 0, 0);
498
499
15.8k
    auto weak_tablets = get_weak_tablets();
500
15.8k
    std::vector<std::pair<std::shared_ptr<CloudTablet>, int64_t>> buf;
501
15.8k
    buf.reserve(n + 1);
502
504M
    for (auto& weak_tablet : weak_tablets) {
503
504M
        auto t = weak_tablet.lock();
504
504M
        if (t == nullptr) { continue; }
505
506
504M
        int64_t s = score(t.get());
507
504M
        if (s <= 0) { continue; }
508
427M
        if (s > score_stats->max_score) {
509
87.9k
            max_score_tablet_id = t->tablet_id();
510
87.9k
            score_stats->max_score = s;
511
87.9k
        }
512
427M
        if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
513
376M
            int64_t* policy_max_score =
514
376M
                    t->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY
515
376M
                            ? &score_stats->time_series_max_score
516
376M
                            : &score_stats->size_based_max_score;
517
376M
            if (s > *policy_max_score) {
518
95.5k
                *policy_max_score = s;
519
95.5k
            }
520
376M
        }
521
522
427M
        if (filter_out(t.get())) { ++num_filtered; continue; }
523
427M
        if (disable(t.get())) { ++num_disabled; continue; }
524
420M
        if (skip(t.get())) { ++num_skipped; continue; }
525
526
416M
        buf.emplace_back(std::move(t), s);
527
5.04G
        std::sort(buf.begin(), buf.end(), [](auto& a, auto& b) { return a.second > b.second; });
528
416M
        if (buf.size() > n) { buf.pop_back(); }
529
416M
    }
530
531
15.8k
    LOG_EVERY_N(INFO, 1000) << "get_topn_compaction_score, n=" << n << " type=" << compaction_type
532
17
               << " num_tablets=" << weak_tablets.size() << " num_skipped=" << num_skipped
533
17
               << " num_disabled=" << num_disabled << " num_filtered=" << num_filtered
534
17
               << " max_score=" << score_stats->max_score << " max_score_tablet=" << max_score_tablet_id
535
99
               << " tablets=[" << [&buf] { std::stringstream ss; for (auto& i : buf) ss << i.first->tablet_id() << ":" << i.second << ","; return ss.str(); }() << "]"
536
15.8k
               ;
537
    // clang-format on
538
539
15.8k
    tablets->clear();
540
15.8k
    tablets->reserve(n + 1);
541
93.7k
    for (auto& [t, _] : buf) {
542
93.7k
        tablets->emplace_back(std::move(t));
543
93.7k
    }
544
545
15.8k
    return Status::OK();
546
15.8k
}
547
548
void CloudTabletMgr::build_all_report_tablets_info(std::map<TTabletId, TTablet>* tablets_info,
549
62
                                                   uint64_t* tablet_num) {
550
62
    DCHECK(tablets_info != nullptr);
551
62
    VLOG_NOTICE << "begin to build all report cloud tablets info";
552
553
62
    HistogramStat tablet_version_num_hist;
554
555
3.18M
    auto handler = [&](const std::weak_ptr<CloudTablet>& tablet_wk) {
556
3.18M
        auto tablet = tablet_wk.lock();
557
3.18M
        if (!tablet) return;
558
3.18M
        (*tablet_num)++;
559
3.18M
        TTabletInfo tablet_info;
560
3.18M
        tablet->build_tablet_report_info(&tablet_info);
561
3.18M
        using namespace std::chrono;
562
3.18M
        int64_t now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
563
3.18M
        if (now - g_tablet_report_inactive_duration_ms < tablet->last_access_time_ms) {
564
            // the tablet is still being accessed and used in recently, so not report it
565
3.18M
            return;
566
3.18M
        }
567
0
        auto& t_tablet = (*tablets_info)[tablet->tablet_id()];
568
        // On the cloud, a specific BE has only one tablet replica;
569
        // there are no multiple replicas for a specific BE.
570
        // This is only to reuse the non-cloud report protocol.
571
0
        tablet_version_num_hist.add(tablet_info.total_version_count);
572
0
        t_tablet.tablet_infos.emplace_back(std::move(tablet_info));
573
0
    };
574
575
62
    auto weak_tablets = get_weak_tablets();
576
62
    std::for_each(weak_tablets.begin(), weak_tablets.end(), handler);
577
578
62
    DorisMetrics::instance()->tablet_version_num_distribution->set_histogram(
579
62
            tablet_version_num_hist);
580
62
    LOG(INFO) << "success to build all cloud report tablets info. all_tablet_count=" << *tablet_num
581
62
              << " exceed drop time limit count=" << tablets_info->size();
582
62
}
583
584
0
void CloudTabletMgr::get_tablet_info(int64_t num_tablets, std::vector<TabletInfo>* tablets_info) {
585
0
    auto weak_tablets = get_weak_tablets();
586
0
    for (auto& weak_tablet : weak_tablets) {
587
0
        auto tablet = weak_tablet.lock();
588
0
        if (tablet == nullptr) {
589
0
            continue;
590
0
        }
591
0
        if (tablets_info->size() >= num_tablets) {
592
0
            return;
593
0
        }
594
0
        tablets_info->push_back(tablet->get_tablet_info());
595
0
    }
596
0
}
597
598
void CloudTabletMgr::get_topn_tablet_delete_bitmap_score(
599
10
        uint64_t* max_delete_bitmap_score, uint64_t* max_base_rowset_delete_bitmap_score) {
600
10
    int64_t max_delete_bitmap_score_tablet_id = 0;
601
10
    OlapStopWatch watch;
602
10
    uint64_t total_delete_map_count = 0;
603
10
    int64_t max_base_rowset_delete_bitmap_score_tablet_id = 0;
604
10
    int n = config::check_tablet_delete_bitmap_score_top_n;
605
10
    std::vector<std::pair<std::shared_ptr<CloudTablet>, int64_t>> buf;
606
10
    buf.reserve(n + 1);
607
521k
    auto handler = [&](const std::weak_ptr<CloudTablet>& tablet_wk) {
608
521k
        auto t = tablet_wk.lock();
609
521k
        if (!t || !t->enable_unique_key_merge_on_write()) return;
610
121k
        uint64_t delete_bitmap_count =
611
121k
                t.get()->tablet_meta()->delete_bitmap().get_delete_bitmap_count();
612
121k
        total_delete_map_count += delete_bitmap_count;
613
121k
        if (delete_bitmap_count > *max_delete_bitmap_score) {
614
61
            max_delete_bitmap_score_tablet_id = t->tablet_id();
615
61
            *max_delete_bitmap_score = delete_bitmap_count;
616
61
        }
617
121k
        buf.emplace_back(std::move(t), delete_bitmap_count);
618
2.43M
        std::sort(buf.begin(), buf.end(), [](auto& a, auto& b) { return a.second > b.second; });
619
121k
        if (buf.size() > n) {
620
121k
            buf.pop_back();
621
121k
        }
622
121k
    };
623
10
    auto weak_tablets = get_weak_tablets();
624
10
    std::for_each(weak_tablets.begin(), weak_tablets.end(), handler);
625
100
    for (auto& [t, _] : buf) {
626
100
        t->get_base_rowset_delete_bitmap_count(max_base_rowset_delete_bitmap_score,
627
100
                                               &max_base_rowset_delete_bitmap_score_tablet_id);
628
100
    }
629
10
    std::stringstream ss;
630
100
    for (auto& i : buf) {
631
100
        ss << i.first->tablet_id() << ": " << i.second << ", ";
632
100
    }
633
10
    LOG(INFO) << "get_topn_tablet_delete_bitmap_score, n=" << n
634
10
              << ", tablet size=" << weak_tablets.size()
635
10
              << ", total_delete_map_count=" << total_delete_map_count
636
10
              << ", cost(us)=" << watch.get_elapse_time_us()
637
10
              << ", max_delete_bitmap_score=" << *max_delete_bitmap_score
638
10
              << ", max_delete_bitmap_score_tablet_id=" << max_delete_bitmap_score_tablet_id
639
10
              << ", max_base_rowset_delete_bitmap_score=" << *max_base_rowset_delete_bitmap_score
640
10
              << ", max_base_rowset_delete_bitmap_score_tablet_id="
641
10
              << max_base_rowset_delete_bitmap_score_tablet_id << ", tablets=[" << ss.str() << "]";
642
10
}
643
644
6
std::vector<std::shared_ptr<CloudTablet>> CloudTabletMgr::get_all_tablet() {
645
6
    std::vector<std::shared_ptr<CloudTablet>> tablets;
646
6
    tablets.reserve(_tablet_map->size());
647
257k
    _tablet_map->traverse([&tablets](auto& t) { tablets.push_back(t); });
648
6
    return tablets;
649
6
}
650
651
14
void CloudTabletMgr::put_tablet_for_UT(std::shared_ptr<CloudTablet> tablet) {
652
14
    _tablet_map->put(tablet);
653
14
}
654
655
} // namespace doris