Coverage Report

Created: 2026-07-29 15:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_warm_up_manager.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_warm_up_manager.h"
19
20
#include <bthread/condition_variable.h>
21
#include <bthread/mutex.h>
22
#include <bthread/unstable.h>
23
#include <butil/time.h>
24
#include <bvar/bvar.h>
25
#include <bvar/reducer.h>
26
27
#include <algorithm>
28
#include <chrono>
29
#include <cstddef>
30
#include <list>
31
#include <string>
32
#include <tuple>
33
#include <vector>
34
35
#include "bthread/mutex.h"
36
#include "bvar/bvar.h"
37
#include "cloud/cloud_tablet.h"
38
#include "cloud/cloud_tablet_mgr.h"
39
#include "cloud/config.h"
40
#include "common/cast_set.h"
41
#include "common/check.h"
42
#include "common/config.h"
43
#include "common/logging.h"
44
#include "cpp/sync_point.h"
45
#include "io/cache/block_file_cache_downloader.h"
46
#include "runtime/exec_env.h"
47
#include "service/backend_options.h"
48
#include "storage/index/inverted/inverted_index_desc.h"
49
#include "storage/rowset/beta_rowset.h"
50
#include "storage/tablet/tablet.h"
51
#include "util/brpc_client_cache.h" // BrpcClientCache
52
#include "util/bvar_windowed_adder.h"
53
#include "util/client_cache.h"
54
#include "util/defer_op.h"
55
#include "util/stack_util.h"
56
#include "util/thrift_rpc_helper.h"
57
#include "util/time.h"
58
59
namespace doris {
60
61
// Peer candidate management statistics
62
bvar::Adder<uint64_t> g_peer_candidate_cache_hit("peer_candidate_cache_hit");
63
bvar::Adder<uint64_t> g_peer_candidate_cache_miss("peer_candidate_cache_miss");
64
bvar::Adder<uint64_t> g_peer_lazy_fetch_total("peer_lazy_fetch_total");
65
bvar::Adder<uint64_t> g_peer_lazy_fetch_success("peer_lazy_fetch_success");
66
bvar::Adder<uint64_t> g_peer_lazy_fetch_failed("peer_lazy_fetch_failed");
67
bvar::LatencyRecorder g_peer_lazy_fetch_latency("peer_lazy_fetch_latency");
68
bvar::Adder<uint64_t> g_peer_rpc_failure_eviction("peer_rpc_failure_eviction");
69
bvar::Adder<uint64_t> g_peer_candidate_expiry_eviction("peer_candidate_expiry_eviction");
70
bvar::Adder<uint64_t> g_peer_candidate_rotate("peer_candidate_rotate");
71
bvar::Adder<uint64_t> g_peer_tablet_cooldown_entered("peer_tablet_cooldown_entered");
72
bvar::Adder<uint64_t> g_peer_tablet_cooldown_skipped("peer_tablet_cooldown_skipped");
73
74
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_skipped_rowset_num(
75
        "file_cache_event_driven_warm_up_skipped_rowset_num");
76
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_segment_size(
77
        "file_cache_event_driven_warm_up_requested_segment_size");
78
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_segment_num(
79
        "file_cache_event_driven_warm_up_requested_segment_num");
80
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_index_size(
81
        "file_cache_event_driven_warm_up_requested_index_size");
82
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_index_num(
83
        "file_cache_event_driven_warm_up_requested_index_num");
84
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_tablet_num(
85
        "file_cache_once_or_periodic_warm_up_submitted_tablet_num");
86
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_tablet_num(
87
        "file_cache_once_or_periodic_warm_up_finished_tablet_num");
88
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_segment_size(
89
        "file_cache_once_or_periodic_warm_up_submitted_segment_size");
90
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_segment_num(
91
        "file_cache_once_or_periodic_warm_up_submitted_segment_num");
92
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_index_size(
93
        "file_cache_once_or_periodic_warm_up_submitted_index_size");
94
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_index_num(
95
        "file_cache_once_or_periodic_warm_up_submitted_index_num");
96
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_segment_size(
97
        "file_cache_once_or_periodic_warm_up_finished_segment_size");
98
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_segment_num(
99
        "file_cache_once_or_periodic_warm_up_finished_segment_num");
100
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_index_size(
101
        "file_cache_once_or_periodic_warm_up_finished_index_size");
102
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_index_num(
103
        "file_cache_once_or_periodic_warm_up_finished_index_num");
104
bvar::Adder<uint64_t> g_file_cache_recycle_cache_requested_segment_num(
105
        "file_cache_recycle_cache_requested_segment_num");
106
bvar::Adder<uint64_t> g_file_cache_recycle_cache_requested_index_num(
107
        "file_cache_recycle_cache_requested_index_num");
108
bvar::Status<int64_t> g_file_cache_warm_up_rowset_last_call_unix_ts(
109
        "file_cache_warm_up_rowset_last_call_unix_ts", 0);
110
bvar::Adder<uint64_t> file_cache_warm_up_failed_task_num("file_cache_warm_up", "failed_task_num");
111
bvar::Adder<int64_t> g_balance_tablet_be_mapping_size("balance_tablet_be_mapping_size");
112
// Number of warm up jobs currently held in this BE's memory.
113
// Incremented when FE dispatches a new job to this BE (SET_JOB / SET_BATCH / event SET_JOB),
114
// decremented when the job is cleared (CLEAR_JOB / event CLEAR_JOB).
115
bvar::Adder<int64_t> g_file_cache_warm_up_job_num("file_cache_warm_up_job_num");
116
117
bvar::LatencyRecorder g_file_cache_warm_up_rowset_wait_for_compaction_latency(
118
        "file_cache_warm_up_rowset_wait_for_compaction_latency");
119
120
// Per-job windowed metrics for source BE
121
// bvar::Window enforces MAX_SECONDS_LIMIT = 3600, so the longest window is 1h.
122
static constexpr int WINDOW_5M = 300;
123
static constexpr int WINDOW_30M = 1800;
124
static constexpr int WINDOW_1H = 3600;
125
126
MBvarWindowedAdder g_warmup_ed_requested_segment_num("warmup_ed_requested_segment_num", {"job_id"},
127
                                                     {WINDOW_5M, WINDOW_30M, WINDOW_1H}, false);
128
MBvarWindowedAdder g_warmup_ed_requested_segment_size("warmup_ed_requested_segment_size",
129
                                                      {"job_id"},
130
                                                      {WINDOW_5M, WINDOW_30M, WINDOW_1H}, false);
131
MBvarWindowedAdder g_warmup_ed_requested_index_num("warmup_ed_requested_index_num", {"job_id"},
132
                                                   {WINDOW_5M, WINDOW_30M, WINDOW_1H}, false);
133
MBvarWindowedAdder g_warmup_ed_requested_index_size("warmup_ed_requested_index_size", {"job_id"},
134
                                                    {WINDOW_5M, WINDOW_30M, WINDOW_1H}, false);
135
bvar::MultiDimension<bvar::Status<int64_t>> g_warmup_ed_last_trigger_ts({"job_id"});
136
137
57
CloudWarmUpManager::CloudWarmUpManager(CloudStorageEngine& engine) : _engine(engine) {
138
57
    auto st = ThreadPoolBuilder("CloudWarmUpManagerThreadPool")
139
57
                      .set_min_threads(config::warm_up_manager_thread_pool_size)
140
57
                      .set_max_threads(config::warm_up_manager_thread_pool_size)
141
57
                      .build(&_thread_pool);
142
57
    DORIS_CHECK(st.ok()) << st;
143
57
    _thread_pool_token = _thread_pool->new_token(ThreadPool::ExecutionMode::CONCURRENT);
144
57
    DORIS_CHECK(_thread_pool_token != nullptr);
145
57
    _download_thread = std::thread(&CloudWarmUpManager::handle_jobs, this);
146
57
    _cleanup_thread = std::thread(&CloudWarmUpManager::run_cleanup_loop, this);
147
57
}
148
149
56
CloudWarmUpManager::~CloudWarmUpManager() {
150
56
    {
151
        // Set _closed under both mutexes so that both threads' wait predicates see it.
152
56
        std::lock_guard lock(_mtx);
153
56
        std::lock_guard<std::mutex> cleanup_lock(_cleanup_mtx);
154
56
        _closed = true;
155
56
    }
156
56
    _cond.notify_all();
157
56
    _cleanup_cond.notify_all();
158
56
    if (_download_thread.joinable()) {
159
56
        _download_thread.join();
160
56
    }
161
56
    if (_cleanup_thread.joinable()) {
162
56
        _cleanup_thread.join();
163
56
    }
164
165
56
    _thread_pool_token->shutdown();
166
56
    _thread_pool_token.reset();
167
56
    _thread_pool->shutdown();
168
56
    _thread_pool.reset();
169
170
573k
    for (auto& shard : _balanced_tablets_shards) {
171
573k
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
172
573k
        shard.tablets.clear();
173
573k
    }
174
56
}
175
176
0
std::unordered_map<std::string, RowsetMetaSharedPtr> snapshot_rs_metas(BaseTablet* tablet) {
177
0
    std::unordered_map<std::string, RowsetMetaSharedPtr> id_to_rowset_meta_map;
178
0
    auto visitor = [&id_to_rowset_meta_map](const RowsetSharedPtr& r) {
179
0
        id_to_rowset_meta_map.emplace(r->rowset_meta()->rowset_id().to_string(), r->rowset_meta());
180
0
    };
181
0
    constexpr bool include_stale = false;
182
0
    tablet->traverse_rowsets(visitor, include_stale);
183
0
    return id_to_rowset_meta_map;
184
0
}
185
186
void CloudWarmUpManager::submit_download_tasks(io::Path path, int64_t file_size,
187
                                               io::FileSystemSPtr file_system,
188
                                               int64_t expiration_time,
189
                                               std::shared_ptr<bthread::CountdownEvent> wait,
190
                                               bool is_index, std::function<void(Status)> done_cb,
191
0
                                               int64_t tablet_id) {
192
0
    VLOG_DEBUG << "submit warm up task for file: " << path << ", file_size: " << file_size
193
0
               << ", expiration_time: " << expiration_time
194
0
               << ", is_index: " << (is_index ? "true" : "false");
195
0
    if (file_size < 0) {
196
0
        auto st = file_system->file_size(path, &file_size);
197
0
        if (!st.ok()) [[unlikely]] {
198
0
            LOG(WARNING) << "get file size failed: " << path;
199
0
            file_cache_warm_up_failed_task_num << 1;
200
0
            return;
201
0
        }
202
0
    }
203
0
    if (is_index) {
204
0
        g_file_cache_once_or_periodic_warm_up_submitted_index_num << 1;
205
0
        g_file_cache_once_or_periodic_warm_up_submitted_index_size << file_size;
206
0
    } else {
207
0
        g_file_cache_once_or_periodic_warm_up_submitted_segment_num << 1;
208
0
        g_file_cache_once_or_periodic_warm_up_submitted_segment_size << file_size;
209
0
    }
210
211
0
    const int64_t chunk_size = 10 * 1024 * 1024; // 10MB
212
0
    int64_t offset = 0;
213
0
    int64_t remaining_size = file_size;
214
215
0
    while (remaining_size > 0) {
216
0
        int64_t current_chunk_size = std::min(chunk_size, remaining_size);
217
0
        wait->add_count();
218
219
0
        _engine.file_cache_block_downloader().submit_download_task(io::DownloadFileMeta {
220
0
                .path = path,
221
0
                .file_size = file_size,
222
0
                .offset = offset,
223
0
                .download_size = current_chunk_size,
224
0
                .file_system = file_system,
225
0
                .ctx = {.expiration_time = expiration_time,
226
0
                        .is_dryrun = config::enable_reader_dryrun_when_download_file_cache,
227
0
                        .is_warmup = true},
228
0
                .download_done =
229
0
                        [=, done_cb = std::move(done_cb)](Status st) {
230
0
                            if (done_cb) done_cb(st);
231
0
                            if (!st) {
232
0
                                LOG_WARNING("Warm up error ").error(st);
233
0
                            } else if (is_index) {
234
0
                                g_file_cache_once_or_periodic_warm_up_finished_index_num
235
0
                                        << (offset == 0 ? 1 : 0);
236
0
                                g_file_cache_once_or_periodic_warm_up_finished_index_size
237
0
                                        << current_chunk_size;
238
0
                            } else {
239
0
                                g_file_cache_once_or_periodic_warm_up_finished_segment_num
240
0
                                        << (offset == 0 ? 1 : 0);
241
0
                                g_file_cache_once_or_periodic_warm_up_finished_segment_size
242
0
                                        << current_chunk_size;
243
0
                            }
244
0
                            wait->signal();
245
0
                        },
246
0
                .tablet_id = tablet_id,
247
0
        });
248
249
0
        offset += current_chunk_size;
250
0
        remaining_size -= current_chunk_size;
251
0
    }
252
0
}
253
254
1
void CloudWarmUpManager::handle_jobs() {
255
1
#ifndef BE_TEST
256
1
    constexpr int WAIT_TIME_SECONDS = 600;
257
2
    while (true) {
258
1
        std::shared_ptr<JobMeta> cur_job = nullptr;
259
1
        {
260
1
            std::unique_lock lock(_mtx);
261
2
            while (!_closed && _pending_job_metas.empty()) {
262
1
                _cond.wait(lock);
263
1
            }
264
1
            if (_closed) break;
265
1
            if (!_pending_job_metas.empty()) {
266
0
                cur_job = _pending_job_metas.front();
267
0
            }
268
1
        }
269
270
1
        if (!cur_job) {
271
0
            LOG_WARNING("Warm up job is null");
272
0
            continue;
273
0
        }
274
275
1
        std::shared_ptr<bthread::CountdownEvent> wait =
276
1
                std::make_shared<bthread::CountdownEvent>(0);
277
278
1
        for (int64_t tablet_id : cur_job->tablet_ids) {
279
0
            VLOG_DEBUG << "Warm up tablet " << tablet_id << " stack: " << get_stack_trace();
280
0
            if (_cur_job_id == 0) { // The job is canceled
281
0
                break;
282
0
            }
283
0
            auto res = _engine.tablet_mgr().get_tablet(tablet_id);
284
0
            if (!res.has_value()) {
285
0
                LOG_WARNING("Warm up error ").tag("tablet_id", tablet_id).error(res.error());
286
0
                continue;
287
0
            }
288
0
            auto tablet = res.value();
289
0
            auto st = tablet->sync_rowsets();
290
0
            if (!st) {
291
0
                LOG_WARNING("Warm up error ").tag("tablet_id", tablet_id).error(st);
292
0
                continue;
293
0
            }
294
295
0
            auto tablet_meta = tablet->tablet_meta();
296
0
            auto rs_metas = snapshot_rs_metas(tablet.get());
297
0
            for (auto& [_, rs] : rs_metas) {
298
0
                auto storage_resource = rs->remote_storage_resource();
299
0
                if (!storage_resource) {
300
0
                    LOG(WARNING) << storage_resource.error();
301
0
                    continue;
302
0
                }
303
304
0
                int64_t expiration_time = tablet_meta->ttl_seconds();
305
0
                if (!tablet->add_rowset_warmup_state(*rs, WarmUpTriggerSource::JOB)) {
306
0
                    LOG(INFO) << "found duplicate warmup task for rowset " << rs->rowset_id()
307
0
                              << ", skip it";
308
0
                    continue;
309
0
                }
310
0
                for (int64_t seg_id = 0; seg_id < rs->num_segments(); seg_id++) {
311
                    // 1st. download segment files
312
                    // Use rs->fs() instead of storage_resource.value()->fs to support packed
313
                    // files. PackedFileSystem wrapper in RowsetMeta::fs() handles the index_map
314
                    // lookup and reads from the correct packed file.
315
0
                    if (!config::file_cache_enable_only_warm_up_idx) {
316
0
                        submit_download_tasks(
317
0
                                storage_resource.value()->remote_segment_path(*rs, seg_id),
318
0
                                rs->segment_file_size(cast_set<int>(seg_id)), rs->fs(),
319
0
                                expiration_time, wait, false,
320
0
                                [tablet, rs, seg_id](Status st) {
321
0
                                    VLOG_DEBUG << "warmup rowset " << rs->version() << " segment "
322
0
                                               << seg_id << " completed";
323
0
                                    if (tablet->complete_rowset_segment_warmup(
324
0
                                                      WarmUpTriggerSource::JOB, rs->rowset_id(), st,
325
0
                                                      1, 0)
326
0
                                                .trigger_source == WarmUpTriggerSource::JOB) {
327
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
328
0
                                                   << " completed";
329
0
                                    }
330
0
                                },
331
0
                                tablet_id);
332
0
                    }
333
334
                    // 2nd. download inverted index files
335
0
                    int64_t file_size = -1;
336
0
                    auto schema_ptr = rs->tablet_schema();
337
0
                    auto idx_version = schema_ptr->get_inverted_index_storage_format();
338
0
                    const auto& idx_file_info = rs->inverted_index_file_info(cast_set<int>(seg_id));
339
0
                    if (idx_version == InvertedIndexStorageFormatPB::V1) {
340
0
                        auto&& inverted_index_info =
341
0
                                rs->inverted_index_file_info(cast_set<int>(seg_id));
342
0
                        std::unordered_map<int64_t, int64_t> index_size_map;
343
0
                        for (const auto& info : inverted_index_info.index_info()) {
344
0
                            if (info.index_file_size() != -1) {
345
0
                                index_size_map[info.index_id()] = info.index_file_size();
346
0
                            } else {
347
0
                                VLOG_DEBUG << "Invalid index_file_size for segment_id " << seg_id
348
0
                                           << ", index_id " << info.index_id();
349
0
                            }
350
0
                        }
351
0
                        for (const auto& index : schema_ptr->inverted_indexes()) {
352
0
                            auto idx_path = storage_resource.value()->remote_idx_v1_path(
353
0
                                    *rs, seg_id, index->index_id(), index->get_index_suffix());
354
0
                            if (idx_file_info.index_info_size() > 0) {
355
0
                                for (const auto& idx_info : idx_file_info.index_info()) {
356
0
                                    if (index->index_id() == idx_info.index_id() &&
357
0
                                        index->get_index_suffix() == idx_info.index_suffix()) {
358
0
                                        file_size = idx_info.index_file_size();
359
0
                                        break;
360
0
                                    }
361
0
                                }
362
0
                            }
363
0
                            tablet->update_rowset_warmup_state_inverted_idx_num(
364
0
                                    WarmUpTriggerSource::JOB, rs->rowset_id(), 1);
365
0
                            submit_download_tasks(
366
0
                                    idx_path, file_size, rs->fs(), expiration_time, wait, true,
367
0
                                    [=](Status st) {
368
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
369
0
                                                   << " segment " << seg_id
370
0
                                                   << "inverted idx:" << idx_path << " completed";
371
0
                                        if (tablet->complete_rowset_segment_warmup(
372
0
                                                          WarmUpTriggerSource::JOB, rs->rowset_id(),
373
0
                                                          st, 0, 1)
374
0
                                                    .trigger_source == WarmUpTriggerSource::JOB) {
375
0
                                            VLOG_DEBUG << "warmup rowset " << rs->version()
376
0
                                                       << " completed";
377
0
                                        }
378
0
                                    },
379
0
                                    tablet_id);
380
0
                        }
381
0
                    } else {
382
0
                        if (schema_ptr->has_inverted_index() || schema_ptr->has_ann_index()) {
383
0
                            auto idx_path =
384
0
                                    storage_resource.value()->remote_idx_v2_path(*rs, seg_id);
385
0
                            file_size = idx_file_info.has_index_size() ? idx_file_info.index_size()
386
0
                                                                       : -1;
387
0
                            tablet->update_rowset_warmup_state_inverted_idx_num(
388
0
                                    WarmUpTriggerSource::JOB, rs->rowset_id(), 1);
389
0
                            submit_download_tasks(
390
0
                                    idx_path, file_size, rs->fs(), expiration_time, wait, true,
391
0
                                    [=](Status st) {
392
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
393
0
                                                   << " segment " << seg_id
394
0
                                                   << "inverted idx:" << idx_path << " completed";
395
0
                                        if (tablet->complete_rowset_segment_warmup(
396
0
                                                          WarmUpTriggerSource::JOB, rs->rowset_id(),
397
0
                                                          st, 0, 1)
398
0
                                                    .trigger_source == WarmUpTriggerSource::JOB) {
399
0
                                            VLOG_DEBUG << "warmup rowset " << rs->version()
400
0
                                                       << " completed";
401
0
                                        }
402
0
                                    },
403
0
                                    tablet_id);
404
0
                        }
405
0
                    }
406
0
                }
407
0
            }
408
0
            g_file_cache_once_or_periodic_warm_up_finished_tablet_num << 1;
409
0
        }
410
411
1
        timespec time;
412
1
        time.tv_sec = UnixSeconds() + WAIT_TIME_SECONDS;
413
1
        if (wait->timed_wait(time)) {
414
0
            LOG_WARNING("Warm up {} tablets take a long time", cur_job->tablet_ids.size());
415
0
        }
416
1
        {
417
1
            std::unique_lock lock(_mtx);
418
1
            _finish_job.push_back(cur_job);
419
            // _pending_job_metas may be cleared by a CLEAR_JOB request
420
            // so we need to check it again.
421
1
            if (!_pending_job_metas.empty()) {
422
                // We can not call pop_front before the job is finished,
423
                // because GET_CURRENT_JOB_STATE_AND_LEASE is relying on the pending job size.
424
0
                _pending_job_metas.pop_front();
425
0
            }
426
1
        }
427
1
    }
428
1
#endif
429
1
}
430
431
JobMeta::JobMeta(const TJobMeta& meta)
432
0
        : be_ip(meta.be_ip), brpc_port(meta.brpc_port), tablet_ids(meta.tablet_ids) {
433
0
    switch (meta.download_type) {
434
0
    case TDownloadType::BE:
435
0
        download_type = DownloadType::BE;
436
0
        break;
437
0
    case TDownloadType::S3:
438
0
        download_type = DownloadType::S3;
439
0
        break;
440
0
    }
441
0
}
442
443
0
Status CloudWarmUpManager::check_and_set_job_id(int64_t job_id) {
444
0
    std::lock_guard lock(_mtx);
445
0
    if (_cur_job_id == 0) {
446
0
        _cur_job_id = job_id;
447
0
        g_file_cache_warm_up_job_num << 1;
448
0
    }
449
0
    Status st = Status::OK();
450
0
    if (_cur_job_id != job_id) {
451
0
        st = Status::InternalError("The job {} is running", _cur_job_id);
452
0
    }
453
0
    return st;
454
0
}
455
456
0
Status CloudWarmUpManager::check_and_set_batch_id(int64_t job_id, int64_t batch_id, bool* retry) {
457
0
    std::lock_guard lock(_mtx);
458
0
    Status st = Status::OK();
459
0
    if (_cur_job_id != 0 && _cur_job_id != job_id) {
460
0
        st = Status::InternalError("The job {} is not current job, current job is {}", job_id,
461
0
                                   _cur_job_id);
462
0
        return st;
463
0
    }
464
0
    if (_cur_job_id == 0) {
465
0
        _cur_job_id = job_id;
466
0
        g_file_cache_warm_up_job_num << 1;
467
0
    }
468
0
    if (_cur_batch_id == batch_id) {
469
0
        *retry = true;
470
0
        return st;
471
0
    }
472
0
    if (_pending_job_metas.empty()) {
473
0
        _cur_batch_id = batch_id;
474
0
    } else {
475
0
        st = Status::InternalError("The batch {} is not finish", _cur_batch_id);
476
0
    }
477
0
    return st;
478
0
}
479
480
0
void CloudWarmUpManager::add_job(const std::vector<TJobMeta>& job_metas) {
481
0
    {
482
0
        std::lock_guard lock(_mtx);
483
0
        std::for_each(job_metas.begin(), job_metas.end(), [this](const TJobMeta& meta) {
484
0
            _pending_job_metas.emplace_back(std::make_shared<JobMeta>(meta));
485
0
            g_file_cache_once_or_periodic_warm_up_submitted_tablet_num << meta.tablet_ids.size();
486
0
        });
487
0
    }
488
0
    _cond.notify_all();
489
0
}
490
491
#ifdef BE_TEST
492
void CloudWarmUpManager::consumer_job() {
493
    {
494
        std::unique_lock lock(_mtx);
495
        _finish_job.push_back(_pending_job_metas.front());
496
        _pending_job_metas.pop_front();
497
    }
498
}
499
500
#endif
501
502
0
std::tuple<int64_t, int64_t, int64_t, int64_t> CloudWarmUpManager::get_current_job_state() {
503
0
    std::lock_guard lock(_mtx);
504
0
    return std::make_tuple(_cur_job_id, _cur_batch_id, _pending_job_metas.size(),
505
0
                           _finish_job.size());
506
0
}
507
508
0
Status CloudWarmUpManager::clear_job(int64_t job_id) {
509
0
    std::lock_guard lock(_mtx);
510
0
    Status st = Status::OK();
511
0
    if (job_id == _cur_job_id) {
512
0
        if (_cur_job_id != 0) {
513
0
            g_file_cache_warm_up_job_num << -1;
514
0
        }
515
0
        _cur_job_id = 0;
516
0
        _cur_batch_id = -1;
517
0
        _pending_job_metas.clear();
518
0
        _finish_job.clear();
519
0
    } else {
520
0
        st = Status::InternalError("The job {} is not current job, current job is {}", job_id,
521
0
                                   _cur_job_id);
522
0
    }
523
0
    return st;
524
0
}
525
526
Status CloudWarmUpManager::set_event(int64_t job_id, TWarmUpEventType::type event, bool clear,
527
8
                                     const std::vector<int64_t>* table_ids) {
528
8
    DBUG_EXECUTE_IF("CloudWarmUpManager.set_event.ignore_all", {
529
8
        LOG(INFO) << "Ignore set_event request, job_id=" << job_id << ", event=" << event
530
8
                  << ", clear=" << clear;
531
8
        return Status::OK();
532
8
    });
533
8
    std::lock_guard lock(_mtx);
534
8
    Status st = Status::OK();
535
8
    if (event == TWarmUpEventType::type::LOAD) {
536
7
        if (clear) {
537
1
            if (_tablet_replica_cache.erase(job_id) > 0) {
538
1
                g_file_cache_warm_up_job_num << -1;
539
1
            }
540
1
            _event_driven_filters.erase(job_id);
541
1
            LOG(INFO) << "Clear event driven sync, job_id=" << job_id << ", event=" << event;
542
6
        } else if (!_tablet_replica_cache.contains(job_id)) {
543
5
            static_cast<void>(_tablet_replica_cache[job_id]);
544
5
            g_file_cache_warm_up_job_num << 1;
545
5
            if (table_ids != nullptr) {
546
                // table-level filter: set to the given table_id set (may be empty,
547
                // meaning all matched tables were deleted — warm up nothing)
548
4
                _event_driven_filters[job_id] =
549
4
                        std::unordered_set<int64_t>(table_ids->begin(), table_ids->end());
550
4
                LOG(INFO) << "Set event driven sync with table filter, job_id=" << job_id
551
4
                          << ", event=" << event << ", table_ids_size=" << table_ids->size();
552
4
            } else {
553
                // cluster-level: no filter, warm up all tables
554
1
                _event_driven_filters[job_id] = std::nullopt;
555
1
                LOG(INFO) << "Set event driven sync, job_id=" << job_id << ", event=" << event;
556
1
            }
557
5
        } else if (table_ids != nullptr) {
558
            // Update table_ids for an existing job (may be empty)
559
1
            _event_driven_filters[job_id] =
560
1
                    std::unordered_set<int64_t>(table_ids->begin(), table_ids->end());
561
1
            LOG(INFO) << "Updated table filter for event driven sync, job_id=" << job_id
562
1
                      << ", table_ids_size=" << table_ids->size();
563
1
        }
564
7
    } else {
565
1
        st = Status::InternalError("The event {} is not supported yet", event);
566
1
    }
567
8
    return st;
568
8
}
569
570
std::vector<JobReplicaInfo> CloudWarmUpManager::get_replica_info(int64_t tablet_id,
571
                                                                 int64_t table_id,
572
                                                                 bool bypass_cache,
573
78.8k
                                                                 bool& cache_hit) {
574
78.8k
    std::vector<JobReplicaInfo> replicas;
575
78.8k
    std::vector<int64_t> cancelled_jobs;
576
78.8k
    std::lock_guard<std::mutex> lock(_mtx);
577
78.8k
    cache_hit = false;
578
78.8k
    for (auto& [job_id, cache] : _tablet_replica_cache) {
579
        // Check table-level filter: skip this job if table_id doesn't match
580
        // table_id == 0 means the caller doesn't have table context (e.g., recycle_cache),
581
        // so skip filtering
582
4
        if (table_id != 0) {
583
2
            auto filter_it = _event_driven_filters.find(job_id);
584
2
            if (filter_it != _event_driven_filters.end() && filter_it->second.has_value()) {
585
2
                if (filter_it->second->find(table_id) == filter_it->second->end()) {
586
1
                    VLOG_DEBUG << "get_replica_info: table_id=" << table_id
587
0
                               << " not in filter for job_id=" << job_id << ", skipping";
588
1
                    continue;
589
1
                }
590
2
            }
591
2
        }
592
593
3
        if (!bypass_cache) {
594
3
            auto it = cache.find(tablet_id);
595
3
            if (it != cache.end()) {
596
                // check ttl expire
597
3
                auto now = std::chrono::steady_clock::now();
598
3
                auto sec = std::chrono::duration_cast<std::chrono::seconds>(now - it->second.first);
599
3
                if (sec.count() < config::warmup_tablet_replica_info_cache_ttl_sec) {
600
3
                    replicas.push_back(JobReplicaInfo {job_id, it->second.second});
601
3
                    VLOG_DEBUG << "get_replica_info: cache hit, tablet_id=" << tablet_id
602
0
                               << ", job_id=" << job_id;
603
3
                    cache_hit = true;
604
3
                    continue;
605
3
                } else {
606
0
                    VLOG_DEBUG << "get_replica_info: cache expired, tablet_id=" << tablet_id
607
0
                               << ", job_id=" << job_id;
608
0
                    cache.erase(it);
609
0
                }
610
3
            }
611
0
            VLOG_DEBUG << "get_replica_info: cache miss, tablet_id=" << tablet_id
612
0
                       << ", job_id=" << job_id;
613
0
        }
614
615
0
        if (!cache_hit) {
616
            // We are trying to save one retry by refresh all the remaining caches
617
0
            bypass_cache = true;
618
0
        }
619
0
        ClusterInfo* cluster_info = ExecEnv::GetInstance()->cluster_info();
620
0
        if (cluster_info == nullptr) {
621
0
            LOG(WARNING) << "get_replica_info: have not get FE Master heartbeat yet, job_id="
622
0
                         << job_id;
623
0
            continue;
624
0
        }
625
0
        TNetworkAddress master_addr = cluster_info->master_fe_addr;
626
0
        if (master_addr.hostname == "" || master_addr.port == 0) {
627
0
            LOG(WARNING) << "get_replica_info: have not get FE Master heartbeat yet, job_id="
628
0
                         << job_id;
629
0
            continue;
630
0
        }
631
632
0
        TGetTabletReplicaInfosRequest request;
633
0
        TGetTabletReplicaInfosResult result;
634
0
        request.warm_up_job_id = job_id;
635
0
        request.__isset.warm_up_job_id = true;
636
0
        request.tablet_ids.emplace_back(tablet_id);
637
0
        Status rpc_st = ThriftRpcHelper::rpc<FrontendServiceClient>(
638
0
                master_addr.hostname, master_addr.port,
639
0
                [&request, &result](FrontendServiceConnection& client) {
640
0
                    client->getTabletReplicaInfos(result, request);
641
0
                });
642
643
0
        if (!rpc_st.ok()) {
644
0
            LOG(WARNING) << "get_replica_info: rpc failed error=" << rpc_st
645
0
                         << ", tablet id=" << tablet_id << ", job_id=" << job_id;
646
0
            continue;
647
0
        }
648
649
0
        auto st = Status::create<false>(result.status);
650
0
        if (!st.ok()) {
651
0
            if (st.is<ErrorCode::CANCELLED>()) {
652
0
                LOG(INFO) << "get_replica_info: warm up job cancelled, tablet_id=" << tablet_id
653
0
                          << ", job_id=" << job_id;
654
0
                cancelled_jobs.push_back(job_id);
655
0
            } else {
656
0
                LOG(WARNING) << "get_replica_info: failed status=" << st
657
0
                             << ", tablet id=" << tablet_id << ", job_id=" << job_id;
658
0
            }
659
0
            continue;
660
0
        }
661
0
        VLOG_DEBUG << "get_replica_info: got " << result.tablet_replica_infos.size()
662
0
                   << " tablets, tablet id=" << tablet_id << ", job_id=" << job_id;
663
664
0
        for (const auto& it : result.tablet_replica_infos) {
665
0
            auto tid = it.first;
666
0
            VLOG_DEBUG << "get_replica_info: got " << it.second.size()
667
0
                       << " replica_infos, tablet id=" << tid << ", job_id=" << job_id;
668
0
            for (const auto& replica : it.second) {
669
0
                cache[tid] = std::make_pair(std::chrono::steady_clock::now(), replica);
670
0
                replicas.push_back(JobReplicaInfo {job_id, replica});
671
0
                LOG(INFO) << "get_replica_info: cache add, tablet_id=" << tid
672
0
                          << ", job_id=" << job_id;
673
0
            }
674
0
        }
675
0
    }
676
78.8k
    for (auto job_id : cancelled_jobs) {
677
0
        LOG(INFO) << "get_replica_info: erasing cancelled job, job_id=" << job_id;
678
        // Lazy cleanup path: FE reported the warm up job as CANCELLED, so the job is
679
        // no longer held in memory. Keep the job-count metric and the event filter
680
        // consistent with the explicit CLEAR_JOB path in set_event().
681
0
        if (_tablet_replica_cache.erase(job_id) > 0) {
682
0
            g_file_cache_warm_up_job_num << -1;
683
0
        }
684
0
        _event_driven_filters.erase(job_id);
685
0
    }
686
18.4E
    VLOG_DEBUG << "get_replica_info: return " << replicas.size()
687
18.4E
               << " replicas, tablet id=" << tablet_id;
688
78.8k
    return replicas;
689
78.8k
}
690
691
void CloudWarmUpManager::warm_up_rowset(RowsetMeta& rs_meta, int64_t table_id,
692
73.7k
                                        int64_t sync_wait_timeout_ms) {
693
73.7k
    if (sync_wait_timeout_ms <= 0) {
694
73.7k
        auto rs_meta_pb = std::make_shared<RowsetMetaPB>(rs_meta.get_rowset_pb());
695
73.7k
        auto st = _thread_pool_token->submit_func([this, rs_meta_pb, table_id,
696
73.8k
                                                   sync_wait_timeout_ms]() {
697
73.8k
            RowsetMeta async_rs_meta;
698
73.8k
            bool init_succeed = async_rs_meta.init_from_pb(*rs_meta_pb);
699
73.8k
            TEST_SYNC_POINT_CALLBACK("CloudWarmUpManager::warm_up_rowset.async_init_from_pb",
700
73.8k
                                     &init_succeed);
701
73.8k
            if (!init_succeed) {
702
1
                LOG(WARNING) << "Failed to init rowset meta when warming up rowset asynchronously";
703
1
                return;
704
1
            }
705
73.8k
            _warm_up_rowset(async_rs_meta, table_id, sync_wait_timeout_ms);
706
73.8k
        });
707
73.7k
        if (!st.ok()) {
708
0
            LOG(WARNING) << "Failed to submit warm up rowset task: " << st;
709
0
            file_cache_warm_up_failed_task_num << 1;
710
0
        }
711
73.7k
        return;
712
73.7k
    }
713
714
18.4E
    bthread::Mutex mu;
715
18.4E
    bthread::ConditionVariable cv;
716
18.4E
    bool finished = false;
717
18.4E
    std::unique_lock<bthread::Mutex> lock(mu);
718
18.4E
    auto st = _thread_pool_token->submit_func([&, this]() {
719
1
        _warm_up_rowset(rs_meta, table_id, sync_wait_timeout_ms);
720
1
        std::unique_lock<bthread::Mutex> l(mu);
721
1
        finished = true;
722
1
        cv.notify_one();
723
1
    });
724
18.4E
    if (!st.ok()) {
725
0
        LOG(WARNING) << "Failed to submit warm up rowset task: " << st;
726
0
        file_cache_warm_up_failed_task_num << 1;
727
18.4E
    } else {
728
18.4E
        while (!finished) {
729
2
            TEST_SYNC_POINT_CALLBACK("CloudWarmUpManager::warm_up_rowset.before_wait", &cv);
730
2
            cv.wait(lock);
731
2
        }
732
18.4E
    }
733
18.4E
}
734
735
void CloudWarmUpManager::_warm_up_rowset(RowsetMeta& rs_meta, int64_t table_id,
736
73.2k
                                         int64_t sync_wait_timeout_ms) {
737
73.2k
    TEST_SYNC_POINT_CALLBACK("CloudWarmUpManager::_warm_up_rowset.enter", &rs_meta,
738
73.2k
                             &sync_wait_timeout_ms);
739
73.2k
    bool cache_hit = false;
740
73.2k
    auto replicas = get_replica_info(rs_meta.tablet_id(), table_id, false, cache_hit);
741
73.7k
    if (replicas.empty()) {
742
73.7k
        VLOG_DEBUG << "There is no need to warmup tablet=" << rs_meta.tablet_id()
743
49
                   << ", skipping rowset=" << rs_meta.rowset_id().to_string();
744
73.7k
        g_file_cache_event_driven_warm_up_skipped_rowset_num << 1;
745
73.7k
        return;
746
73.7k
    }
747
18.4E
    Status st = _do_warm_up_rowset(rs_meta, table_id, replicas, sync_wait_timeout_ms, !cache_hit);
748
18.4E
    if (cache_hit && !st.ok() && st.is<ErrorCode::TABLE_NOT_FOUND>()) {
749
0
        replicas = get_replica_info(rs_meta.tablet_id(), table_id, true, cache_hit);
750
0
        st = _do_warm_up_rowset(rs_meta, table_id, replicas, sync_wait_timeout_ms, true);
751
0
    }
752
18.4E
    if (!st.ok()) {
753
0
        LOG(WARNING) << "Failed to warm up rowset, tablet_id=" << rs_meta.tablet_id()
754
0
                     << ", rowset_id=" << rs_meta.rowset_id().to_string() << ", status=" << st;
755
0
    }
756
18.4E
}
757
758
Status CloudWarmUpManager::_build_warm_up_rowset_result(
759
        const std::vector<WarmUpRowsetFailure>& failures, size_t replica_count, int64_t tablet_id,
760
3
        int64_t table_id, const std::string& rowset_id) {
761
3
    if (failures.empty()) {
762
1
        return Status::OK();
763
1
    }
764
765
2
    int code = failures.front().code;
766
2
    std::string failure_msg;
767
6
    for (size_t i = 0; i < failures.size(); ++i) {
768
4
        if (failures[i].code == ErrorCode::TABLE_NOT_FOUND) {
769
1
            code = ErrorCode::TABLE_NOT_FOUND;
770
1
        }
771
4
        if (i > 0) {
772
2
            failure_msg.append("; ");
773
2
        }
774
4
        failure_msg.append(failures[i].reason);
775
4
    }
776
777
2
    return Status::Error(code,
778
2
                         "warm up rowset failed on {}/{} replicas, tablet_id={}, table_id={}, "
779
2
                         "rowset_id={}, failures=[{}]",
780
2
                         failures.size(), replica_count, tablet_id, table_id, rowset_id,
781
2
                         failure_msg);
782
3
}
783
784
Status CloudWarmUpManager::_do_warm_up_rowset(RowsetMeta& rs_meta, int64_t table_id,
785
                                              std::vector<JobReplicaInfo>& replicas,
786
                                              int64_t sync_wait_timeout_ms,
787
0
                                              bool skip_existence_check) {
788
0
    auto tablet_id = rs_meta.tablet_id();
789
0
    int64_t now_ts = std::chrono::duration_cast<std::chrono::microseconds>(
790
0
                             std::chrono::system_clock::now().time_since_epoch())
791
0
                             .count();
792
0
    g_file_cache_warm_up_rowset_last_call_unix_ts.set_value(now_ts);
793
0
    std::vector<WarmUpRowsetFailure> failures;
794
0
    auto add_failure = [&failures](const JobReplicaInfo& info, const std::string& target,
795
0
                                   const Status& st) {
796
0
        failures.push_back(WarmUpRowsetFailure {
797
0
                .code = st.code(),
798
0
                .reason = "job_id=" + std::to_string(info.job_id) +
799
0
                          ", backend_id=" + std::to_string(info.replica.backend_id) +
800
0
                          ", target=" + target + ", status=" + st.to_string_no_stack()});
801
0
    };
802
803
0
    for (auto& info : replicas) {
804
0
        std::string job_id_str = std::to_string(info.job_id);
805
0
        std::string target = get_host_port(info.replica.host, info.replica.brpc_port);
806
0
        int64_t trigger_ts_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
807
0
                                        std::chrono::system_clock::now().time_since_epoch())
808
0
                                        .count();
809
810
0
        PWarmUpRowsetRequest request;
811
0
        request.add_rowset_metas()->CopyFrom(rs_meta.get_rowset_pb());
812
0
        request.set_unix_ts_us(now_ts);
813
0
        request.set_sync_wait_timeout_ms(sync_wait_timeout_ms);
814
0
        request.set_skip_existence_check(skip_existence_check);
815
0
        request.set_job_id(info.job_id);
816
0
        request.set_upstream_trigger_ts_ms(trigger_ts_ms);
817
818
        // send sync request
819
0
        std::string host = info.replica.host;
820
0
        auto dns_cache = ExecEnv::GetInstance()->dns_cache();
821
0
        if (dns_cache == nullptr) {
822
0
            LOG(WARNING) << "DNS cache is not initialized, skipping hostname resolve";
823
0
        } else if (!is_valid_ip(info.replica.host)) {
824
0
            Status status = dns_cache->get(info.replica.host, &host);
825
0
            if (!status.ok()) {
826
0
                LOG(WARNING) << "failed to get ip from host " << info.replica.host << ": "
827
0
                             << status.to_string();
828
0
                add_failure(info, target, status);
829
0
                continue;
830
0
            }
831
0
        }
832
0
        std::string brpc_addr = get_host_port(host, info.replica.brpc_port);
833
0
        Status st = Status::OK();
834
0
        std::shared_ptr<PBackendService_Stub> brpc_stub =
835
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->get_new_client_no_cache(
836
0
                        brpc_addr);
837
0
        if (!brpc_stub) {
838
0
            st = Status::RpcError("Address {} is wrong", brpc_addr);
839
0
            add_failure(info, target, st);
840
0
            continue;
841
0
        }
842
843
        // update metrics
844
0
        auto schema_ptr = rs_meta.tablet_schema();
845
0
        auto idx_version = schema_ptr->get_inverted_index_storage_format();
846
0
        for (int64_t segment_id = 0; segment_id < rs_meta.num_segments(); segment_id++) {
847
0
            auto seg_size = rs_meta.segment_file_size(cast_set<int>(segment_id));
848
849
0
            g_file_cache_event_driven_warm_up_requested_segment_num << 1;
850
0
            g_warmup_ed_requested_segment_num.put({job_id_str}, 1);
851
852
0
            g_file_cache_event_driven_warm_up_requested_segment_size << seg_size;
853
0
            g_warmup_ed_requested_segment_size.put({job_id_str}, seg_size);
854
855
0
            if (schema_ptr->has_inverted_index() || schema_ptr->has_ann_index()) {
856
0
                if (idx_version == InvertedIndexStorageFormatPB::V1) {
857
0
                    auto&& inverted_index_info =
858
0
                            rs_meta.inverted_index_file_info(cast_set<int>(segment_id));
859
0
                    if (inverted_index_info.index_info().empty()) {
860
0
                        VLOG_DEBUG << "No index info available for segment " << segment_id;
861
0
                        continue;
862
0
                    }
863
0
                    for (const auto& idx_info : inverted_index_info.index_info()) {
864
0
                        g_file_cache_event_driven_warm_up_requested_index_num << 1;
865
0
                        g_warmup_ed_requested_index_num.put({job_id_str}, 1);
866
867
0
                        if (idx_info.index_file_size() != -1) {
868
0
                            g_file_cache_event_driven_warm_up_requested_index_size
869
0
                                    << idx_info.index_file_size();
870
0
                            g_warmup_ed_requested_index_size.put({job_id_str},
871
0
                                                                 idx_info.index_file_size());
872
0
                        } else {
873
0
                            VLOG_DEBUG << "Invalid index_file_size for segment_id " << segment_id
874
0
                                       << ", index_id " << idx_info.index_id();
875
0
                        }
876
0
                    }
877
0
                } else { // InvertedIndexStorageFormatPB::V2
878
0
                    auto&& inverted_index_info =
879
0
                            rs_meta.inverted_index_file_info(cast_set<int>(segment_id));
880
0
                    g_file_cache_event_driven_warm_up_requested_index_num << 1;
881
0
                    g_warmup_ed_requested_index_num.put({job_id_str}, 1);
882
883
0
                    if (inverted_index_info.has_index_size()) {
884
0
                        g_file_cache_event_driven_warm_up_requested_index_size
885
0
                                << inverted_index_info.index_size();
886
0
                        g_warmup_ed_requested_index_size.put({job_id_str},
887
0
                                                             inverted_index_info.index_size());
888
0
                    } else {
889
0
                        VLOG_DEBUG << "index_size is not set for segment " << segment_id;
890
0
                    }
891
0
                }
892
0
            }
893
0
        }
894
895
        // Update last trigger timestamp
896
0
        auto* trigger_ts =
897
0
                g_warmup_ed_last_trigger_ts.get_stats(std::list<std::string> {job_id_str});
898
0
        if (trigger_ts) {
899
0
            trigger_ts->set_value(trigger_ts_ms);
900
0
        }
901
902
0
        brpc::Controller cntl;
903
0
        if (sync_wait_timeout_ms > 0) {
904
0
            cntl.set_timeout_ms(sync_wait_timeout_ms + 1000);
905
0
        }
906
0
        PWarmUpRowsetResponse response;
907
0
        MonotonicStopWatch watch;
908
0
        watch.start();
909
0
        brpc_stub->warm_up_rowset(&cntl, &request, &response, nullptr);
910
0
        if (cntl.Failed()) {
911
0
            LOG_WARNING("warm up rowset {} for tablet {} failed, rpc error: {}",
912
0
                        rs_meta.rowset_id().to_string(), tablet_id, cntl.ErrorText());
913
0
            add_failure(info, target, Status::RpcError(cntl.ErrorText()));
914
0
            continue;
915
0
        }
916
0
        if (sync_wait_timeout_ms > 0) {
917
0
            auto cost_us = watch.elapsed_time_microseconds();
918
0
            VLOG_DEBUG << "warm up rowset wait for compaction: " << cost_us << " us";
919
0
            if (cost_us / 1000 > sync_wait_timeout_ms) {
920
0
                LOG_WARNING(
921
0
                        "Warm up rowset {} for tabelt {} wait for compaction timeout, takes {} ms",
922
0
                        rs_meta.rowset_id().to_string(), tablet_id, cost_us / 1000);
923
0
            }
924
0
            g_file_cache_warm_up_rowset_wait_for_compaction_latency << cost_us;
925
0
        }
926
0
        auto status = Status::create<false>(response.status());
927
0
        if (response.has_status() && !status.ok()) {
928
0
            LOG(INFO) << "warm_up_rowset failed, tablet_id=" << rs_meta.tablet_id()
929
0
                      << ", rowset_id=" << rs_meta.rowset_id().to_string()
930
0
                      << ", target=" << info.replica.host << ", skip_existence_check"
931
0
                      << skip_existence_check << ", status=" << status;
932
0
            add_failure(info, target, status);
933
0
        }
934
0
    }
935
0
    return _build_warm_up_rowset_result(failures, replicas.size(), tablet_id, table_id,
936
0
                                        rs_meta.rowset_id().to_string());
937
0
}
938
939
void CloudWarmUpManager::recycle_cache(int64_t tablet_id,
940
5.35k
                                       const std::vector<RecycledRowsets>& rowsets) {
941
5.35k
    bthread::Mutex mu;
942
5.35k
    bthread::ConditionVariable cv;
943
5.35k
    std::unique_lock<bthread::Mutex> lock(mu);
944
5.35k
    auto st = _thread_pool_token->submit_func([&, this]() {
945
5.35k
        std::unique_lock<bthread::Mutex> l(mu);
946
5.35k
        _recycle_cache(tablet_id, rowsets);
947
5.35k
        cv.notify_one();
948
5.35k
    });
949
5.35k
    if (!st.ok()) {
950
0
        LOG(WARNING) << "Failed to submit recycle cache task, tablet_id=" << tablet_id
951
0
                     << ", error=" << st;
952
5.35k
    } else {
953
5.35k
        cv.wait(lock);
954
5.35k
    }
955
5.35k
}
956
957
void CloudWarmUpManager::_recycle_cache(int64_t tablet_id,
958
5.35k
                                        const std::vector<RecycledRowsets>& rowsets) {
959
5.35k
    LOG(INFO) << "recycle_cache: tablet_id=" << tablet_id << ", num_rowsets=" << rowsets.size();
960
5.35k
    bool cache_hit = false;
961
5.35k
    auto replicas = get_replica_info(tablet_id, /*table_id=*/0, false, cache_hit);
962
5.35k
    if (replicas.empty()) {
963
5.35k
        return;
964
5.35k
    }
965
966
0
    PRecycleCacheRequest request;
967
0
    for (const auto& rowset : rowsets) {
968
0
        RecycleCacheMeta* meta = request.add_cache_metas();
969
0
        meta->set_tablet_id(tablet_id);
970
0
        meta->set_rowset_id(rowset.rowset_id.to_string());
971
0
        meta->set_num_segments(rowset.num_segments);
972
0
        for (const auto& name : rowset.index_file_names) {
973
0
            meta->add_index_file_names(name);
974
0
        }
975
0
        g_file_cache_recycle_cache_requested_segment_num << rowset.num_segments;
976
0
        g_file_cache_recycle_cache_requested_index_num << rowset.index_file_names.size();
977
0
    }
978
0
    auto dns_cache = ExecEnv::GetInstance()->dns_cache();
979
0
    for (auto& replica : replicas) {
980
        // send sync request
981
0
        std::string host = replica.replica.host;
982
0
        if (dns_cache == nullptr) {
983
0
            LOG(WARNING) << "DNS cache is not initialized, skipping hostname resolve";
984
0
        } else if (!is_valid_ip(replica.replica.host)) {
985
0
            Status status = dns_cache->get(replica.replica.host, &host);
986
0
            if (!status.ok()) {
987
0
                LOG(WARNING) << "failed to get ip from host " << replica.replica.host << ": "
988
0
                             << status.to_string();
989
0
                return;
990
0
            }
991
0
        }
992
0
        std::string brpc_addr = get_host_port(host, replica.replica.brpc_port);
993
0
        Status st = Status::OK();
994
0
        std::shared_ptr<PBackendService_Stub> brpc_stub =
995
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->get_new_client_no_cache(
996
0
                        brpc_addr);
997
0
        if (!brpc_stub) {
998
0
            st = Status::RpcError("Address {} is wrong", brpc_addr);
999
0
            continue;
1000
0
        }
1001
0
        brpc::Controller cntl;
1002
0
        PRecycleCacheResponse response;
1003
0
        brpc_stub->recycle_cache(&cntl, &request, &response, nullptr);
1004
0
    }
1005
0
}
1006
1007
// Balance warm up cache management methods implementation
1008
void CloudWarmUpManager::record_balanced_tablet(int64_t tablet_id, const std::string& host,
1009
                                                int32_t brpc_port,
1010
55
                                                const std::string& compute_group_id) {
1011
55
    int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1012
55
                             std::chrono::system_clock::now().time_since_epoch())
