Coverage Report

Created: 2026-08-13 16:52

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
117k
    Val load(const Key& key, Loader loader) {
62
117k
        std::unique_lock lock(_call_map_mtx);
63
64
117k
        auto it = _call_map.find(key);
65
117k
        if (it != _call_map.end()) {
66
60
            auto call = it->second;
67
60
            lock.unlock();
68
60
            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
60
            return call->val;
73
60
        }
74
116k
        auto call = std::make_shared<Call>();
75
116k
        _call_map.emplace(key, call);
76
116k
        lock.unlock();
77
78
116k
        call->val = loader(key);
79
116k
        call->event.signal();
80
81
116k
        lock.lock();
82
116k
        _call_map.erase(key);
83
116k
        lock.unlock();
84
85
116k
        return call->val;
86
117k
    }
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
115k
    void put(std::shared_ptr<CloudTablet> tablet) {
111
115k
        std::lock_guard lock(_mtx);
112
115k
        _map[tablet->tablet_id()] = std::move(tablet);
113
115k
    }
114
115
16.9k
    void erase(CloudTablet* tablet) {
116
16.9k
        std::lock_guard lock(_mtx);
117
16.9k
        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
17.1k
        if (it != _map.end() && it->second.get() == tablet) {
122
17.1k
            _map.erase(it);
123
17.1k
        }
124
16.9k
    }
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
14.9k
    size_t size() { return _map.size(); }
