Coverage Report

Created: 2026-08-10 13:02

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