1013
55
                             .count();
1014
1015
55
    PeerCandidate candidate;
1016
55
    candidate.host = host;
1017
55
    candidate.brpc_port = brpc_port;
1018
55
    candidate.compute_group_id = compute_group_id;
1019
55
    candidate.last_access_time_ms = now_ms;
1020
55
    candidate.consecutive_rpc_failures = 0;
1021
1022
55
    auto& shard = get_shard(tablet_id);
1023
55
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1024
1025
55
    auto [it, inserted] = shard.tablets.try_emplace(tablet_id);
1026
55
    if (inserted) {
1027
        // Only increment the gauge counter on first insertion.
1028
38
        g_balance_tablet_be_mapping_size << 1;
1029
38
    }
1030
1031
55
    auto& cands = it->second.candidates;
1032
    // Warmup rebalance: a tablet has at most one warm-up peer (the current rebalance source).
1033
    // Upsert: replace existing same-CG entry if present, otherwise prepend.
1034
55
    auto same_cg_it = std::find_if(cands.begin(), cands.end(), [&](const PeerCandidate& c) {
1035
19
        return c.compute_group_id == compute_group_id;
1036
19
    });
1037
1038
55
    if (same_cg_it != cands.end()) {
1039
        // Update in-place, preserve position (already at or near front from prior insert).
1040
2
        same_cg_it->host = std::move(candidate.host);
1041
2
        same_cg_it->brpc_port = candidate.brpc_port;
1042
2
        same_cg_it->last_access_time_ms = candidate.last_access_time_ms;
1043
2
        same_cg_it->consecutive_rpc_failures = 0;
1044
53
    } else {
1045
        // New CG entry: insert at front (warmup has highest priority).
1046
53
        cands.insert(cands.begin(), std::move(candidate));
1047
53
    }