135
136
14.9k
    void traverse(std::function<void(const std::shared_ptr<CloudTablet>&)> visitor) {
137
14.9k
        std::lock_guard lock(_mtx);
138
479M
        for (auto& [_, tablet] : _map) {
139
479M
            visitor(tablet);
140
479M
        }
141
14.9k
    }
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.07M
void set_tablet_access_time_ms(CloudTablet* tablet) {
161
3.07M
    using namespace std::chrono;
162
3.07M
    int64_t now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
163
3.07M
    tablet->last_access_time_ms = now;
164
3.07M
}
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.52M
                                                                bool cache_on_miss) {
171
1.52M
    DBUG_EXECUTE_IF("CloudTabletMgr::get_tablet.block", DBUG_BLOCK);
172
    // LRU value type. `Value`'s lifetime MUST NOT be longer than `CloudTabletMgr`
173
1.52M
    class Value : public LRUCacheValueBase {
174
1.52M
    public:
175
1.52M
        Value(const std::shared_ptr<CloudTablet>& tablet, TabletMap& tablet_map)
176
1.52M
                : tablet(tablet), tablet_map(tablet_map) {}
177
1.52M
        ~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.52M
        std::shared_ptr<CloudTablet> tablet;
182
1.52M
        TabletMap& tablet_map;
183
1.52M
    };
184
185
18.4E
    VLOG_DEBUG << "get_tablet tablet_id=" << tablet_id << " stack: " << get_stack_trace();
186
187
1.52M
    auto tablet_id_str = std::to_string(tablet_id);
188
1.52M
    CacheKey key(tablet_id_str);
189
1.52M
    auto* handle = _cache->lookup(key);
190
191
1.52M
    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
117k
        if (force_use_only_cached) {
199
0
            LOG(INFO) << "tablet=" << tablet_id
200
0
                      << "does not exists in local tablet cache, because param "
201
0
                         "force_use_only_cached=true, "
202
0
                         "treat it as an error";
203
0
            return ResultError(Status::InternalError(
204
0
                    "tablet={} does not exists in local tablet cache, because param "
205
0
                    "force_use_only_cached=true, "
206
0
                    "treat it as an error",
207
0
                    tablet_id));
208
0
        }
209
117k
        TEST_SYNC_POINT("CloudTabletMgr::get_tablet.not_found_in_cache");
210
117k
        if (sync_stats) {
211
12.4k
            ++sync_stats->tablet_meta_cache_miss;
212
12.4k
        }
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
117k
        auto load_tablet = [this, &key, warmup_data, sync_delete_bitmap, sync_stats, cache_on_miss](
223
117k
                                   int64_t tablet_id) -> Result<std::shared_ptr<CloudTablet>> {
224
117k
            TabletMetaSharedPtr tablet_meta;
225
117k
            auto start = std::chrono::steady_clock::now();
226
117k
            auto st = _engine.meta_mgr().get_tablet_meta(tablet_id, &tablet_meta);
227
117k
            auto end = std::chrono::steady_clock::now();
228
117k
            if (sync_stats) {
229
12.4k
                sync_stats->get_remote_tablet_meta_rpc_ns +=
230
12.4k
                        std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
231
12.4k
            }
232
117k
            if (!st.ok()) {
233
110
                LOG(WARNING) << "failed to tablet " << tablet_id << ": " << st;
234
110
                return ResultError(st);
235
110
            }
236
237
116k
            auto tablet = std::make_shared<CloudTablet>(_engine, std::move(tablet_meta));
238
            // MUST sync stats to let compaction scheduler work correctly
239
116k
            SyncOptions options;
240
116k
            options.warmup_delta_data = warmup_data;
241
116k
            options.sync_delete_bitmap = sync_delete_bitmap;
242
116k
            st = _engine.meta_mgr().sync_tablet_rowsets(tablet.get(), options, sync_stats);
243
116k
            if (!st.ok()) {
244
0
                LOG(WARNING) << "failed to sync tablet " << tablet_id << ": " << st;
245
0
                return ResultError(st);
246
0
            }
247
248
116k
            if (!cache_on_miss) {
249
0
                set_tablet_access_time_ms(tablet.get());
250
0
                return tablet;
251
0
            }
252
253
116k
            auto value = std::make_unique<Value>(tablet, *_tablet_map);
254
116k
            auto* insert_handle = _cache->insert(key, value.release(), 1, sizeof(CloudTablet),
255
116k
                                                 CachePriority::NORMAL);
256
116k
            auto ret = std::shared_ptr<CloudTablet>(tablet.get(),
257
116k
                                                    [this, insert_handle](CloudTablet* tablet_ptr) {
258
116k
                                                        set_tablet_access_time_ms(tablet_ptr);
259
116k
                                                        _cache->release(insert_handle);
260
116k
                                                    });
261
116k
            _tablet_map->put(std::move(tablet));
262
116k
            return ret;
263
116k
        };
264
265
117k
        auto load_result = s_singleflight_load_tablet.load(tablet_id, std::move(load_tablet));
266
117k
        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
117k
        auto tablet = load_result.value();
271
117k
        set_tablet_access_time_ms(tablet.get());
272
117k
        return tablet;
273
117k
    }
274
1.40M
    if (sync_stats) {
275
1.01M
        ++sync_stats->tablet_meta_cache_hit;
276
1.01M
    }
277
1.40M
    CloudTablet* tablet_raw_ptr = reinterpret_cast<Value*>(_cache->value(handle))->tablet.get();
278
1.40M
    set_tablet_access_time_ms(tablet_raw_ptr);
279
1.42M
    auto tablet = std::shared_ptr<CloudTablet>(tablet_raw_ptr, [this, handle](CloudTablet* tablet) {
280
1.42M
        set_tablet_access_time_ms(tablet);
281
1.42M
        _cache->release(handle);
282
1.42M
    });
283
1.40M
    return tablet;