1048
1049
55
    VLOG_DEBUG << "Recorded balanced warm up cache tablet: tablet_id=" << tablet_id
1050
0
               << ", host=" << host << ":" << brpc_port
1051
0
               << ", compute_group_id=" << compute_group_id;
1052
55
}
1053
1054
3
void CloudWarmUpManager::remove_balanced_tablet(int64_t tablet_id) {
1055
3
    auto& shard = get_shard(tablet_id);
1056
3
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1057
3
    auto it = shard.tablets.find(tablet_id);
1058
3
    if (it != shard.tablets.end()) {
1059
2
        shard.tablets.erase(it);
1060
2
        g_balance_tablet_be_mapping_size << -1;
1061
2
        VLOG_DEBUG << "Removed balanced warm up cache tablet by timer, tablet_id=" << tablet_id;
1062
2
    }
1063
3
}
1064
1065
0
void CloudWarmUpManager::remove_balanced_tablets(const std::vector<int64_t>& tablet_ids) {
1066
    // Group tablet_ids by shard to minimize lock contention
1067
0
    std::array<std::vector<int64_t>, SHARD_COUNT> shard_groups;
1068
0
    for (int64_t tablet_id : tablet_ids) {
1069
0
        shard_groups[get_shard_index(tablet_id)].push_back(tablet_id);
1070
0
    }
1071
1072
    // Process each shard
1073
0
    for (size_t i = 0; i < SHARD_COUNT; ++i) {
1074
0
        if (shard_groups[i].empty()) continue;
1075
1076
0
        auto& shard = _balanced_tablets_shards[i];
1077
0
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
1078
0
        for (int64_t tablet_id : shard_groups[i]) {
1079
0
            auto it = shard.tablets.find(tablet_id);
1080
0
            if (it != shard.tablets.end()) {
1081
0
                shard.tablets.erase(it);
1082
0
                g_balance_tablet_be_mapping_size << -1;
1083
0
                VLOG_DEBUG << "Removed balanced warm up cache tablet: tablet_id=" << tablet_id;
1084
0
            }
1085
0
        }
1086
0
    }
1087
0
}
1088
1089
// Cleanup loop: runs on a dedicated pthread, wakes up periodically to evict
1090
// expired peer candidates and empty tablet entries.
1091
57
void CloudWarmUpManager::run_cleanup_loop() {
1092
59
    while (true) {
1093
58
        {
1094
58
            std::unique_lock<std::mutex> lock(_cleanup_mtx);
1095
58
            _cleanup_cond.wait_for(lock,
1096
58
                                   std::chrono::seconds(config::peer_candidate_cleanup_interval_s),
1097
80
                                   [this]() { return _closed; });
1098
58
            if (_closed) break;
1099
58
        }
1100
1101
2
        int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1102
2
                                 std::chrono::system_clock::now().time_since_epoch())
1103
2
                                 .count();
1104
2
        int64_t expiry_ms = config::peer_candidate_expiry_s * 1000LL;
1105
1106
10.2k
        for (auto& shard : _balanced_tablets_shards) {
1107
10.2k
            std::unique_lock<bthread::Mutex> lock(shard.mtx);
1108
10.2k
            auto tablet_it = shard.tablets.begin();
1109
10.2k
            while (tablet_it != shard.tablets.end()) {
1110
0
                auto& tpc = tablet_it->second;
1111
                // Remove expired candidates
1112
0
                auto& cands = tpc.candidates;
1113
0
                size_t cands_before = cands.size();
1114
0
                cands.erase(std::remove_if(cands.begin(), cands.end(),
1115
0
                                           [&](const PeerCandidate& c) {
1116
0
                                               return (now_ms - c.last_access_time_ms) >= expiry_ms;
1117
0
                                           }),
1118
0
                            cands.end());
1119
0
                size_t removed = cands_before - cands.size();
1120
0
                if (removed > 0) {
1121
0
                    g_peer_candidate_expiry_eviction << removed;
1122
0
                }
1123
                // Remove the tablet entry if no candidates remain
1124
0
                if (cands.empty()) {
1125
0
                    tablet_it = shard.tablets.erase(tablet_it);
1126
0
                    g_balance_tablet_be_mapping_size << -1;
1127
0
                } else {
1128
0
                    ++tablet_it;
1129
0
                }
1130
0
            }
1131
10.2k
        }
1132
2
    }
1133
57
}
1134
1135
// fetch_candidates_from_fe: lazy fetch path — appends candidates to the end
1136
// (lower priority than warmup-inserted ones).  Uses singleflight to avoid
1137
// duplicate concurrent RPCs for the same tablet.
1138
1
void CloudWarmUpManager::fetch_candidates_from_fe(int64_t tablet_id) {
1139
    // --- singleflight check ---
1140
1
    {
1141
1
        auto& shard = get_shard(tablet_id);
1142
1
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
1143
1
        auto it = shard.tablets.find(tablet_id);
1144
1
        if (it != shard.tablets.end() && it->second.fetching_from_fe) {
1145
0
            return; // another fetch is already in flight
1146
0
        }
1147
        // Increment gauge when we create a genuinely new tablet entry
1148
1
        if (it == shard.tablets.end()) {
1149
1
            g_balance_tablet_be_mapping_size << 1;
1150
1
        }
1151
        // Mark as fetching (creates entry if not present).
1152
1
        shard.tablets[tablet_id].fetching_from_fe = true;
1153
1
    }
1154
1155
    // Use Defer to absolutely guarantee we reset the fetching flag on return
1156
1
    Defer defer_fetching_reset {[this, tablet_id]() {
1157
1
        auto& shard = get_shard(tablet_id);
1158
1
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
1159
1
        auto it = shard.tablets.find(tablet_id);
1160
1
        if (it != shard.tablets.end()) {
1161
1
            it->second.fetching_from_fe = false;
1162
1
        }
1163
1
    }};
1164
1165
    // --- RPC to FE (without warm_up_job_id) ---
1166
1
    ClusterInfo* cluster_info = ExecEnv::GetInstance()->cluster_info();
1167
1
    if (cluster_info == nullptr) {
1168
0
        LOG(WARNING) << "fetch_candidates_from_fe: have not got FE Master heartbeat yet"
1169
0
                     << ", tablet_id=" << tablet_id;
1170
0
        return;
1171
0
    }
1172
1
    TNetworkAddress master_addr = cluster_info->master_fe_addr;
1173
1
    if (master_addr.hostname.empty() || master_addr.port == 0) {
1174
1
        LOG(WARNING) << "fetch_candidates_from_fe: FE master address unknown"
1175
1
                     << ", tablet_id=" << tablet_id;
1176
1
        return;
1177
1
    }
1178
1179
0
    TGetTabletReplicaInfosRequest request;
1180
0
    TGetTabletReplicaInfosResult result;
1181
    // No warm_up_job_id — lazy fetch path
1182
0
    request.tablet_ids.emplace_back(tablet_id);
1183
1184
0
    g_peer_lazy_fetch_total << 1;
1185
0
    const auto rpc_start = std::chrono::steady_clock::now();
1186
0
    Status rpc_st = ThriftRpcHelper::rpc<FrontendServiceClient>(
1187
0
            master_addr.hostname, master_addr.port,
1188
0
            [&request, &result](FrontendServiceConnection& client) {
1189
0
                client->getTabletReplicaInfos(result, request);
1190
0
            });
1191
0
    g_peer_lazy_fetch_latency << std::chrono::duration_cast<std::chrono::microseconds>(
1192
0
                                         std::chrono::steady_clock::now() - rpc_start)
1193
0
                                         .count();
1194
1195
0
    if (!rpc_st.ok()) {
1196
0
        LOG(WARNING) << "fetch_candidates_from_fe: rpc failed, tablet_id=" << tablet_id
1197
0
                     << ", error=" << rpc_st;
1198
0
        g_peer_lazy_fetch_failed << 1;
1199
0
        return;
1200
0
    }
1201
1202
0
    auto st = Status::create<false>(result.status);
1203
0
    if (!st.ok()) {
1204
0
        LOG(WARNING) << "fetch_candidates_from_fe: FE returned error, tablet_id=" << tablet_id
1205
0
                     << ", status=" << st;
1206
0
        g_peer_lazy_fetch_failed << 1;
1207
0
        return;
1208
0
    }
1209
1210
0
    int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1211
0
                             std::chrono::system_clock::now().time_since_epoch())