284
1.52M
}
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
192
void CloudTabletMgr::erase_tablet(int64_t tablet_id) {
299
192
    auto tablet_id_str = std::to_string(tablet_id);
300
192
    CacheKey key(tablet_id_str.data(), tablet_id_str.size());
301
192
    _cache->erase(key);
302
192
}
303
304
8
void CloudTabletMgr::vacuum_stale_rowsets(const CountDownLatch& stop_latch) {
305
8
    LOG_INFO("begin to vacuum stale rowsets");
306
8
    std::vector<std::shared_ptr<CloudTablet>> tablets_to_vacuum;
307
8
    tablets_to_vacuum.reserve(_tablet_map->size());
308
395k
    _tablet_map->traverse([&tablets_to_vacuum](auto&& t) {
309
395k
        if (t->has_stale_rowsets()) {
310
9.17k
            tablets_to_vacuum.push_back(t);
311
9.17k
        }
312
395k
    });
313
8
    int num_vacuumed = 0;
314
9.17k
    for (auto& t : tablets_to_vacuum) {
315
9.17k
        if (stop_latch.count() <= 0) {
316
0
            break;
317
0
        }
318
319
9.17k
        num_vacuumed += t->delete_expired_stale_rowsets();
320
9.17k
    }
321
8
    LOG_INFO("finish vacuum stale rowsets")
322
8
            .tag("num_vacuumed", num_vacuumed)
323
8
            .tag("num_tablets", tablets_to_vacuum.size());
324
325
8
    {
326
8
        LOG_INFO("begin to remove unused rowsets");
327
8
        std::vector<std::shared_ptr<CloudTablet>> tablets_to_remove_unused_rowsets;
328
8
        tablets_to_remove_unused_rowsets.reserve(_tablet_map->size());
329
396k
        _tablet_map->traverse([&tablets_to_remove_unused_rowsets](auto&& t) {
330
396k
            if (t->need_remove_unused_rowsets()) {
331
4.62k
                tablets_to_remove_unused_rowsets.push_back(t);
332
4.62k
            }
333
396k
        });
334
4.62k
        for (auto& t : tablets_to_remove_unused_rowsets) {
335
4.62k
            t->remove_unused_rowsets();
336
4.62k
        }
337
8
        LOG_INFO("finish remove unused rowsets")
338
8
                .tag("num_tablets", tablets_to_remove_unused_rowsets.size());
339
8
        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
8
    }
370
8
    {
371
8
        _tablet_map->traverse(
372
396k
                [](auto&& tablet) { tablet->clear_unused_visible_pending_rowsets(); });
373
8
    }
374
8
}
375
376
14.8k
std::vector<std::weak_ptr<CloudTablet>> CloudTabletMgr::get_weak_tablets() {
377
14.8k
    std::vector<std::weak_ptr<CloudTablet>> weak_tablets;
378
14.8k
    weak_tablets.reserve(_tablet_map->size());
379
478M
    _tablet_map->traverse([&weak_tablets](auto& t) { weak_tablets.push_back(t); });
380
14.8k
    return weak_tablets;
381
14.8k
}
382
383
4
void CloudTabletMgr::sync_tablets(const CountDownLatch& stop_latch) {
384
4
    LOG_INFO("begin to sync tablets");
385
4
    int64_t last_sync_time_bound = ::time(nullptr) - config::tablet_sync_interval_s;
386
387
4
    auto weak_tablets = get_weak_tablets();
388
389
    // sort by last_sync_time
390
4
    static auto cmp = [](const auto& a, const auto& b) { return a.first < b.first; };
391
4
    std::multiset<std::pair<int64_t, std::weak_ptr<CloudTablet>>, decltype(cmp)>
392
4
            sync_time_tablet_set(cmp);
393
394
219k
    for (auto& weak_tablet : weak_tablets) {
395
219k
        if (auto tablet = weak_tablet.lock()) {
396
219k
            int64_t last_sync_time = tablet->last_sync_time_s;
397
219k
            if (last_sync_time <= last_sync_time_bound) {
398
0
                sync_time_tablet_set.emplace(last_sync_time, weak_tablet);
399
0
            }
400
219k
        }
401
219k
    }
402
403
4
    int num_sync = 0;
404
4
    for (auto&& [_, weak_tablet] : sync_time_tablet_set) {
405
0
        if (stop_latch.count() <= 0) {
406
0
            break;
407
0
        }
408
409
0
        if (auto tablet = weak_tablet.lock()) {
410
0
            if (tablet->last_sync_time_s > last_sync_time_bound) {
411
0
                continue;
412
0
            }
413
414
0
            ++num_sync;
415
0
            auto st = tablet->sync_meta();
416
0
            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
0
            SyncOptions options;
423
0
            options.query_version = -1;
424
0
            options.merge_schema = true;
425
0
            st = tablet->sync_rowsets(options);
426
0
            if (!st) {
427
0
                LOG_WARNING("failed to sync tablet rowsets {}", tablet->tablet_id()).error(st);
428
0
            }
429
0
        }
430
0
    }
431
4
    LOG_INFO("finish sync tablets").tag("num_sync", num_sync);
432
4
}
433
434
Status CloudTabletMgr::get_topn_tablets_to_compact(
435
        int n, CompactionType compaction_type, const std::function<bool(CloudTablet*)>& filter_out,
436
14.8k
        std::vector<std::shared_ptr<CloudTablet>>* tablets, CompactionScoreStats* score_stats) {
437
14.8k
    DCHECK(compaction_type == CompactionType::BASE_COMPACTION ||
438
14.8k
           compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
439
14.8k
           compaction_type == CompactionType::CUMU_BINLOG_COMPACTION);
440
14.8k
    *score_stats = {};
441
14.8k
    score_stats->scanned = true;
442
14.8k
    int64_t max_score_tablet_id = 0;
443
    // clang-format off
444
475M
    auto score = [compaction_type](CloudTablet* t) {
445
475M
        if (compaction_type == CompactionType::CUMU_BINLOG_COMPACTION && !t->is_row_binlog_tablet()) {
446
2
            return int64_t {0};
447
2
        }
448
475M
        if (compaction_type != CompactionType::CUMU_BINLOG_COMPACTION && t->is_row_binlog_tablet()) {
449
0
            return int64_t {0};
450
0
        }
451
475M
        return compaction_type == CompactionType::BASE_COMPACTION ? t->get_cloud_base_compaction_score()
452
475M
               : (compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
453
427M
                  compaction_type == CompactionType::CUMU_BINLOG_COMPACTION) ? t->get_cloud_cumu_compaction_score()
454
427M
               : 0;
455
475M
    };
456
457
14.8k
    using namespace std::chrono;
458
14.8k
    auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
459
407M
    auto skip = [now, compaction_type](CloudTablet* t) {
460
407M
        auto* cloud_cluster_info = static_cast<CloudClusterInfo*>(ExecEnv::GetInstance()->cluster_info());
461
462
407M
        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
407M
        if (cloud_cluster_info->should_skip_compaction(t)) {
471
0
            return true;
472
0
        }
473
474
407M
        int32_t max_version_config = t->max_version_config();
475
407M
        if (compaction_type == CompactionType::BASE_COMPACTION) {
476
47.0M
            bool is_recent_failure = now - t->last_base_compaction_failure_time() < config::min_compaction_failure_interval_ms;
477
47.0M
            bool is_frozen = (now - t->last_load_time_ms > config::compaction_load_max_freeze_interval_s * 1000
478
47.0M
                   && now - t->last_base_compaction_success_time_ms < config::base_compaction_freeze_interval_s * 1000
479
47.0M
                   && t->fetch_add_approximate_num_rowsets(0) < max_version_config / 2);
480
47.0M
            g_base_compaction_not_frozen_tablet_num << !is_frozen;
481
47.0M
            return is_recent_failure || is_frozen;
482
47.0M
        }
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
360M
        bool is_recent_failure = now - t->last_cumu_compaction_failure_time() < config::min_compaction_failure_interval_ms;
487
360M
        bool is_recent_no_suitable_version = now - t->last_cumu_no_suitable_version_ms < config::min_compaction_failure_interval_ms;
488
360M
        bool is_frozen = (now - t->last_load_time_ms > config::compaction_load_max_freeze_interval_s * 1000
489
360M
               && now - t->last_cumu_compaction_success_time_ms < config::cumu_compaction_interval_s * 1000
490
360M
               && t->fetch_add_approximate_num_rowsets(0) < max_version_config / 2);
491
360M
        g_cumu_compaction_not_frozen_tablet_num << !is_frozen;
492
360M
        return is_recent_failure || is_recent_no_suitable_version || is_frozen;
493
407M
    };
494
    // We don't schedule tablets that are disabled for compaction
495
413M
    auto disable = [](CloudTablet* t) { return t->tablet_meta()->tablet_schema()->disable_auto_compaction(); };
496
497
14.8k
    auto [num_filtered, num_disabled, num_skipped] = std::make_tuple(0, 0, 0);
498
499
14.8k
    auto weak_tablets = get_weak_tablets();
500
14.8k
    std::vector<std::pair<std::shared_ptr<CloudTablet>, int64_t>> buf;
501
14.8k
    buf.reserve(n + 1);
502
475M
    for (auto& weak_tablet : weak_tablets) {
503
475M
        auto t = weak_tablet.lock();
504
475M
        if (t == nullptr) { continue; }
505
506
475M
        int64_t s = score(t.get());
507
475M
        if (s <= 0) { continue; }
508
414M
        if (s > score_stats->max_score) {
509
82.6k
            max_score_tablet_id = t->tablet_id();
510
82.6k
            score_stats->max_score = s;
511
82.6k
        }
512
414M
        if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
513
366M
            int64_t* policy_max_score =
514
366M
                    t->tablet_meta()->compaction_policy() == CUMULATIVE_TIME_SERIES_POLICY
515
366M
                            ? &score_stats->time_series_max_score
516
366M
                            : &score_stats->size_based_max_score;
517
366M
            if (s > *policy_max_score) {
518
90.3k
                *policy_max_score = s;
519
90.3k
            }
520
366M
        }
521
522
414M
        if (filter_out(t.get())) { ++num_filtered; continue; }
523
413M
        if (disable(t.get())) { ++num_disabled; continue; }
524
407M
        if (skip(t.get())) { ++num_skipped; continue; }
525
526
403M
        buf.emplace_back(std::move(t), s);
527
5.22G
        std::sort(buf.begin(), buf.end(), [](auto& a, auto& b) { return a.second > b.second; });
528
403M
        if (buf.size() > n) { buf.pop_back(); }
529
403M
    }