1212
0
                             .count();
1213
1214
    // Parse the results OUTSIDE the lock
1215
0
    std::vector<PeerCandidate> new_candidates;
1216
0
    const std::string& self_host = BackendOptions::get_localhost();
1217
0
    const int32_t self_brpc_port = config::brpc_port;
1218
1219
0
    auto it_res = result.tablet_replica_infos.find(tablet_id);
1220
0
    if (it_res != result.tablet_replica_infos.end()) {
1221
0
        const auto& replicas = it_res->second;
1222
        // Pre-allocate memory since we know the upper bound of candidates
1223
0
        new_candidates.reserve(replicas.size());
1224
1225
0
        for (const auto& replica : replicas) {
1226
            // Skip self: a BE must not peer-read from its own file cache
1227
0
            if (replica.host == self_host && replica.brpc_port == self_brpc_port) {
1228
0
                VLOG_DEBUG << "fetch_candidates_from_fe: skipping self candidate " << replica.host
1229
0
                           << ":" << replica.brpc_port << " for tablet_id=" << tablet_id;
1230
0
                continue;
1231
0
            }
1232
1233
0
            PeerCandidate& candidate = new_candidates.emplace_back();
1234
0
            candidate.host = replica.host;
1235
0
            candidate.brpc_port = replica.brpc_port;
1236
0
            if (replica.__isset.cloud_compute_group_id) {
1237
0
                candidate.compute_group_id = replica.cloud_compute_group_id;
1238
0
            }
1239
0
            candidate.last_access_time_ms = now_ms;
1240
0
            candidate.consecutive_rpc_failures = 0;
1241
0
        }
1242
0
    }
1243
1244
0
    g_peer_lazy_fetch_success << 1;
1245
1246
    // --- Merge results back into shard ---
1247
    // Acquire lock only to append to the candidates vector
1248
0
    {
1249
0
        auto& shard = get_shard(tablet_id);
1250
0
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
1251
0
        auto it = shard.tablets.find(tablet_id);
1252
        // Safely check if tablet is still there
1253
0
        if (it != shard.tablets.end()) {
1254
0
            auto& tpc = it->second;
1255
0
            tpc.candidates.insert(tpc.candidates.end(),
1256
0
                                  std::make_move_iterator(new_candidates.begin()),
1257
0
                                  std::make_move_iterator(new_candidates.end()));
1258
0
            LOG(INFO) << "fetch_candidates_from_fe: tablet_id=" << tablet_id << " got "
1259
0
                      << tpc.candidates.size() << " total candidates from FE";
1260
0
            VLOG_DEBUG << "fetch_candidates_from_fe: added " << new_candidates.size()
1261
0
                       << " candidates for tablet_id=" << tablet_id;
1262
0
        }
1263
0
    }
1264
0
}
1265
1266
60
std::vector<PeerCandidate> CloudWarmUpManager::get_peer_candidates(int64_t tablet_id) {
1267
60
    auto& shard = get_shard(tablet_id);
1268
60
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1269
60
    auto it = shard.tablets.find(tablet_id);
1270
60
    if (it == shard.tablets.end()) {
1271
5
        g_peer_candidate_cache_miss << 1;
1272
5
        return {};
1273
5
    }
1274
    // Update last_access_time_ms for all candidates to keep them alive
1275
55
    int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1276
55
                             std::chrono::system_clock::now().time_since_epoch())