530
531
14.8k
    LOG_EVERY_N(INFO, 1000) << "get_topn_compaction_score, n=" << n << " type=" << compaction_type
532
16
               << " num_tablets=" << weak_tablets.size() << " num_skipped=" << num_skipped
533
16
               << " num_disabled=" << num_disabled << " num_filtered=" << num_filtered
534
16
               << " max_score=" << score_stats->max_score << " max_score_tablet=" << max_score_tablet_id
535
90
               << " tablets=[" << [&buf] { std::stringstream ss; for (auto& i : buf) ss << i.first->tablet_id() << ":" << i.second << ","; return ss.str(); }() << "]"
536
14.8k
               ;
537
    // clang-format on
538
539
14.8k
    tablets->clear();
540
14.8k
    tablets->reserve(n + 1);
541
89.8k
    for (auto& [t, _] : buf) {
542
89.8k
        tablets->emplace_back(std::move(t));
543
89.8k
    }
544
545
14.8k
    return Status::OK();
546
14.8k
}
547
548
void CloudTabletMgr::build_all_report_tablets_info(std::map<TTabletId, TTablet>* tablets_info,
549
47
                                                   uint64_t* tablet_num) {
550
47
    DCHECK(tablets_info != nullptr);
551
47
    VLOG_NOTICE << "begin to build all report cloud tablets info";
552
553
47
    HistogramStat tablet_version_num_hist;
554
555
2.38M
    auto handler = [&](const std::weak_ptr<CloudTablet>& tablet_wk) {
556
2.38M
        auto tablet = tablet_wk.lock();
557
2.38M
        if (!tablet) return;
558
2.38M
        (*tablet_num)++;
559
2.38M
        TTabletInfo tablet_info;
560
2.38M
        tablet->build_tablet_report_info(&tablet_info);
561
2.38M
        using namespace std::chrono;
562
2.38M
        int64_t now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
563
2.38M
        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
2.38M
            return;
566
2.38M
        }
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
47
    auto weak_tablets = get_weak_tablets();
576
47
    std::for_each(weak_tablets.begin(), weak_tablets.end(), handler);
577
578
47
    DorisMetrics::instance()->tablet_version_num_distribution->set_histogram(
579
47
            tablet_version_num_hist);
580
47
    LOG(INFO) << "success to build all cloud report tablets info. all_tablet_count=" << *tablet_num
581
47
              << " exceed drop time limit count=" << tablets_info->size();
582
47
}
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
9
        uint64_t* max_delete_bitmap_score, uint64_t* max_base_rowset_delete_bitmap_score) {
600
9
    int64_t max_delete_bitmap_score_tablet_id = 0;
601
9
    OlapStopWatch watch;
602
9
    uint64_t total_delete_map_count = 0;
603
9
    int64_t max_base_rowset_delete_bitmap_score_tablet_id = 0;
604
9
    int n = config::check_tablet_delete_bitmap_score_top_n;
605
9
    std::vector<std::pair<std::shared_ptr<CloudTablet>, int64_t>> buf;
606
9
    buf.reserve(n + 1);
607
439k
    auto handler = [&](const std::weak_ptr<CloudTablet>& tablet_wk) {
608
439k
        auto t = tablet_wk.lock();
609
439k
        if (!t || !t->enable_unique_key_merge_on_write()) return;
610
114k
        uint64_t delete_bitmap_count =
611
114k
                t.get()->tablet_meta()->delete_bitmap().get_delete_bitmap_count();
612
114k
        total_delete_map_count += delete_bitmap_count;
613
114k
        if (delete_bitmap_count > *max_delete_bitmap_score) {
614
62
            max_delete_bitmap_score_tablet_id = t->tablet_id();
615
62
            *max_delete_bitmap_score = delete_bitmap_count;
616
62
        }
617
114k
        buf.emplace_back(std::move(t), delete_bitmap_count);
618
2.28M
        std::sort(buf.begin(), buf.end(), [](auto& a, auto& b) { return a.second > b.second; });
619
114k
        if (buf.size() > n) {
620
114k
            buf.pop_back();
621
114k
        }
622
114k
    };
623
9
    auto weak_tablets = get_weak_tablets();
624
9
    std::for_each(weak_tablets.begin(), weak_tablets.end(), handler);
625
90
    for (auto& [t, _] : buf) {
626
90
        t->get_base_rowset_delete_bitmap_count(max_base_rowset_delete_bitmap_score,
627
90
                                               &max_base_rowset_delete_bitmap_score_tablet_id);
628
90
    }
629
9
    std::stringstream ss;
630
90
    for (auto& i : buf) {
631
90
        ss << i.first->tablet_id() << ": " << i.second << ", ";
632
90
    }
633
9
    LOG(INFO) << "get_topn_tablet_delete_bitmap_score, n=" << n
634
9
              << ", tablet size=" << weak_tablets.size()
635
9
              << ", total_delete_map_count=" << total_delete_map_count
636
9
              << ", cost(us)=" << watch.get_elapse_time_us()
637
9
              << ", max_delete_bitmap_score=" << *max_delete_bitmap_score
638
9
              << ", max_delete_bitmap_score_tablet_id=" << max_delete_bitmap_score_tablet_id
639
9
              << ", max_base_rowset_delete_bitmap_score=" << *max_base_rowset_delete_bitmap_score
640
9
              << ", max_base_rowset_delete_bitmap_score_tablet_id="
641
9
              << max_base_rowset_delete_bitmap_score_tablet_id << ", tablets=[" << ss.str() << "]";
642
9
}
643
644
4
std::vector<std::shared_ptr<CloudTablet>> CloudTabletMgr::get_all_tablet() {
645
4
    std::vector<std::shared_ptr<CloudTablet>> tablets;
646
4
    tablets.reserve(_tablet_map->size());
647
123k
    _tablet_map->traverse([&tablets](auto& t) { tablets.push_back(t); });
648
4
    return tablets;
649
4
}
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