1277
55
                             .count();
1278
85
    for (auto& c : it->second.candidates) {
1279
85
        c.last_access_time_ms = now_ms;
1280
85
    }
1281
55
    auto& tpc = it->second;
1282
    // Cooldown check: if this tablet is in cooldown, return empty to skip peer.
1283
55
    if (tpc.cooldown_until_ms > 0 && now_ms < tpc.cooldown_until_ms) {
1284
2
        g_peer_tablet_cooldown_skipped << 1;
1285
2
        return {};
1286
2
    }
1287
    // Cooldown expired — reset for next cycle.
1288
53
    if (tpc.cooldown_until_ms > 0) {
1289
1
        tpc.cooldown_until_ms = 0;
1290
1
        tpc.consecutive_all_miss = 0;
1291
1
    }
1292
53
    auto result = tpc.candidates;
1293
53
    if (result.empty()) {
1294
0
        g_peer_candidate_cache_miss << 1;
1295
53
    } else {
1296
53
        g_peer_candidate_cache_hit << 1;
1297
        // Apply compute group affinity: if a previous read succeeded from a particular
1298
        // compute group, move its candidates to the front so the next read tries it first.
1299
        // stable_partition preserves relative order within each group.
1300
        //
1301
        // Example:
1302
        // Candidates: [A(CG1), B(CG2), C(CG1), D(CG3)]
1303
        // pref = "CG1"
1304
        // After stable_partition: [A(CG1), C(CG1), B(CG2), D(CG3)]
1305
        // (A remains before C, and B remains before D)
1306
53
        if (!tpc.last_successful_compute_group_id.empty()) {
1307
11
            const std::string& pref = tpc.last_successful_compute_group_id;
1308
18
            std::stable_partition(result.begin(), result.end(), [&pref](const PeerCandidate& c) {
1309
18
                return c.compute_group_id == pref;
1310
18
            });
1311
11
        }
1312
53
    }
1313
53
    return result;
1314
55
}
1315
1316
void CloudWarmUpManager::update_peer_candidate_on_success(int64_t tablet_id,
1317
17
                                                          const std::string& compute_group_id) {
1318
17
    auto& shard = get_shard(tablet_id);
1319
17
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1320
17
    auto it = shard.tablets.find(tablet_id);
1321
17
    if (it == shard.tablets.end()) {
1322
1
        return;
1323
1
    }
1324
16
    it->second.last_successful_compute_group_id = compute_group_id;
1325
16
    it->second.consecutive_all_miss = 0;
1326
16
    it->second.cooldown_until_ms = 0;
1327
16
}
1328
1329
void CloudWarmUpManager::update_peer_candidate_on_rpc_failure(int64_t tablet_id,
1330
                                                              const std::string& host,
1331
12
                                                              int32_t brpc_port) {
1332
12
    auto& shard = get_shard(tablet_id);
1333
12
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1334
12
    auto it = shard.tablets.find(tablet_id);
1335
12
    if (it == shard.tablets.end()) {
1336
1
        return;
1337
1
    }
1338
11
    auto& cands = it->second.candidates;
1339
12
    for (auto cit = cands.begin(); cit != cands.end(); ++cit) {
1340
11
        if (cit->host == host && cit->brpc_port == brpc_port) {
1341
10
            ++cit->consecutive_rpc_failures;
1342
10
            if (cit->consecutive_rpc_failures >= config::peer_rpc_failure_eviction_threshold) {
1343
2
                LOG(INFO) << "Evicting peer candidate due to consecutive RPC failures"
1344
2
                          << ", tablet_id=" << tablet_id << ", host=" << host << ":" << brpc_port
1345
2
                          << ", failures=" << cit->consecutive_rpc_failures;
1346
2
                g_peer_rpc_failure_eviction << 1;
1347
2
                cands.erase(cit);
1348
                // If all candidates have been evicted, remove the tablet entry
1349
                // entirely so that the gauge stays accurate.
1350
2
                if (cands.empty()) {
1351
1
                    shard.tablets.erase(it);
1352
1
                    g_balance_tablet_be_mapping_size << -1;
1353
1
                }
1354
2
            }
1355
10
            break;
1356
10
        }
1357
11
    }
1358
11
}
1359
1360
void CloudWarmUpManager::rotate_peer_candidate_on_cache_miss(int64_t tablet_id,
1361
                                                             const std::string& host,
1362
15
                                                             int32_t brpc_port) {
1363
15
    auto& shard = get_shard(tablet_id);
1364
15
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1365
15
    auto it = shard.tablets.find(tablet_id);
1366
15
    if (it == shard.tablets.end()) {
1367
1
        return;
1368
1
    }
1369
14
    auto& cands = it->second.candidates;
1370
16
    auto cit = std::find_if(cands.begin(), cands.end(), [&](const PeerCandidate& c) {
1371
16
        return c.host == host && c.brpc_port == brpc_port;
1372
16
    });
1373
14
    if (cit != cands.end() && std::next(cit) != cands.end()) {
1374
        // Move this candidate to the end so the next read tries a different one.
1375
        // This ensures that if the first N candidates are all cache-miss, the system
1376
        // gradually converges to whichever compute group actually has the data.
1377
        //
1378
        // Example:
1379
        // cands: [B, C, D],  cit points to B (front, cache miss)
1380
        // std::rotate(B, C, end) → [C, D, B]
1381
        // Next read tries C first instead of B.
1382
        //
1383
        // Also clear affinity if the rotated candidate belongs to the currently preferred
1384
        // compute group.  Without this, get_peer_candidates() would stable_partition that
1385
        // CG back to the front on the very next call — completely undoing the rotate.
1386
10
        if (it->second.last_successful_compute_group_id == cit->compute_group_id) {
1387
1
            it->second.last_successful_compute_group_id.clear();
1388
1
        }
1389
10
        std::rotate(cit, std::next(cit), cands.end());
1390
10
    }
1391
    // Always count the metric when the candidate is found, even if it is the
1392
    // last (or only) element where rotation is a no-op.
1393
14
    if (cit != cands.end()) {
1394
13
        g_peer_candidate_rotate << 1;
1395
13
    }
1396
14
}
1397
1398
10
bool CloudWarmUpManager::is_peer_cooldown(int64_t tablet_id) const {
1399
10
    const auto& shard = get_shard(tablet_id);
1400
10
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1401
10
    auto it = shard.tablets.find(tablet_id);
1402
10
    if (it == shard.tablets.end()) {
1403
2
        return false;
1404
2
    }
1405
8
    if (it->second.cooldown_until_ms <= 0) {
1406
3
        return false;
1407
3
    }
1408
5
    int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1409
5
                             std::chrono::system_clock::now().time_since_epoch())
1410
5
                             .count();
1411
5
    return now_ms < it->second.cooldown_until_ms;
1412
8
}
1413
1414
19
void CloudWarmUpManager::record_peer_all_miss(int64_t tablet_id) {
1415
19
    auto& shard = get_shard(tablet_id);
1416
19
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1417
19
    auto it = shard.tablets.find(tablet_id);
1418
19
    if (it == shard.tablets.end()) {
1419
2
        return;
1420
2
    }
1421
17
    auto& tpc = it->second;
1422
17
    tpc.consecutive_all_miss++;
1423
17
    if (tpc.consecutive_all_miss >= config::peer_all_miss_cooldown_threshold) {
1424
4
        int64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
1425
4
                                 std::chrono::system_clock::now().time_since_epoch())
1426
4
                                 .count();
1427
4
        tpc.cooldown_until_ms = now_ms + config::peer_all_miss_cooldown_duration_s * 1000;
1428
4
        g_peer_tablet_cooldown_entered << 1;
1429
4
        LOG(INFO) << "Peer read cooldown entered for tablet_id=" << tablet_id << " after "
1430
4
                  << tpc.consecutive_all_miss << " consecutive all-miss races"
1431
4
                  << ", cooldown_duration_s=" << config::peer_all_miss_cooldown_duration_s;
1432
4
    }
1433
17
}
1434
1435
std::optional<TabletPeerCandidates> CloudWarmUpManager::get_tablet_peer_info(
1436
0
        int64_t tablet_id) const {
1437
0
    const auto& shard = get_shard(tablet_id);
1438
0
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1439
0
    auto it = shard.tablets.find(tablet_id);
1440
0
    if (it == shard.tablets.end()) {
1441
0
        return std::nullopt;
1442
0
    }
1443
0
    return it->second; // copy under lock
1444
0
}
1445
1446
std::vector<std::pair<int64_t, TabletPeerCandidates>> CloudWarmUpManager::get_all_peer_info(
1447
0
        int64_t limit) const {
1448
0
    std::vector<std::pair<int64_t, TabletPeerCandidates>> result;
1449
0
    for (size_t i = 0; i < SHARD_COUNT; ++i) {
1450
0
        const auto& shard = _balanced_tablets_shards[i];
1451
0
        std::unique_lock<bthread::Mutex> lock(shard.mtx);
1452
0
        for (const auto& [tid, tpc] : shard.tablets) {
1453
0
            result.emplace_back(tid, tpc);
1454
0
            if (limit > 0 && static_cast<int64_t>(result.size()) >= limit) {
1455
0
                return result;
1456
0
            }
1457
0
        }
1458
0
    }
1459
0
    return result;
1460
0
}
1461
1462
void CloudWarmUpManager::set_tablet_peer_candidates(int64_t tablet_id,
1463
1
                                                    TabletPeerCandidates candidates) {
1464
1
    auto& shard = get_shard(tablet_id);
1465
1
    std::unique_lock<bthread::Mutex> lock(shard.mtx);
1466
1
    auto [it, inserted] = shard.tablets.insert_or_assign(tablet_id, std::move(candidates));
1467
1
    if (inserted) {
1468
1
        g_balance_tablet_be_mapping_size << 1;
1469
1
    }
1470
1
}
1471
1472
} // namespace doris