Coverage Report

Created: 2026-06-02 11:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/block_file_cache.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
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Interpreters/Cache/FileCache.cpp
19
// and modified by Doris
20
21
#include "io/cache/block_file_cache.h"
22
23
#include <gen_cpp/file_cache.pb.h>
24
25
#include <cstdio>
26
#include <exception>
27
#include <fstream>
28
#include <unordered_set>
29
30
#include "common/status.h"
31
#include "cpp/sync_point.h"
32
#include "runtime/exec_env.h"
33
34
#if defined(__APPLE__)
35
#include <sys/mount.h>
36
#else
37
#include <sys/statfs.h>
38
#endif
39
40
#include <chrono> // IWYU pragma: keep
41
#include <mutex>
42
#include <ranges>
43
44
#include "common/cast_set.h"
45
#include "common/config.h"
46
#include "common/logging.h"
47
#include "core/uint128.h"
48
#include "exec/common/sip_hash.h"
49
#include "io/cache/block_file_cache_ttl_mgr.h"
50
#include "io/cache/file_block.h"
51
#include "io/cache/file_cache_common.h"
52
#include "io/cache/fs_file_cache_storage.h"
53
#include "io/cache/mem_file_cache_storage.h"
54
#include "runtime/runtime_profile.h"
55
#include "util/concurrency_stats.h"
56
#include "util/stack_util.h"
57
#include "util/stopwatch.hpp"
58
#include "util/thread.h"
59
#include "util/time.h"
60
namespace doris::io {
61
62
// Insert a block pointer into one shard while swallowing allocation failures.
63
5.45M
bool NeedUpdateLRUBlocks::insert(FileBlockSPtr block) {
64
5.45M
    if (!block) {
65
1
        return false;
66
1
    }
67
5.45M
    try {
68
5.45M
        auto* raw_ptr = block.get();
69
5.45M
        auto idx = shard_index(raw_ptr);
70
5.45M
        auto& shard = _shards[idx];
71
5.45M
        std::lock_guard lock(shard.mutex);
72
5.45M
        auto [_, inserted] = shard.entries.emplace(raw_ptr, std::move(block));
73
5.45M
        if (inserted) {
74
141k
            _size.fetch_add(1, std::memory_order_relaxed);
75
141k
        }
76
5.45M
        return inserted;
77
5.45M
    } catch (const std::exception& e) {
78
0
        LOG(WARNING) << "Failed to enqueue block for LRU update: " << e.what();
79
0
    } catch (...) {
80
0
        LOG(WARNING) << "Failed to enqueue block for LRU update: unknown error";
81
0
    }
82
0
    return false;
83
5.45M
}
84
85
// Drain up to `limit` unique blocks to the caller, keeping the structure consistent on failures.
86
4.91k
size_t NeedUpdateLRUBlocks::drain(size_t limit, std::vector<FileBlockSPtr>* output) {
87
4.91k
    if (limit == 0 || output == nullptr) {
88
2
        return 0;
89
2
    }
90
4.91k
    size_t drained = 0;
91
4.91k
    try {
92
4.91k
        output->reserve(output->size() + std::min(limit, size()));
93
313k
        for (auto& shard : _shards) {
94
313k
            if (drained >= limit) {
95
1
                break;
96
1
            }
97
313k
            std::lock_guard lock(shard.mutex);
98
313k
            auto it = shard.entries.begin();
99
313k
            size_t shard_drained = 0;
100
453k
            while (it != shard.entries.end() && drained + shard_drained < limit) {
101
139k
                output->emplace_back(std::move(it->second));
102
139k
                it = shard.entries.erase(it);
103
139k
                ++shard_drained;
104
139k
            }
105
313k
            if (shard_drained > 0) {
106
641
                _size.fetch_sub(shard_drained, std::memory_order_relaxed);
107
641
                drained += shard_drained;
108
641
            }
109
313k
        }
110
4.91k
    } catch (const std::exception& e) {
111
0
        LOG(WARNING) << "Failed to drain LRU update blocks: " << e.what();
112
0
    } catch (...) {
113
0
        LOG(WARNING) << "Failed to drain LRU update blocks: unknown error";
114
0
    }
115
4.91k
    return drained;
116
4.91k
}
117
118
// Remove every pending block, guarding against unexpected exceptions.
119
32
void NeedUpdateLRUBlocks::clear() {
120
32
    try {
121
2.04k
        for (auto& shard : _shards) {
122
2.04k
            std::lock_guard lock(shard.mutex);
123
2.04k
            if (!shard.entries.empty()) {
124
2
                auto removed = shard.entries.size();
125
2
                shard.entries.clear();
126
2
                _size.fetch_sub(removed, std::memory_order_relaxed);
127
2
            }
128
2.04k
        }
129
32
    } catch (const std::exception& e) {
130
0
        LOG(WARNING) << "Failed to clear LRU update blocks: " << e.what();
131
0
    } catch (...) {
132
0
        LOG(WARNING) << "Failed to clear LRU update blocks: unknown error";
133
0
    }
134
32
}
135
136
5.45M
size_t NeedUpdateLRUBlocks::shard_index(FileBlock* ptr) const {
137
5.45M
    DCHECK(ptr != nullptr);
138
5.45M
    return std::hash<FileBlock*> {}(ptr)&kShardMask;
139
5.45M
}
140
141
BlockFileCache::BlockFileCache(const std::string& cache_base_path,
142
                               const FileCacheSettings& cache_settings)
143
176
        : _cache_base_path(cache_base_path),
144
176
          _capacity(cache_settings.capacity),
145
176
          _max_file_block_size(cache_settings.max_file_block_size) {
146
176
    _cur_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(_cache_base_path.c_str(),
147
176
                                                                     "file_cache_cache_size", 0);
148
176
    _cache_capacity_metrics = std::make_shared<bvar::Status<size_t>>(
149
176
            _cache_base_path.c_str(), "file_cache_capacity", _capacity);
150
176
    _cur_ttl_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
151
176
            _cache_base_path.c_str(), "file_cache_ttl_cache_size", 0);
152
176
    _cur_normal_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
153
176
            _cache_base_path.c_str(), "file_cache_normal_queue_element_count", 0);
154
176
    _cur_ttl_cache_lru_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
155
176
            _cache_base_path.c_str(), "file_cache_ttl_cache_lru_queue_size", 0);
156
176
    _cur_ttl_cache_lru_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
157
176
            _cache_base_path.c_str(), "file_cache_ttl_cache_lru_queue_element_count", 0);
158
176
    _cur_normal_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
159
176
            _cache_base_path.c_str(), "file_cache_normal_queue_cache_size", 0);
160
176
    _cur_index_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
161
176
            _cache_base_path.c_str(), "file_cache_index_queue_element_count", 0);
162
176
    _cur_index_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
163
176
            _cache_base_path.c_str(), "file_cache_index_queue_cache_size", 0);
164
176
    _cur_disposable_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
165
176
            _cache_base_path.c_str(), "file_cache_disposable_queue_element_count", 0);
166
176
    _cur_disposable_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
167
176
            _cache_base_path.c_str(), "file_cache_disposable_queue_cache_size", 0);
168
169
176
    _queue_evict_size_metrics[0] = std::make_shared<bvar::Adder<size_t>>(
170
176
            _cache_base_path.c_str(), "file_cache_index_queue_evict_size");
171
176
    _queue_evict_size_metrics[1] = std::make_shared<bvar::Adder<size_t>>(
172
176
            _cache_base_path.c_str(), "file_cache_normal_queue_evict_size");
173
176
    _queue_evict_size_metrics[2] = std::make_shared<bvar::Adder<size_t>>(
174
176
            _cache_base_path.c_str(), "file_cache_disposable_queue_evict_size");
175
176
    _queue_evict_size_metrics[3] = std::make_shared<bvar::Adder<size_t>>(
176
176
            _cache_base_path.c_str(), "file_cache_ttl_cache_evict_size");
177
176
    _total_evict_size_metrics = std::make_shared<bvar::Adder<size_t>>(
178
176
            _cache_base_path.c_str(), "file_cache_total_evict_size");
179
176
    _total_read_size_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
180
176
                                                                     "file_cache_total_read_size");
181
176
    _total_hit_size_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
182
176
                                                                    "file_cache_total_hit_size");
183
176
    _gc_evict_bytes_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
184
176
                                                                    "file_cache_gc_evict_bytes");
185
176
    _gc_evict_count_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
186
176
                                                                    "file_cache_gc_evict_count");
187
188
176
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::NORMAL] =
189
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
190
176
                                                  "file_cache_evict_by_time_disposable_to_normal");
191
176
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::INDEX] =
192
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
193
176
                                                  "file_cache_evict_by_time_disposable_to_index");
194
176
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::TTL] =
195
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
196
176
                                                  "file_cache_evict_by_time_disposable_to_ttl");
197
176
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::DISPOSABLE] =
198
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
199
176
                                                  "file_cache_evict_by_time_normal_to_disposable");
200
176
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::INDEX] =
201
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
202
176
                                                  "file_cache_evict_by_time_normal_to_index");
203
176
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::TTL] =
204
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
205
176
                                                  "file_cache_evict_by_time_normal_to_ttl");
206
176
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::DISPOSABLE] =
207
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
208
176
                                                  "file_cache_evict_by_time_index_to_disposable");
209
176
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::NORMAL] =
210
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
211
176
                                                  "file_cache_evict_by_time_index_to_normal");
212
176
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::TTL] =
213
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
214
176
                                                  "file_cache_evict_by_time_index_to_ttl");
215
176
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::DISPOSABLE] =
216
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
217
176
                                                  "file_cache_evict_by_time_ttl_to_disposable");
218
176
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::NORMAL] =
219
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
220
176
                                                  "file_cache_evict_by_time_ttl_to_normal");
221
176
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::INDEX] =
222
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
223
176
                                                  "file_cache_evict_by_time_ttl_to_index");
224
225
176
    _evict_by_self_lru_metrics_matrix[FileCacheType::DISPOSABLE] =
226
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
227
176
                                                  "file_cache_evict_by_self_lru_disposable");
228
176
    _evict_by_self_lru_metrics_matrix[FileCacheType::NORMAL] =
229
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
230
176
                                                  "file_cache_evict_by_self_lru_normal");
231
176
    _evict_by_self_lru_metrics_matrix[FileCacheType::INDEX] = std::make_shared<bvar::Adder<size_t>>(
232
176
            _cache_base_path.c_str(), "file_cache_evict_by_self_lru_index");
233
176
    _evict_by_self_lru_metrics_matrix[FileCacheType::TTL] = std::make_shared<bvar::Adder<size_t>>(
234
176
            _cache_base_path.c_str(), "file_cache_evict_by_self_lru_ttl");
235
236
176
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::NORMAL] =
237
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
238
176
                                                  "file_cache_evict_by_size_disposable_to_normal");
239
176
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::INDEX] =
240
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
241
176
                                                  "file_cache_evict_by_size_disposable_to_index");
242
176
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::TTL] =
243
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
244
176
                                                  "file_cache_evict_by_size_disposable_to_ttl");
245
176
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::DISPOSABLE] =
246
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
247
176
                                                  "file_cache_evict_by_size_normal_to_disposable");
248
176
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::INDEX] =
249
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
250
176
                                                  "file_cache_evict_by_size_normal_to_index");
251
176
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::TTL] =
252
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
253
176
                                                  "file_cache_evict_by_size_normal_to_ttl");
254
176
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::DISPOSABLE] =
255
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
256
176
                                                  "file_cache_evict_by_size_index_to_disposable");
257
176
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::NORMAL] =
258
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
259
176
                                                  "file_cache_evict_by_size_index_to_normal");
260
176
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::TTL] =
261
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
262
176
                                                  "file_cache_evict_by_size_index_to_ttl");
263
176
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::DISPOSABLE] =
264
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
265
176
                                                  "file_cache_evict_by_size_ttl_to_disposable");
266
176
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::NORMAL] =
267
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
268
176
                                                  "file_cache_evict_by_size_ttl_to_normal");
269
176
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::INDEX] =
270
176
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
271
176
                                                  "file_cache_evict_by_size_ttl_to_index");
272
273
176
    _evict_by_try_release = std::make_shared<bvar::Adder<size_t>>(
274
176
            _cache_base_path.c_str(), "file_cache_evict_by_try_release");
275
276
176
    _num_read_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
277
176
                                                             "file_cache_num_read_blocks");
278
176
    _num_hit_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
279
176
                                                            "file_cache_num_hit_blocks");
280
176
    _num_removed_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
281
176
                                                                "file_cache_num_removed_blocks");
282
283
176
    _no_warmup_num_read_blocks = std::make_shared<bvar::Adder<size_t>>(
284
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks");
285
176
    _no_warmup_num_hit_blocks = std::make_shared<bvar::Adder<size_t>>(
286
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks");
287
288
176
#ifndef BE_TEST
289
176
    _num_hit_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
290
176
            _cache_base_path.c_str(), "file_cache_num_hit_blocks_5m", _num_hit_blocks.get(), 300);
291
176
    _num_read_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
292
176
            _cache_base_path.c_str(), "file_cache_num_read_blocks_5m", _num_read_blocks.get(), 300);
293
176
    _num_hit_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
294
176
            _cache_base_path.c_str(), "file_cache_num_hit_blocks_1h", _num_hit_blocks.get(), 3600);
295
176
    _num_read_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
296
176
            _cache_base_path.c_str(), "file_cache_num_read_blocks_1h", _num_read_blocks.get(),
297
176
            3600);
298
176
    _no_warmup_num_hit_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
299
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks_5m",
300
176
            _no_warmup_num_hit_blocks.get(), 300);
301
176
    _no_warmup_num_read_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
302
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks_5m",
303
176
            _no_warmup_num_read_blocks.get(), 300);
304
176
    _no_warmup_num_hit_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
305
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks_1h",
306
176
            _no_warmup_num_hit_blocks.get(), 3600);
307
176
    _no_warmup_num_read_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
308
176
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks_1h",
309
176
            _no_warmup_num_read_blocks.get(), 3600);
310
176
#endif
311
312
176
    _hit_ratio = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
313
176
                                                        "file_cache_hit_ratio", 0.0);
314
176
    _hit_ratio_5m = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
315
176
                                                           "file_cache_hit_ratio_5m", 0.0);
316
176
    _hit_ratio_1h = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
317
176
                                                           "file_cache_hit_ratio_1h", 0.0);
318
319
176
    _no_warmup_hit_ratio = std::make_shared<bvar::Status<double>>(
320
176
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio", 0.0);
321
176
    _no_warmup_hit_ratio_5m = std::make_shared<bvar::Status<double>>(
322
176
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio_5m", 0.0);
323
176
    _no_warmup_hit_ratio_1h = std::make_shared<bvar::Status<double>>(
324
176
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio_1h", 0.0);
325
326
176
    _disk_limit_mode_metrics = std::make_shared<bvar::Status<size_t>>(
327
176
            _cache_base_path.c_str(), "file_cache_disk_limit_mode", 0);
328
176
    _need_evict_cache_in_advance_metrics = std::make_shared<bvar::Status<size_t>>(
329
176
            _cache_base_path.c_str(), "file_cache_need_evict_cache_in_advance", 0);
330
176
    _meta_store_write_queue_size_metrics = std::make_shared<bvar::Status<size_t>>(
331
176
            _cache_base_path.c_str(), "file_cache_meta_store_write_queue_size", 0);
332
333
176
    _cache_lock_wait_time_us = std::make_shared<bvar::LatencyRecorder>(
334
176
            _cache_base_path.c_str(), "file_cache_cache_lock_wait_time_us");
335
176
    _get_or_set_latency_us = std::make_shared<bvar::LatencyRecorder>(
336
176
            _cache_base_path.c_str(), "file_cache_get_or_set_latency_us");
337
176
    _storage_sync_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
338
176
            _cache_base_path.c_str(), "file_cache_storage_sync_remove_latency_us");
339
176
    _storage_retry_sync_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
340
176
            _cache_base_path.c_str(), "file_cache_storage_retry_sync_remove_latency_us");
341
176
    _storage_async_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
342
176
            _cache_base_path.c_str(), "file_cache_storage_async_remove_latency_us");
343
176
    _evict_in_advance_latency_us = std::make_shared<bvar::LatencyRecorder>(
344
176
            _cache_base_path.c_str(), "file_cache_evict_in_advance_latency_us");
345
176
    _lru_dump_latency_us = std::make_shared<bvar::LatencyRecorder>(
346
176
            _cache_base_path.c_str(), "file_cache_lru_dump_latency_us");
347
176
    _recycle_keys_length_recorder = std::make_shared<bvar::LatencyRecorder>(
348
176
            _cache_base_path.c_str(), "file_cache_recycle_keys_length");
349
176
    _need_update_lru_blocks_length_recorder = std::make_shared<bvar::LatencyRecorder>(
350
176
            _cache_base_path.c_str(), "file_cache_need_update_lru_blocks_length");
351
176
    _update_lru_blocks_latency_us = std::make_shared<bvar::LatencyRecorder>(
352
176
            _cache_base_path.c_str(), "file_cache_update_lru_blocks_latency_us");
353
176
    _ttl_gc_latency_us = std::make_shared<bvar::LatencyRecorder>(_cache_base_path.c_str(),
354
176
                                                                 "file_cache_ttl_gc_latency_us");
355
176
    _shadow_queue_levenshtein_distance = std::make_shared<bvar::LatencyRecorder>(
356
176
            _cache_base_path.c_str(), "file_cache_shadow_queue_levenshtein_distance");
357
358
176
    _disposable_queue = LRUQueue(cache_settings.disposable_queue_size,
359
176
                                 cache_settings.disposable_queue_elements, 60 * 60);
360
176
    _index_queue = LRUQueue(cache_settings.index_queue_size, cache_settings.index_queue_elements,
361
176
                            7 * 24 * 60 * 60);
362
176
    _normal_queue = LRUQueue(cache_settings.query_queue_size, cache_settings.query_queue_elements,
363
176
                             24 * 60 * 60);
364
176
    _ttl_queue = LRUQueue(cache_settings.ttl_queue_size, cache_settings.ttl_queue_elements,
365
176
                          std::numeric_limits<int>::max());
366
367
176
    _lru_recorder = std::make_unique<LRUQueueRecorder>(this);
368
176
    _lru_dumper = std::make_unique<CacheLRUDumper>(this, _lru_recorder.get());
369
176
    if (cache_settings.storage == "memory") {
370
21
        _storage = std::make_unique<MemFileCacheStorage>();
371
21
        _cache_base_path = "memory";
372
155
    } else {
373
155
        _storage = std::make_unique<FSFileCacheStorage>();
374
155
    }
375
376
176
    LOG(INFO) << "file cache path= " << _cache_base_path << " " << cache_settings.to_string();
377
176
}
378
379
475k
UInt128Wrapper BlockFileCache::hash(const std::string& path) {
380
475k
    uint128_t value;
381
475k
    sip_hash128(path.data(), path.size(), reinterpret_cast<char*>(&value));
382
475k
    return UInt128Wrapper(value);
383
475k
}
384
385
BlockFileCache::QueryFileCacheContextHolderPtr BlockFileCache::get_query_context_holder(
386
8
        const TUniqueId& query_id, int file_cache_query_limit_percent) {
387
8
    SCOPED_CACHE_LOCK(_mutex, this);
388
8
    if (!config::enable_file_cache_query_limit) {
389
1
        return {};
390
1
    }
391
392
    /// if enable_filesystem_query_cache_limit is true,
393
    /// we create context query for current query.
394
7
    auto context = get_or_set_query_context(query_id, cache_lock, file_cache_query_limit_percent);
395
7
    return std::make_unique<QueryFileCacheContextHolder>(query_id, this, context);
396
8
}
397
398
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_query_context(
399
21.6k
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock) {
400
21.6k
    auto query_iter = _query_map.find(query_id);
401
21.6k
    return (query_iter == _query_map.end()) ? nullptr : query_iter->second;
402
21.6k
}
403
404
6
void BlockFileCache::remove_query_context(const TUniqueId& query_id) {
405
6
    SCOPED_CACHE_LOCK(_mutex, this);
406
6
    const auto& query_iter = _query_map.find(query_id);
407
408
6
    if (query_iter != _query_map.end() && query_iter->second.use_count() <= 1) {
409
5
        _query_map.erase(query_iter);
410
5
    }
411
6
}
412
413
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_or_set_query_context(
414
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock,
415
7
        int file_cache_query_limit_percent) {
416
7
    if (query_id.lo == 0 && query_id.hi == 0) {
417
1
        return nullptr;
418
1
    }
419
420
6
    auto context = get_query_context(query_id, cache_lock);
421
6
    if (context) {
422
1
        return context;
423
1
    }
424
425
5
    size_t file_cache_query_limit_size = _capacity * file_cache_query_limit_percent / 100;
426
5
    if (file_cache_query_limit_size < 268435456) {
427
5
        LOG(WARNING) << "The user-set file cache query limit (" << file_cache_query_limit_size
428
5
                     << " bytes) is less than the 256MB recommended minimum. "
429
5
                     << "Consider increasing the session variable 'file_cache_query_limit_percent'"
430
5
                     << " from its current value " << file_cache_query_limit_percent << "%.";
431
5
    }
432
5
    auto query_context = std::make_shared<QueryFileCacheContext>(file_cache_query_limit_size);
433
5
    auto query_iter = _query_map.emplace(query_id, query_context).first;
434
5
    return query_iter->second;
435
6
}
436
437
void BlockFileCache::QueryFileCacheContext::remove(const UInt128Wrapper& hash, size_t offset,
438
20
                                                   std::lock_guard<std::mutex>& cache_lock) {
439
20
    auto pair = std::make_pair(hash, offset);
440
20
    auto record = records.find(pair);
441
20
    DCHECK(record != records.end());
442
20
    auto iter = record->second;
443
20
    records.erase(pair);
444
20
    lru_queue.remove(iter, cache_lock);
445
20
}
446
447
void BlockFileCache::QueryFileCacheContext::reserve(const UInt128Wrapper& hash, size_t offset,
448
                                                    size_t size,
449
30
                                                    std::lock_guard<std::mutex>& cache_lock) {
450
30
    auto pair = std::make_pair(hash, offset);
451
30
    if (records.find(pair) == records.end()) {
452
29
        auto queue_iter = lru_queue.add(hash, offset, size, cache_lock);
453
29
        records.insert({pair, queue_iter});
454
29
    }
455
30
}
456
457
153
Status BlockFileCache::initialize() {
458
153
    SCOPED_CACHE_LOCK(_mutex, this);
459
153
    return initialize_unlocked(cache_lock);
460
153
}
461
462
153
Status BlockFileCache::initialize_unlocked(std::lock_guard<std::mutex>& cache_lock) {
463
153
    DCHECK(!_is_initialized);
464
153
    _is_initialized = true;
465
153
    if (config::file_cache_background_lru_dump_tail_record_num > 0) {
466
        // requirements:
467
        // 1. restored data should not overwrite the last dump
468
        // 2. restore should happen before load and async load
469
        // 3. all queues should be restored sequencially to avoid conflict
470
        // TODO(zhengyu): we can parralize them but will increase complexity, so lets check the time cost
471
        // to see if any improvement is a necessary
472
153
        restore_lru_queues_from_disk(cache_lock);
473
153
    }
474
153
    RETURN_IF_ERROR(_storage->init(this));
475
476
153
    if (auto* fs_storage = dynamic_cast<FSFileCacheStorage*>(_storage.get())) {
477
134
        if (auto* meta_store = fs_storage->get_meta_store()) {
478
134
            _ttl_mgr = std::make_unique<BlockFileCacheTtlMgr>(this, meta_store);
479
134
        }
480
134
    }
481
482
153
    _cache_background_monitor_thread = std::thread(&BlockFileCache::run_background_monitor, this);
483
153
    _cache_background_gc_thread = std::thread(&BlockFileCache::run_background_gc, this);
484
153
    _cache_background_evict_in_advance_thread =
485
153
            std::thread(&BlockFileCache::run_background_evict_in_advance, this);
486
153
    _cache_background_block_lru_update_thread =
487
153
            std::thread(&BlockFileCache::run_background_block_lru_update, this);
488
489
    // Initialize LRU dump thread and restore queues
490
153
    _cache_background_lru_dump_thread = std::thread(&BlockFileCache::run_background_lru_dump, this);
491
153
    _cache_background_lru_log_replay_thread =
492
153
            std::thread(&BlockFileCache::run_background_lru_log_replay, this);
493
494
153
    return Status::OK();
495
153
}
496
497
void BlockFileCache::update_block_lru(FileBlockSPtr block,
498
139k
                                      std::lock_guard<std::mutex>& cache_lock) {
499
139k
    if (!block) {
500
1
        return;
501
1
    }
502
503
139k
    FileBlockCell* cell = get_cell(block->get_hash_value(), block->offset(), cache_lock);
504
139k
    if (!cell || cell->file_block.get() != block.get()) {
505
17.5k
        return;
506
17.5k
    }
507
508
121k
    if (cell->queue_iterator) {
509
121k
        auto& queue = get_queue(block->cache_type());
510
121k
        queue.move_to_end(*cell->queue_iterator, cache_lock);
511
121k
        _lru_recorder->record_queue_event(block->cache_type(), CacheLRULogType::MOVETOBACK,
512
121k
                                          block->_key.hash, block->_key.offset,
513
121k
                                          block->_block_range.size());
514
121k
    }
515
121k
    cell->update_atime();
516
121k
}
517
518
void BlockFileCache::use_cell(const FileBlockCell& cell, FileBlocks* result, bool move_iter_flag,
519
737k
                              std::lock_guard<std::mutex>& cache_lock) {
520
737k
    if (result) {
521
737k
        result->push_back(cell.file_block);
522
737k
    }
523
524
737k
    auto& queue = get_queue(cell.file_block->cache_type());
525
    /// Move to the end of the queue. The iterator remains valid.
526
737k
    if (!config::enable_file_cache_async_touch_on_get_or_set && cell.queue_iterator &&
527
737k
        move_iter_flag) {
528
541k
        queue.move_to_end(*cell.queue_iterator, cache_lock);
529
541k
        _lru_recorder->record_queue_event(cell.file_block->cache_type(),
530
541k
                                          CacheLRULogType::MOVETOBACK, cell.file_block->_key.hash,
531
541k
                                          cell.file_block->_key.offset, cell.size());
532
541k
    }
533
534
737k
    cell.update_atime();
535
737k
}
536
537
template <class T>
538
    requires IsXLock<T>
539
FileBlockCell* BlockFileCache::get_cell(const UInt128Wrapper& hash, size_t offset,
540
5.16M
                                        T& /* cache_lock */) {
541
5.16M
    auto it = _files.find(hash);
542
5.16M
    if (it == _files.end()) {
543
3.52k
        return nullptr;
544
3.52k
    }
545
546
5.15M
    auto& offsets = it->second;
547
5.15M
    auto cell_it = offsets.find(offset);
548
5.15M
    if (cell_it == offsets.end()) {
549
528
        return nullptr;
550
528
    }
551
552
5.15M
    return &cell_it->second;
553
5.15M
}
554
555
929k
bool BlockFileCache::need_to_move(FileCacheType cell_type, FileCacheType query_type) const {
556
929k
    return query_type != FileCacheType::DISPOSABLE && cell_type != FileCacheType::DISPOSABLE;
557
929k
}
558
559
FileBlocks BlockFileCache::get_impl(const UInt128Wrapper& hash, const CacheContext& context,
560
                                    const FileBlock::Range& range,
561
875k
                                    std::lock_guard<std::mutex>& cache_lock) {
562
    /// Given range = [left, right] and non-overlapping ordered set of file blocks,
563
    /// find list [block1, ..., blockN] of blocks which intersect with given range.
564
875k
    auto it = _files.find(hash);
565
875k
    if (it == _files.end()) {
566
129k
        if (_async_open_done) {
567
129k
            return {};
568
129k
        }
569
1
        FileCacheKey key;
570
1
        key.hash = hash;
571
1
        key.meta.type = context.cache_type;
572
1
        key.meta.expiration_time = context.expiration_time;
573
1
        key.meta.tablet_id = context.tablet_id;
574
1
        _storage->load_blocks_directly_unlocked(this, key, cache_lock);
575
576
1
        it = _files.find(hash);
577
1
        if (it == _files.end()) [[unlikely]] {
578
1
            return {};
579
1
        }
580
1
    }
581
582
746k
    auto& file_blocks = it->second;
583
746k
    if (file_blocks.empty()) {
584
0
        LOG(WARNING) << "file_blocks is empty for hash=" << hash.to_string()
585
0
                     << " cache type=" << context.cache_type
586
0
                     << " cache expiration time=" << context.expiration_time
587
0
                     << " cache range=" << range.left << " " << range.right
588
0
                     << " query id=" << context.query_id;
589
0
        DCHECK(false);
590
0
        _files.erase(hash);
591
0
        return {};
592
0
    }
593
594
746k
    FileBlocks result;
595
746k
    auto block_it = file_blocks.lower_bound(range.left);
596
746k
    if (block_it == file_blocks.end()) {
597
        /// N - last cached block for given file hash, block{N}.offset < range.left:
598
        ///   block{N}                       block{N}
599
        /// [________                         [_______]
600
        ///     [__________]         OR                  [________]
601
        ///     ^                                        ^
602
        ///     range.left                               range.left
603
604
6.79k
        const auto& cell = file_blocks.rbegin()->second;
605
6.79k
        if (cell.file_block->range().right < range.left) {
606
6.78k
            return {};
607
6.78k
        }
608
609
14
        use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
610
14
                 cache_lock);
611
739k
    } else { /// block_it <-- segmment{k}
612
739k
        if (block_it != file_blocks.begin()) {
613
1.67k
            const auto& prev_cell = std::prev(block_it)->second;
614
1.67k
            const auto& prev_cell_range = prev_cell.file_block->range();
615
616
1.67k
            if (range.left <= prev_cell_range.right) {
617
                ///   block{k-1}  block{k}
618
                ///   [________]   [_____
619
                ///       [___________
620
                ///       ^
621
                ///       range.left
622
623
137
                use_cell(prev_cell, &result,
624
137
                         need_to_move(prev_cell.file_block->cache_type(), context.cache_type),
625
137
                         cache_lock);
626
137
            }
627
1.67k
        }
628
629
        ///  block{k} ...       block{k-1}  block{k}                      block{k}
630
        ///  [______              [______]     [____                        [________
631
        ///  [_________     OR              [________      OR    [______]   ^
632
        ///  ^                              ^                           ^   block{k}.offset
633
        ///  range.left                     range.left                  range.right
634
635
1.47M
        while (block_it != file_blocks.end()) {
636
740k
            const auto& cell = block_it->second;
637
740k
            if (range.right < cell.file_block->range().left) {
638
3.37k
                break;
639
3.37k
            }
640
641
737k
            use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
642
737k
                     cache_lock);
643
737k
            ++block_it;
644
737k
        }
645
739k
    }
646
647
739k
    return result;
648
746k
}
649
650
5.45M
void BlockFileCache::add_need_update_lru_block(FileBlockSPtr block) {
651
5.45M
    if (_need_update_lru_blocks.insert(std::move(block))) {
652
141k
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
653
141k
    }
654
5.45M
}
655
656
3
std::string BlockFileCache::clear_file_cache_async() {
657
3
    LOG(INFO) << "start clear_file_cache_async, path=" << _cache_base_path;
658
3
    _lru_dumper->remove_lru_dump_files();
659
3
    int64_t num_cells_all = 0;
660
3
    int64_t num_cells_to_delete = 0;
661
3
    int64_t num_cells_wait_recycle = 0;
662
3
    int64_t num_files_all = 0;
663
3
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::clear_file_cache_async");
664
3
    {
665
3
        SCOPED_CACHE_LOCK(_mutex, this);
666
667
3
        std::vector<FileBlockCell*> deleting_cells;
668
4
        for (auto& [_, offset_to_cell] : _files) {
669
4
            ++num_files_all;
670
37
            for (auto& [_1, cell] : offset_to_cell) {
671
37
                ++num_cells_all;
672
37
                deleting_cells.push_back(&cell);
673
37
            }
674
4
        }
675
676
        // we cannot delete the element in the loop above, because it will break the iterator
677
37
        for (auto& cell : deleting_cells) {
678
37
            if (!cell->releasable()) {
679
2
                LOG(INFO) << "cell is not releasable, hash="
680
2
                          << " offset=" << cell->file_block->offset();
681
2
                cell->file_block->set_deleting();
682
2
                ++num_cells_wait_recycle;
683
2
                continue;
684
2
            }
685
35
            FileBlockSPtr file_block = cell->file_block;
686
35
            if (file_block) {
687
35
                std::lock_guard block_lock(file_block->_mutex);
688
35
                remove(file_block, cache_lock, block_lock, false);
689
35
                ++num_cells_to_delete;
690
35
            }
691
35
        }
692
3
        clear_need_update_lru_blocks();
693
3
    }
694
695
3
    std::stringstream ss;
696
3
    ss << "finish clear_file_cache_async, path=" << _cache_base_path
697
3
       << " num_files_all=" << num_files_all << " num_cells_all=" << num_cells_all
698
3
       << " num_cells_to_delete=" << num_cells_to_delete
699
3
       << " num_cells_wait_recycle=" << num_cells_wait_recycle;
700
3
    auto msg = ss.str();
701
3
    LOG(INFO) << msg;
702
3
    _lru_dumper->remove_lru_dump_files();
703
3
    return msg;
704
3
}
705
706
FileBlocks BlockFileCache::split_range_into_cells(const UInt128Wrapper& hash,
707
                                                  const CacheContext& context, size_t offset,
708
                                                  size_t size, FileBlock::State state,
709
139k
                                                  std::lock_guard<std::mutex>& cache_lock) {
710
139k
    DCHECK(size > 0);
711
712
139k
    auto current_pos = offset;
713
139k
    auto end_pos_non_included = offset + size;
714
715
139k
    size_t current_size = 0;
716
139k
    size_t remaining_size = size;
717
718
139k
    FileBlocks file_blocks;
719
303k
    while (current_pos < end_pos_non_included) {
720
163k
        current_size = std::min(remaining_size, _max_file_block_size);
721
163k
        remaining_size -= current_size;
722
163k
        state = try_reserve(hash, context, current_pos, current_size, cache_lock)
723
163k
                        ? state
724
163k
                        : FileBlock::State::SKIP_CACHE;
725
163k
        if (state == FileBlock::State::SKIP_CACHE) [[unlikely]] {
726
16.3k
            FileCacheKey key;
727
16.3k
            key.hash = hash;
728
16.3k
            key.offset = current_pos;
729
16.3k
            key.meta.type = context.cache_type;
730
16.3k
            key.meta.expiration_time = context.expiration_time;
731
16.3k
            key.meta.tablet_id = context.tablet_id;
732
16.3k
            auto file_block = std::make_shared<FileBlock>(key, current_size, this,
733
16.3k
                                                          FileBlock::State::SKIP_CACHE);
734
16.3k
            file_blocks.push_back(std::move(file_block));
735
147k
        } else {
736
147k
            auto* cell = add_cell(hash, context, current_pos, current_size, state, cache_lock);
737
147k
            if (cell) {
738
147k
                file_blocks.push_back(cell->file_block);
739
147k
                if (!context.is_cold_data) {
740
147k
                    cell->update_atime();
741
147k
                }
742
147k
            }
743
147k
            if (_ttl_mgr && context.tablet_id != 0) {
744
135k
                _ttl_mgr->register_tablet_id(context.tablet_id);
745
135k
            }
746
147k
        }
747
748
163k
        current_pos += current_size;
749
163k
    }
750
751
139k
    DCHECK(file_blocks.empty() || offset + size - 1 == file_blocks.back()->range().right);
752
139k
    return file_blocks;
753
139k
}
754
755
void BlockFileCache::fill_holes_with_empty_file_blocks(FileBlocks& file_blocks,
756
                                                       const UInt128Wrapper& hash,
757
                                                       const CacheContext& context,
758
                                                       const FileBlock::Range& range,
759
736k
                                                       std::lock_guard<std::mutex>& cache_lock) {
760
    /// There are blocks [block1, ..., blockN]
761
    /// (non-overlapping, non-empty, ascending-ordered) which (maybe partially)
762
    /// intersect with given range.
763
764
    /// It can have holes:
765
    /// [____________________]         -- requested range
766
    ///     [____]  [_]   [_________]  -- intersecting cache [block1, ..., blockN]
767
    ///
768
    /// For each such hole create a cell with file block state EMPTY.
769
770
736k
    auto it = file_blocks.begin();
771
736k
    auto block_range = (*it)->range();
772
773
736k
    size_t current_pos = 0;
774
736k
    if (block_range.left < range.left) {
775
        ///    [_______     -- requested range
776
        /// [_______
777
        /// ^
778
        /// block1
779
780
151
        current_pos = block_range.right + 1;
781
151
        ++it;
782
736k
    } else {
783
736k
        current_pos = range.left;
784
736k
    }
785
786
1.47M
    while (current_pos <= range.right && it != file_blocks.end()) {
787
737k
        block_range = (*it)->range();
788
789
737k
        if (current_pos == block_range.left) {
790
737k
            current_pos = block_range.right + 1;
791
737k
            ++it;
792
737k
            continue;
793
737k
        }
794
795
737k
        DCHECK(current_pos < block_range.left);
796
797
145
        auto hole_size = block_range.left - current_pos;
798
799
145
        file_blocks.splice(it, split_range_into_cells(hash, context, current_pos, hole_size,
800
145
                                                      FileBlock::State::EMPTY, cache_lock));
801
802
145
        current_pos = block_range.right + 1;
803
145
        ++it;
804
145
    }
805
806
736k
    if (current_pos <= range.right) {
807
        ///   ________]     -- requested range
808
        ///   _____]
809
        ///        ^
810
        /// blockN
811
812
525
        auto hole_size = range.right - current_pos + 1;
813
814
525
        file_blocks.splice(file_blocks.end(),
815
525
                           split_range_into_cells(hash, context, current_pos, hole_size,
816
525
                                                  FileBlock::State::EMPTY, cache_lock));
817
525
    }
818
736k
}
819
820
FileBlocksHolder BlockFileCache::get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
821
875k
                                            CacheContext& context) {
822
875k
    FileBlock::Range range(offset, offset + size - 1);
823
824
875k
    ReadStatistics* stats = context.stats;
825
875k
    DCHECK(stats != nullptr);
826
875k
    MonotonicStopWatch sw;
827
875k
    sw.start();
828
875k
    FileBlocks file_blocks;
829
875k
    std::vector<FileBlockSPtr> need_update_lru_blocks;
830
875k
    const bool async_touch_on_get_or_set = config::enable_file_cache_async_touch_on_get_or_set;
831
875k
    int64_t duration = 0;
832
875k
    {
833
875k
        ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->increment();
834
875k
        std::lock_guard cache_lock(_mutex);
835
875k
        ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->decrement();
836
875k
        stats->lock_wait_timer += sw.elapsed_time();
837
875k
        SCOPED_RAW_TIMER(&duration);
838
        /// Get all blocks which intersect with the given range.
839
875k
        {
840
875k
            SCOPED_RAW_TIMER(&stats->get_timer);
841
875k
            file_blocks = get_impl(hash, context, range, cache_lock);
842
875k
        }
843
844
875k
        if (file_blocks.empty()) {
845
138k
            SCOPED_RAW_TIMER(&stats->set_timer);
846
138k
            file_blocks = split_range_into_cells(hash, context, offset, size,
847
138k
                                                 FileBlock::State::EMPTY, cache_lock);
848
736k
        } else {
849
736k
            SCOPED_RAW_TIMER(&stats->set_timer);
850
736k
            fill_holes_with_empty_file_blocks(file_blocks, hash, context, range, cache_lock);
851
736k
        }
852
875k
        DCHECK(!file_blocks.empty());
853
875k
        *_num_read_blocks << file_blocks.size();
854
875k
        if (!context.is_warmup) {
855
874k
            *_no_warmup_num_read_blocks << file_blocks.size();
856
874k
        }
857
875k
        if (async_touch_on_get_or_set) {
858
193k
            need_update_lru_blocks.reserve(file_blocks.size());
859
193k
        }
860
901k
        for (auto& block : file_blocks) {
861
901k
            size_t block_size = block->range().size();
862
901k
            *_total_read_size_metrics << block_size;
863
901k
            if (block->state_unsafe() == FileBlock::State::DOWNLOADED) {
864
730k
                *_num_hit_blocks << 1;
865
730k
                *_total_hit_size_metrics << block_size;
866
730k
                if (!context.is_warmup) {
867
730k
                    *_no_warmup_num_hit_blocks << 1;
868
730k
                }
869
730k
                if (async_touch_on_get_or_set &&
870
730k
                    need_to_move(block->cache_type(), context.cache_type)) {
871
192k
                    need_update_lru_blocks.emplace_back(block);
872
192k
                }
873
730k
            }
874
901k
        }
875
875k
    }
876
877
875k
    if (async_touch_on_get_or_set) {
878
193k
        for (auto& block : need_update_lru_blocks) {
879
192k
            add_need_update_lru_block(std::move(block));
880
192k
        }
881
193k
    }
882
883
875k
    *_get_or_set_latency_us << (duration / 1000);
884
875k
    return FileBlocksHolder(std::move(file_blocks));
885
875k
}
886
887
FileBlockCell* BlockFileCache::add_cell(const UInt128Wrapper& hash, const CacheContext& context,
888
                                        size_t offset, size_t size, FileBlock::State state,
889
148k
                                        std::lock_guard<std::mutex>& cache_lock) {
890
    /// Create a file block cell and put it in `files` map by [hash][offset].
891
148k
    if (size == 0) {
892
0
        return nullptr; /// Empty files are not cached.
893
0
    }
894
895
148k
    VLOG_DEBUG << "Adding file block to cache. size=" << size << " hash=" << hash.to_string()
896
0
               << " offset=" << offset << " cache_type=" << cache_type_to_string(context.cache_type)
897
0
               << " expiration_time=" << context.expiration_time
898
0
               << " tablet_id=" << context.tablet_id;
899
900
148k
    if (size > 1024 * 1024 * 1024) {
901
1
        LOG(WARNING) << "File block size is too large for a block, reject. size=" << size
902
1
                     << " hash=" << hash.to_string() << " offset=" << offset
903
1
                     << " stack:" << get_stack_trace();
904
1
        return nullptr;
905
1
    }
906
907
148k
    auto& offsets = _files[hash];
908
148k
    auto itr = offsets.find(offset);
909
148k
    if (itr != offsets.end()) {
910
5
        VLOG_DEBUG << "Cache already exists for hash: " << hash.to_string()
911
0
                   << ", offset: " << offset << ", size: " << size
912
0
                   << ".\nCurrent cache structure: " << dump_structure_unlocked(hash, cache_lock);
913
5
        return &(itr->second);
914
5
    }
915
916
148k
    FileCacheKey key;
917
148k
    key.hash = hash;
918
148k
    key.offset = offset;
919
148k
    key.meta.type = context.cache_type;
920
148k
    key.meta.expiration_time = context.expiration_time;
921
148k
    key.meta.tablet_id = context.tablet_id;
922
148k
    FileBlockCell cell(std::make_shared<FileBlock>(key, size, this, state), cache_lock);
923
148k
    Status st;
924
148k
    if (context.expiration_time == 0 && context.cache_type == FileCacheType::TTL) {
925
0
        st = cell.file_block->change_cache_type_lock(FileCacheType::NORMAL, cache_lock);
926
148k
    } else if (context.cache_type != FileCacheType::TTL && context.expiration_time != 0) {
927
1
        st = cell.file_block->change_cache_type_lock(FileCacheType::TTL, cache_lock);
928
1
    }
929
148k
    if (!st.ok()) {
930
0
        LOG(WARNING) << "Cannot change cache type. expiration_time=" << context.expiration_time
931
0
                     << " cache_type=" << cache_type_to_string(context.cache_type)
932
0
                     << " error=" << st.msg();
933
0
    }
934
935
148k
    auto& queue = get_queue(cell.file_block->cache_type());
936
148k
    cell.queue_iterator = queue.add(hash, offset, size, cache_lock);
937
148k
    _lru_recorder->record_queue_event(cell.file_block->cache_type(), CacheLRULogType::ADD,
938
148k
                                      cell.file_block->get_hash_value(), cell.file_block->offset(),
939
148k
                                      cell.size());
940
941
148k
    if (cell.file_block->cache_type() == FileCacheType::TTL) {
942
3.92k
        _cur_ttl_size += cell.size();
943
3.92k
    }
944
148k
    auto [it, _] = offsets.insert(std::make_pair(offset, std::move(cell)));
945
148k
    _cur_cache_size += size;
946
148k
    return &(it->second);
947
148k
}
948
949
0
size_t BlockFileCache::try_release() {
950
0
    SCOPED_CACHE_LOCK(_mutex, this);
951
0
    std::vector<FileBlockCell*> trash;
952
0
    for (auto& [hash, blocks] : _files) {
953
0
        for (auto& [offset, cell] : blocks) {
954
0
            if (cell.releasable()) {
955
0
                trash.emplace_back(&cell);
956
0
            } else {
957
0
                cell.file_block->set_deleting();
958
0
            }
959
0
        }
960
0
    }
961
0
    size_t remove_size = 0;
962
0
    for (auto& cell : trash) {
963
0
        FileBlockSPtr file_block = cell->file_block;
964
0
        std::lock_guard lc(cell->file_block->_mutex);
965
0
        remove_size += file_block->range().size();
966
0
        remove(file_block, cache_lock, lc);
967
0
        VLOG_DEBUG << "try_release " << _cache_base_path
968
0
                   << " hash=" << file_block->get_hash_value().to_string()
969
0
                   << " offset=" << file_block->offset();
970
0
    }
971
0
    *_evict_by_try_release << remove_size;
972
0
    LOG(INFO) << "Released " << trash.size() << " blocks in file cache " << _cache_base_path;
973
0
    return trash.size();
974
0
}
975
976
1.52M
LRUQueue& BlockFileCache::get_queue(FileCacheType type) {
977
1.52M
    switch (type) {
978
249k
    case FileCacheType::INDEX:
979
249k
        return _index_queue;
980
170k
    case FileCacheType::DISPOSABLE:
981
170k
        return _disposable_queue;
982
1.10M
    case FileCacheType::NORMAL:
983
1.10M
        return _normal_queue;
984
6.92k
    case FileCacheType::TTL:
985
6.92k
        return _ttl_queue;
986
0
    default:
987
0
        DCHECK(false);
988
1.52M
    }
989
0
    return _normal_queue;
990
1.52M
}
991
992
140
const LRUQueue& BlockFileCache::get_queue(FileCacheType type) const {
993
140
    switch (type) {
994
33
    case FileCacheType::INDEX:
995
33
        return _index_queue;
996
1
    case FileCacheType::DISPOSABLE:
997
1
        return _disposable_queue;
998
106
    case FileCacheType::NORMAL:
999
106
        return _normal_queue;
1000
0
    case FileCacheType::TTL:
1001
0
        return _ttl_queue;
1002
0
    default:
1003
0
        DCHECK(false);
1004
140
    }
1005
0
    return _normal_queue;
1006
140
}
1007
1008
void BlockFileCache::remove_file_blocks(std::vector<FileBlockCell*>& to_evict,
1009
                                        std::lock_guard<std::mutex>& cache_lock, bool sync,
1010
288k
                                        std::string& reason) {
1011
288k
    auto remove_file_block_if = [&](FileBlockCell* cell) {
1012
113k
        FileBlockSPtr file_block = cell->file_block;
1013
113k
        if (file_block) {
1014
113k
            std::lock_guard block_lock(file_block->_mutex);
1015
113k
            remove(file_block, cache_lock, block_lock, sync);
1016
113k
            VLOG_DEBUG << "remove_file_blocks"
1017
0
                       << " hash=" << file_block->get_hash_value().to_string()
1018
0
                       << " offset=" << file_block->offset() << " reason=" << reason;
1019
113k
        }
1020
113k
    };
1021
288k
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1022
288k
}
1023
1024
void BlockFileCache::find_evict_candidates(LRUQueue& queue, size_t size, size_t cur_cache_size,
1025
                                           size_t& removed_size,
1026
                                           std::vector<FileBlockCell*>& to_evict,
1027
                                           std::lock_guard<std::mutex>& cache_lock,
1028
22.4k
                                           size_t& cur_removed_size, bool evict_in_advance) {
1029
4.84M
    for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1030
4.84M
        if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1031
4.71k
            break;
1032
4.71k
        }
1033
4.83M
        auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1034
1035
4.83M
        DCHECK(cell) << "Cache became inconsistent. key: " << entry_key.to_string()
1036
0
                     << ", offset: " << entry_offset;
1037
1038
4.83M
        size_t cell_size = cell->size();
1039
4.83M
        DCHECK(entry_size == cell_size);
1040
1041
4.83M
        if (cell->releasable()) {
1042
112k
            auto& file_block = cell->file_block;
1043
1044
112k
            std::lock_guard block_lock(file_block->_mutex);
1045
112k
            DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1046
112k
            to_evict.push_back(cell);
1047
112k
            removed_size += cell_size;
1048
112k
            cur_removed_size += cell_size;
1049
112k
        }
1050
4.83M
    }
1051
22.4k
}
1052
1053
// 1. if async load file cache not finish
1054
//     a. evict from lru queue
1055
// 2. if ttl cache
1056
//     a. evict from disposable/normal/index queue one by one
1057
// 3. if dont reach query limit or dont have query limit
1058
//     a. evict from other queue
1059
//     b. evict from current queue
1060
//         a.1 if the data belong write, then just evict cold data
1061
// 4. if reach query limit
1062
//     a. evict from query queue
1063
//     b. evict from other queue
1064
bool BlockFileCache::try_reserve(const UInt128Wrapper& hash, const CacheContext& context,
1065
                                 size_t offset, size_t size,
1066
163k
                                 std::lock_guard<std::mutex>& cache_lock) {
1067
163k
    if (!_async_open_done) {
1068
4
        return try_reserve_during_async_load(size, cache_lock);
1069
4
    }
1070
    // use this strategy in scenarios where there is insufficient disk capacity or insufficient number of inodes remaining
1071
    // directly eliminate 5 times the size of the space
1072
163k
    if (_disk_resource_limit_mode) {
1073
1
        size = 5 * size;
1074
1
    }
1075
1076
163k
    auto query_context = config::enable_file_cache_query_limit &&
1077
163k
                                         (context.query_id.hi != 0 || context.query_id.lo != 0)
1078
163k
                                 ? get_query_context(context.query_id, cache_lock)
1079
163k
                                 : nullptr;
1080
163k
    if (!query_context) {
1081
163k
        return try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock);
1082
163k
    } else if (query_context->get_cache_size(cache_lock) + size <=
1083
31
               query_context->get_max_cache_size()) {
1084
16
        return try_reserve_for_lru(hash, query_context, context, offset, size, cache_lock);
1085
16
    }
1086
15
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1087
15
                               std::chrono::steady_clock::now().time_since_epoch())
1088
15
                               .count();
1089
15
    auto& queue = get_queue(context.cache_type);
1090
15
    size_t removed_size = 0;
1091
15
    size_t ghost_remove_size = 0;
1092
15
    size_t queue_size = queue.get_capacity(cache_lock);
1093
15
    size_t cur_cache_size = _cur_cache_size;
1094
15
    size_t query_context_cache_size = query_context->get_cache_size(cache_lock);
1095
1096
15
    std::vector<LRUQueue::Iterator> ghost;
1097
15
    std::vector<FileBlockCell*> to_evict;
1098
1099
15
    size_t max_size = queue.get_max_size();
1100
48
    auto is_overflow = [&] {
1101
48
        return _disk_resource_limit_mode ? removed_size < size
1102
48
                                         : cur_cache_size + size - removed_size > _capacity ||
1103
48
                                                   (queue_size + size - removed_size > max_size) ||
1104
48
                                                   (query_context_cache_size + size -
1105
38
                                                            (removed_size + ghost_remove_size) >
1106
38
                                                    query_context->get_max_cache_size());
1107
48
    };
1108
1109
    /// Select the cache from the LRU queue held by query for expulsion.
1110
35
    for (auto iter = query_context->queue().begin(); iter != query_context->queue().end(); iter++) {
1111
33
        if (!is_overflow()) {
1112
13
            break;
1113
13
        }
1114
1115
20
        auto* cell = get_cell(iter->hash, iter->offset, cache_lock);
1116
1117
20
        if (!cell) {
1118
            /// The cache corresponding to this record may be swapped out by
1119
            /// other queries, so it has become invalid.
1120
4
            ghost.push_back(iter);
1121
4
            ghost_remove_size += iter->size;
1122
16
        } else {
1123
16
            size_t cell_size = cell->size();
1124
16
            DCHECK(iter->size == cell_size);
1125
1126
16
            if (cell->releasable()) {
1127
16
                auto& file_block = cell->file_block;
1128
1129
16
                std::lock_guard block_lock(file_block->_mutex);
1130
16
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1131
16
                to_evict.push_back(cell);
1132
16
                removed_size += cell_size;
1133
16
            }
1134
16
        }
1135
20
    }
1136
1137
16
    auto remove_file_block_if = [&](FileBlockCell* cell) {
1138
16
        FileBlockSPtr file_block = cell->file_block;
1139
16
        if (file_block) {
1140
16
            query_context->remove(file_block->get_hash_value(), file_block->offset(), cache_lock);
1141
16
            std::lock_guard block_lock(file_block->_mutex);
1142
16
            remove(file_block, cache_lock, block_lock);
1143
16
        }
1144
16
    };
1145
1146
15
    for (auto& iter : ghost) {
1147
4
        query_context->remove(iter->hash, iter->offset, cache_lock);
1148
4
    }
1149
1150
15
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1151
1152
15
    if (is_overflow() &&
1153
15
        !try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock)) {
1154
1
        return false;
1155
1
    }
1156
14
    query_context->reserve(hash, offset, size, cache_lock);
1157
14
    return true;
1158
15
}
1159
1160
381
void BlockFileCache::try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock) {
1161
381
    UInt128Wrapper hash = UInt128Wrapper();
1162
381
    size_t offset = 0;
1163
381
    CacheContext context;
1164
    /* we pick NORMAL and TTL cache to evict in advance
1165
     * we reserve for them but won't acutually give space to them
1166
     * on the contrary, NORMAL and TTL may sacrifice by LRU evicting themselves
1167
     * other cache types cannot be exempted because we will evict what they have stolen before LRU evicting
1168
     * in summary: all cache types will shrink somewhat, and NORMAL and TTL shrink the most, to make sure the cache is not full
1169
     */
1170
381
    context.cache_type = FileCacheType::NORMAL;
1171
381
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1172
381
    context.cache_type = FileCacheType::TTL;
1173
381
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1174
381
}
1175
1176
// remove specific cache synchronously, for critical operations
1177
// if in use, cache meta will be deleted after use and the block file is then deleted asynchronously
1178
8
void BlockFileCache::remove_if_cached(const UInt128Wrapper& file_key) {
1179
8
    std::string reason = "remove_if_cached";
1180
8
    SCOPED_CACHE_LOCK(_mutex, this);
1181
8
    auto iter = _files.find(file_key);
1182
8
    std::vector<FileBlockCell*> to_remove;
1183
8
    if (iter != _files.end()) {
1184
14
        for (auto& [_, cell] : iter->second) {
1185
14
            if (cell.releasable()) {
1186
13
                to_remove.push_back(&cell);
1187
13
            } else {
1188
1
                cell.file_block->set_deleting();
1189
1
            }
1190
14
        }
1191
6
    }
1192
8
    remove_file_blocks(to_remove, cache_lock, true, reason);
1193
8
}
1194
1195
// the async version of remove_if_cached, for background operations
1196
// cache meta is deleted synchronously if not in use, and the block file is deleted asynchronously
1197
// if in use, cache meta will be deleted after use and the block file is then deleted asynchronously
1198
101k
void BlockFileCache::remove_if_cached_async(const UInt128Wrapper& file_key) {
1199
101k
    std::string reason = "remove_if_cached_async";
1200
101k
    SCOPED_CACHE_LOCK(_mutex, this);
1201
1202
101k
    auto iter = _files.find(file_key);
1203
101k
    std::vector<FileBlockCell*> to_remove;
1204
101k
    if (iter != _files.end()) {
1205
12.4k
        for (auto& [_, cell] : iter->second) {
1206
12.4k
            *_gc_evict_bytes_metrics << cell.size();
1207
12.4k
            *_gc_evict_count_metrics << 1;
1208
12.4k
            if (cell.releasable()) {
1209
891
                to_remove.push_back(&cell);
1210
11.5k
            } else {
1211
11.5k
                cell.file_block->set_deleting();
1212
11.5k
            }
1213
12.4k
        }
1214
12.4k
    }
1215
101k
    remove_file_blocks(to_remove, cache_lock, false, reason);
1216
101k
}
1217
1218
std::vector<FileCacheType> BlockFileCache::get_other_cache_type_without_ttl(
1219
164k
        FileCacheType cur_cache_type) {
1220
164k
    switch (cur_cache_type) {
1221
4.29k
    case FileCacheType::TTL:
1222
4.29k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1223
39.1k
    case FileCacheType::INDEX:
1224
39.1k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL};
1225
117k
    case FileCacheType::NORMAL:
1226
117k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX};
1227
3.60k
    case FileCacheType::DISPOSABLE:
1228
3.60k
        return {FileCacheType::NORMAL, FileCacheType::INDEX};
1229
0
    default:
1230
0
        return {};
1231
164k
    }
1232
0
    return {};
1233
164k
}
1234
1235
21.4k
std::vector<FileCacheType> BlockFileCache::get_other_cache_type(FileCacheType cur_cache_type) {
1236
21.4k
    switch (cur_cache_type) {
1237
663
    case FileCacheType::TTL:
1238
663
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1239
10.0k
    case FileCacheType::INDEX:
1240
10.0k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::TTL};
1241
9.74k
    case FileCacheType::NORMAL:
1242
9.74k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX, FileCacheType::TTL};
1243
1.02k
    case FileCacheType::DISPOSABLE:
1244
1.02k
        return {FileCacheType::NORMAL, FileCacheType::INDEX, FileCacheType::TTL};
1245
0
    default:
1246
0
        return {};
1247
21.4k
    }
1248
0
    return {};
1249
21.4k
}
1250
1251
void BlockFileCache::reset_range(const UInt128Wrapper& hash, size_t offset, size_t old_size,
1252
5.46k
                                 size_t new_size, std::lock_guard<std::mutex>& cache_lock) {
1253
5.46k
    DCHECK(_files.find(hash) != _files.end() &&
1254
5.46k
           _files.find(hash)->second.find(offset) != _files.find(hash)->second.end());
1255
5.46k
    FileBlockCell* cell = get_cell(hash, offset, cache_lock);
1256
5.46k
    DCHECK(cell != nullptr);
1257
5.46k
    if (cell == nullptr) {
1258
0
        LOG(WARNING) << "reset_range skipped because cache cell is missing. hash="
1259
0
                     << hash.to_string() << " offset=" << offset << " old_size=" << old_size
1260
0
                     << " new_size=" << new_size;
1261
0
        return;
1262
0
    }
1263
5.46k
    DCHECK_EQ(cell->file_block->_block_range.size(), old_size);
1264
5.46k
    if (cell->queue_iterator) {
1265
5.46k
        auto& queue = get_queue(cell->file_block->cache_type());
1266
5.46k
        DCHECK(queue.contains(hash, offset, cache_lock));
1267
5.46k
        queue.resize(*cell->queue_iterator, new_size, cache_lock);
1268
5.46k
        _lru_recorder->record_queue_event(cell->file_block->cache_type(), CacheLRULogType::RESIZE,
1269
5.46k
                                          cell->file_block->get_hash_value(),
1270
5.46k
                                          cell->file_block->offset(), new_size);
1271
5.46k
    }
1272
5.46k
    cell->file_block->_block_range.right = cell->file_block->_block_range.left + new_size - 1;
1273
5.46k
    _cur_cache_size -= old_size;
1274
5.46k
    _cur_cache_size += new_size;
1275
5.46k
    if (cell->file_block->cache_type() == FileCacheType::TTL) {
1276
0
        _cur_ttl_size -= old_size;
1277
0
        _cur_ttl_size += new_size;
1278
0
    }
1279
5.46k
}
1280
1281
bool BlockFileCache::try_reserve_from_other_queue_by_time_interval(
1282
        FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, size_t size,
1283
164k
        int64_t cur_time, std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1284
164k
    size_t removed_size = 0;
1285
164k
    size_t cur_cache_size = _cur_cache_size;
1286
164k
    std::vector<FileBlockCell*> to_evict;
1287
333k
    for (FileCacheType cache_type : other_cache_types) {
1288
333k
        auto& queue = get_queue(cache_type);
1289
333k
        size_t remove_size_per_type = 0;
1290
333k
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1291
296k
            if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1292
255k
                break;
1293
255k
            }
1294
41.4k
            auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1295
41.4k
            DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << entry_key.to_string()
1296
0
                         << ", offset: " << entry_offset;
1297
1298
41.4k
            size_t cell_size = cell->size();
1299
41.4k
            DCHECK(entry_size == cell_size);
1300
1301
41.4k
            if (cell->atime == 0 ? true : cell->atime + queue.get_hot_data_interval() > cur_time) {
1302
41.4k
                break;
1303
41.4k
            }
1304
1305
2
            if (cell->releasable()) {
1306
2
                auto& file_block = cell->file_block;
1307
2
                std::lock_guard block_lock(file_block->_mutex);
1308
2
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1309
2
                to_evict.push_back(cell);
1310
2
                removed_size += cell_size;
1311
2
                remove_size_per_type += cell_size;
1312
2
            }
1313
2
        }
1314
333k
        *(_evict_by_time_metrics_matrix[cache_type][cur_type]) << remove_size_per_type;
1315
333k
    }
1316
164k
    bool is_sync_removal = !evict_in_advance;
1317
164k
    std::string reason = std::string("try_reserve_by_time ") +
1318
164k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1319
164k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1320
1321
164k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1322
164k
}
1323
1324
bool BlockFileCache::is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
1325
5.32M
                                 bool evict_in_advance) const {
1326
5.32M
    bool ret = false;
1327
5.32M
    if (evict_in_advance) { // we don't need to check _need_evict_cache_in_advance
1328
507k
        ret = (removed_size < need_size);
1329
507k
        return ret;
1330
507k
    }
1331
4.81M
    if (_disk_resource_limit_mode) {
1332
4
        ret = (removed_size < need_size);
1333
4.81M
    } else {
1334
4.81M
        ret = (cur_cache_size + need_size - removed_size > _capacity);
1335
4.81M
    }
1336
4.81M
    return ret;
1337
5.32M
}
1338
1339
bool BlockFileCache::try_reserve_from_other_queue_by_size(
1340
        FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, size_t size,
1341
1.22k
        std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1342
1.22k
    size_t removed_size = 0;
1343
1.22k
    size_t cur_cache_size = _cur_cache_size;
1344
1.22k
    std::vector<FileBlockCell*> to_evict;
1345
    // we follow the privilege defined in get_other_cache_types to evict
1346
3.68k
    for (FileCacheType cache_type : other_cache_types) {
1347
3.68k
        auto& queue = get_queue(cache_type);
1348
1349
        // we will not drain each of them to the bottom -- i.e., we only
1350
        // evict what they have stolen.
1351
3.68k
        size_t cur_queue_size = queue.get_capacity(cache_lock);
1352
3.68k
        size_t cur_queue_max_size = queue.get_max_size();
1353
3.68k
        if (cur_queue_size <= cur_queue_max_size) {
1354
2.11k
            continue;
1355
2.11k
        }
1356
1.57k
        size_t cur_removed_size = 0;
1357
1.57k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1358
1.57k
                              cur_removed_size, evict_in_advance);
1359
1.57k
        *(_evict_by_size_metrics_matrix[cache_type][cur_type]) << cur_removed_size;
1360
1.57k
    }
1361
1.22k
    bool is_sync_removal = !evict_in_advance;
1362
1.22k
    std::string reason = std::string("try_reserve_by_size") +
1363
1.22k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1364
1.22k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1365
1.22k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1366
1.22k
}
1367
1368
bool BlockFileCache::try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t size,
1369
                                                  int64_t cur_time,
1370
                                                  std::lock_guard<std::mutex>& cache_lock,
1371
164k
                                                  bool evict_in_advance) {
1372
    // currently, TTL cache is not considered as a candidate
1373
164k
    auto other_cache_types = get_other_cache_type_without_ttl(cur_cache_type);
1374
164k
    bool reserve_success = try_reserve_from_other_queue_by_time_interval(
1375
164k
            cur_cache_type, other_cache_types, size, cur_time, cache_lock, evict_in_advance);
1376
164k
    if (reserve_success || !config::file_cache_enable_evict_from_other_queue_by_size) {
1377
143k
        return reserve_success;
1378
143k
    }
1379
1380
21.4k
    other_cache_types = get_other_cache_type(cur_cache_type);
1381
21.4k
    auto& cur_queue = get_queue(cur_cache_type);
1382
21.4k
    size_t cur_queue_size = cur_queue.get_capacity(cache_lock);
1383
21.4k
    size_t cur_queue_max_size = cur_queue.get_max_size();
1384
    // Hit the soft limit by self, cannot remove from other queues
1385
21.4k
    if (_cur_cache_size + size > _capacity && cur_queue_size + size > cur_queue_max_size) {
1386
20.2k
        return false;
1387
20.2k
    }
1388
1.22k
    return try_reserve_from_other_queue_by_size(cur_cache_type, other_cache_types, size, cache_lock,
1389
1.22k
                                                evict_in_advance);
1390
21.4k
}
1391
1392
bool BlockFileCache::try_reserve_for_lru(const UInt128Wrapper& hash,
1393
                                         QueryFileCacheContextPtr query_context,
1394
                                         const CacheContext& context, size_t offset, size_t size,
1395
                                         std::lock_guard<std::mutex>& cache_lock,
1396
164k
                                         bool evict_in_advance) {
1397
164k
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1398
164k
                               std::chrono::steady_clock::now().time_since_epoch())
1399
164k
                               .count();
1400
164k
    if (!try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock,
1401
164k
                                      evict_in_advance)) {
1402
20.8k
        auto& queue = get_queue(context.cache_type);
1403
20.8k
        size_t removed_size = 0;
1404
20.8k
        size_t cur_cache_size = _cur_cache_size;
1405
1406
20.8k
        std::vector<FileBlockCell*> to_evict;
1407
20.8k
        size_t cur_removed_size = 0;
1408
20.8k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1409
20.8k
                              cur_removed_size, evict_in_advance);
1410
20.8k
        bool is_sync_removal = !evict_in_advance;
1411
20.8k
        std::string reason = std::string("try_reserve for cache type ") +
1412
20.8k
                             cache_type_to_string(context.cache_type) +
1413
20.8k
                             " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1414
20.8k
        remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1415
20.8k
        *(_evict_by_self_lru_metrics_matrix[context.cache_type]) << cur_removed_size;
1416
1417
20.8k
        if (is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1418
16.9k
            return false;
1419
16.9k
        }
1420
20.8k
    }
1421
1422
147k
    if (query_context) {
1423
16
        query_context->reserve(hash, offset, size, cache_lock);
1424
16
    }
1425
147k
    return true;
1426
164k
}
1427
1428
template <class T, class U>
1429
    requires IsXLock<T> && IsXLock<U>
1430
137k
void BlockFileCache::remove(FileBlockSPtr file_block, T& cache_lock, U& block_lock, bool sync) {
1431
137k
    auto hash = file_block->get_hash_value();
1432
137k
    auto offset = file_block->offset();
1433
137k
    auto type = file_block->cache_type();
1434
137k
    auto expiration_time = file_block->expiration_time();
1435
137k
    auto tablet_id = file_block->tablet_id();
1436
137k
    auto* cell = get_cell(hash, offset, cache_lock);
1437
137k
    file_block->cell = nullptr;
1438
    // Holder cleanup can race with prior cache metadata cleanup. In that case,
1439
    // skip the duplicate remove instead of touching a detached or replaced cell.
1440
137k
    if (cell == nullptr) {
1441
1
        LOG(WARNING) << "remove skipped because cache cell is missing. hash=" << hash.to_string()
1442
1
                     << " offset=" << offset << " size=" << file_block->range().size()
1443
1
                     << " type=" << cache_type_to_string(type)
1444
1
                     << " state=" << FileBlock::state_to_string(file_block->state_unsafe())
1445
1
                     << " expiration_time=" << expiration_time << " sync=" << sync;
1446
1
        return;
1447
1
    }
1448
137k
    if (cell->file_block.get() != file_block.get()) {
1449
1
        auto* cell_file_block = cell->file_block.get();
1450
1
        LOG(WARNING)
1451
1
                << "remove skipped because cache cell points to a different file block. hash="
1452
1
                << hash.to_string() << " offset=" << offset
1453
1
                << " size=" << file_block->range().size() << " type=" << cache_type_to_string(type)
1454
1
                << " state=" << FileBlock::state_to_string(file_block->state_unsafe())
1455
1
                << " expiration_time=" << expiration_time << " sync=" << sync << " cell_block_hash="
1456
1
                << (cell_file_block ? cell_file_block->get_hash_value().to_string() : "<null>")
1457
1
                << " cell_block_offset="
1458
1
                << (cell_file_block ? std::to_string(cell_file_block->offset()) : "<null>")
1459
1
                << " cell_block_size="
1460
1
                << (cell_file_block ? std::to_string(cell_file_block->range().size()) : "<null>")
1461
1
                << " cell_block_type="
1462
1
                << (cell_file_block ? cache_type_to_string(cell_file_block->cache_type())
1463
1
                                    : "<null>")
1464
1
                << " cell_block_state="
1465
1
                << (cell_file_block ? FileBlock::state_to_string(cell_file_block->state_unsafe())
1466
1
                                    : "<null>");
1467
1
        return;
1468
1
    }
1469
137k
    DCHECK(cell->queue_iterator);
1470
137k
    if (cell->queue_iterator) {
1471
137k
        auto& queue = get_queue(file_block->cache_type());
1472
137k
        queue.remove(*cell->queue_iterator, cache_lock);
1473
137k
        _lru_recorder->record_queue_event(file_block->cache_type(), CacheLRULogType::REMOVE,
1474
137k
                                          cell->file_block->get_hash_value(),
1475
137k
                                          cell->file_block->offset(), cell->size());
1476
137k
    }
1477
137k
    *_queue_evict_size_metrics[static_cast<int>(file_block->cache_type())]
1478
137k
            << file_block->range().size();
1479
137k
    *_total_evict_size_metrics << file_block->range().size();
1480
1481
137k
    VLOG_DEBUG << "Removing file block from cache. hash: " << hash.to_string()
1482
0
               << ", offset: " << offset << ", size: " << file_block->range().size()
1483
0
               << ", type: " << cache_type_to_string(type);
1484
1485
137k
    if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADED) {
1486
113k
        FileCacheKey key;
1487
113k
        key.hash = hash;
1488
113k
        key.offset = offset;
1489
113k
        key.meta.type = type;
1490
113k
        key.meta.expiration_time = expiration_time;
1491
113k
        key.meta.tablet_id = tablet_id;
1492
113k
        if (sync) {
1493
27.6k
            int64_t duration_ns = 0;
1494
27.6k
            Status st;
1495
27.6k
            {
1496
27.6k
                SCOPED_RAW_TIMER(&duration_ns);
1497
27.6k
                st = _storage->remove(key);
1498
27.6k
            }
1499
27.6k
            *_storage_sync_remove_latency_us << (duration_ns / 1000);
1500
27.6k
            if (!st.ok()) {
1501
2
                LOG_WARNING("").error(st);
1502
2
            }
1503
86.1k
        } else {
1504
            // the file will be deleted in the bottom half
1505
            // so there will be a window that the file is not in the cache but still in the storage
1506
            // but it's ok, because the rowset is stale already
1507
86.1k
            bool ret = _recycle_keys.enqueue(key);
1508
86.1k
            if (ret) [[likely]] {
1509
86.1k
                *_recycle_keys_length_recorder << _recycle_keys.size_approx();
1510
86.1k
            } else {
1511
0
                LOG_WARNING("Failed to push recycle key to queue, do it synchronously");
1512
0
                int64_t duration_ns = 0;
1513
0
                Status st;
1514
0
                {
1515
0
                    SCOPED_RAW_TIMER(&duration_ns);
1516
0
                    st = _storage->remove(key);
1517
0
                }
1518
0
                *_storage_retry_sync_remove_latency_us << (duration_ns / 1000);
1519
0
                if (!st.ok()) {
1520
0
                    LOG_WARNING("").error(st);
1521
0
                }
1522
0
            }
1523
86.1k
        }
1524
113k
    } else if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADING) {
1525
0
        file_block->set_deleting();
1526
0
        return;
1527
0
    }
1528
137k
    _cur_cache_size -= file_block->range().size();
1529
137k
    if (FileCacheType::TTL == type) {
1530
1.29k
        _cur_ttl_size -= file_block->range().size();
1531
1.29k
    }
1532
137k
    auto it = _files.find(hash);
1533
137k
    if (it != _files.end()) {
1534
137k
        it->second.erase(file_block->offset());
1535
137k
        if (it->second.empty()) {
1536
108k
            _files.erase(hash);
1537
108k
        }
1538
137k
    }
1539
137k
    *_num_removed_blocks << 1;
1540
137k
}
1541
1542
46
size_t BlockFileCache::get_used_cache_size(FileCacheType cache_type) const {
1543
46
    SCOPED_CACHE_LOCK(_mutex, this);
1544
46
    return get_used_cache_size_unlocked(cache_type, cache_lock);
1545
46
}
1546
1547
size_t BlockFileCache::get_used_cache_size_unlocked(FileCacheType cache_type,
1548
46
                                                    std::lock_guard<std::mutex>& cache_lock) const {
1549
46
    return get_queue(cache_type).get_capacity(cache_lock);
1550
46
}
1551
1552
0
size_t BlockFileCache::get_available_cache_size(FileCacheType cache_type) const {
1553
0
    SCOPED_CACHE_LOCK(_mutex, this);
1554
0
    return get_available_cache_size_unlocked(cache_type, cache_lock);
1555
0
}
1556
1557
size_t BlockFileCache::get_available_cache_size_unlocked(
1558
0
        FileCacheType cache_type, std::lock_guard<std::mutex>& cache_lock) const {
1559
0
    return get_queue(cache_type).get_max_element_size() -
1560
0
           get_used_cache_size_unlocked(cache_type, cache_lock);
1561
0
}
1562
1563
91
size_t BlockFileCache::get_file_blocks_num(FileCacheType cache_type) const {
1564
91
    SCOPED_CACHE_LOCK(_mutex, this);
1565
91
    return get_file_blocks_num_unlocked(cache_type, cache_lock);
1566
91
}
1567
1568
size_t BlockFileCache::get_file_blocks_num_unlocked(FileCacheType cache_type,
1569
91
                                                    std::lock_guard<std::mutex>& cache_lock) const {
1570
91
    return get_queue(cache_type).get_elements_num(cache_lock);
1571
91
}
1572
1573
FileBlockCell::FileBlockCell(FileBlockSPtr file_block, std::lock_guard<std::mutex>& cache_lock)
1574
148k
        : file_block(file_block) {
1575
148k
    file_block->cell = this;
1576
    /**
1577
     * Cell can be created with either DOWNLOADED or EMPTY file block's state.
1578
     * File block acquires DOWNLOADING state and creates LRUQueue iterator on first
1579
     * successful getOrSetDownaloder call.
1580
     */
1581
1582
148k
    switch (file_block->_download_state) {
1583
778
    case FileBlock::State::DOWNLOADED:
1584
148k
    case FileBlock::State::EMPTY:
1585
148k
    case FileBlock::State::SKIP_CACHE: {
1586
148k
        break;
1587
148k
    }
1588
0
    default:
1589
0
        DCHECK(false) << "Can create cell with either EMPTY, DOWNLOADED, SKIP_CACHE state, got: "
1590
0
                      << FileBlock::state_to_string(file_block->_download_state);
1591
148k
    }
1592
148k
    if (file_block->cache_type() == FileCacheType::TTL) {
1593
3.92k
        update_atime();
1594
3.92k
    }
1595
148k
}
1596
1597
LRUQueue::Iterator LRUQueue::add(const UInt128Wrapper& hash, size_t offset, size_t size,
1598
289k
                                 std::lock_guard<std::mutex>& /* cache_lock */) {
1599
289k
    cache_size += size;
1600
289k
    auto iter = queue.insert(queue.end(), FileKeyAndOffset(hash, offset, size));
1601
289k
    map.insert(std::make_pair(std::make_pair(hash, offset), iter));
1602
289k
    return iter;
1603
289k
}
1604
1605
0
void LRUQueue::remove_all(std::lock_guard<std::mutex>& /* cache_lock */) {
1606
0
    queue.clear();
1607
0
    map.clear();
1608
0
    cache_size = 0;
1609
0
}
1610
1611
1.07M
void LRUQueue::move_to_end(Iterator queue_it, std::lock_guard<std::mutex>& /* cache_lock */) {
1612
1.07M
    queue.splice(queue.end(), queue, queue_it);
1613
1.07M
}
1614
1615
void LRUQueue::resize(Iterator queue_it, size_t new_size,
1616
10.9k
                      std::lock_guard<std::mutex>& /* cache_lock */) {
1617
10.9k
    cache_size -= queue_it->size;
1618
10.9k
    queue_it->size = new_size;
1619
10.9k
    cache_size += new_size;
1620
10.9k
}
1621
bool LRUQueue::contains(const UInt128Wrapper& hash, size_t offset,
1622
5.46k
                        std::lock_guard<std::mutex>& /* cache_lock */) const {
1623
5.46k
    return map.find(std::make_pair(hash, offset)) != map.end();
1624
5.46k
}
1625
1626
LRUQueue::Iterator LRUQueue::get(const UInt128Wrapper& hash, size_t offset,
1627
785k
                                 std::lock_guard<std::mutex>& /* cache_lock */) const {
1628
785k
    auto itr = map.find(std::make_pair(hash, offset));
1629
785k
    if (itr != map.end()) {
1630
548k
        return itr->second;
1631
548k
    }
1632
237k
    return std::list<FileKeyAndOffset>::iterator();
1633
785k
}
1634
1635
2
std::string LRUQueue::to_string(std::lock_guard<std::mutex>& /* cache_lock */) const {
1636
2
    std::string result;
1637
18
    for (const auto& [hash, offset, size] : queue) {
1638
18
        if (!result.empty()) {
1639
16
            result += ", ";
1640
16
        }
1641
18
        result += fmt::format("{}: [{}, {}]", hash.to_string(), offset, offset + size - 1);
1642
18
    }
1643
2
    return result;
1644
2
}
1645
1646
size_t LRUQueue::levenshtein_distance_from(LRUQueue& base,
1647
5
                                           std::lock_guard<std::mutex>& cache_lock) {
1648
5
    std::list<FileKeyAndOffset> target_queue = this->queue;
1649
5
    std::list<FileKeyAndOffset> base_queue = base.queue;
1650
5
    std::vector<FileKeyAndOffset> vec1(target_queue.begin(), target_queue.end());
1651
5
    std::vector<FileKeyAndOffset> vec2(base_queue.begin(), base_queue.end());
1652
1653
5
    size_t m = vec1.size();
1654
5
    size_t n = vec2.size();
1655
1656
    // Create a 2D vector (matrix) to store the Levenshtein distances
1657
    // dp[i][j] will hold the distance between the first i elements of vec1 and the first j elements of vec2
1658
5
    std::vector<std::vector<size_t>> dp(m + 1, std::vector<size_t>(n + 1, 0));
1659
1660
    // Initialize the first row and column of the matrix
1661
    // The distance between an empty list and a list of length k is k (all insertions or deletions)
1662
22
    for (size_t i = 0; i <= m; ++i) {
1663
17
        dp[i][0] = i;
1664
17
    }
1665
20
    for (size_t j = 0; j <= n; ++j) {
1666
15
        dp[0][j] = j;
1667
15
    }
1668
1669
    // Fill the matrix using dynamic programming
1670
17
    for (size_t i = 1; i <= m; ++i) {
1671
38
        for (size_t j = 1; j <= n; ++j) {
1672
            // Check if the current elements of both vectors are equal
1673
26
            size_t cost = (vec1[i - 1].hash == vec2[j - 1].hash &&
1674
26
                           vec1[i - 1].offset == vec2[j - 1].offset)
1675
26
                                  ? 0
1676
26
                                  : 1;
1677
            // Calculate the minimum cost of three possible operations:
1678
            // 1. Insertion: dp[i][j-1] + 1
1679
            // 2. Deletion: dp[i-1][j] + 1
1680
            // 3. Substitution: dp[i-1][j-1] + cost (0 if elements are equal, 1 if not)
1681
26
            dp[i][j] = std::min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost});
1682
26
        }
1683
12
    }
1684
    // The bottom-right cell of the matrix contains the Levenshtein distance
1685
5
    return dp[m][n];
1686
5
}
1687
1688
1
std::string BlockFileCache::dump_structure(const UInt128Wrapper& hash) {
1689
1
    SCOPED_CACHE_LOCK(_mutex, this);
1690
1
    return dump_structure_unlocked(hash, cache_lock);
1691
1
}
1692
1693
std::string BlockFileCache::dump_structure_unlocked(const UInt128Wrapper& hash,
1694
1
                                                    std::lock_guard<std::mutex>&) {
1695
1
    std::stringstream result;
1696
1
    auto it = _files.find(hash);
1697
1
    if (it == _files.end()) {
1698
0
        return std::string("");
1699
0
    }
1700
1
    const auto& cells_by_offset = it->second;
1701
1702
1
    for (const auto& [_, cell] : cells_by_offset) {
1703
1
        result << cell.file_block->get_info_for_log() << " "
1704
1
               << cache_type_to_string(cell.file_block->cache_type()) << "\n";
1705
1
    }
1706
1707
1
    return result.str();
1708
1
}
1709
1710
0
std::string BlockFileCache::dump_single_cache_type(const UInt128Wrapper& hash, size_t offset) {
1711
0
    SCOPED_CACHE_LOCK(_mutex, this);
1712
0
    return dump_single_cache_type_unlocked(hash, offset, cache_lock);
1713
0
}
1714
1715
std::string BlockFileCache::dump_single_cache_type_unlocked(const UInt128Wrapper& hash,
1716
                                                            size_t offset,
1717
0
                                                            std::lock_guard<std::mutex>&) {
1718
0
    std::stringstream result;
1719
0
    auto it = _files.find(hash);
1720
0
    if (it == _files.end()) {
1721
0
        return std::string("");
1722
0
    }
1723
0
    const auto& cells_by_offset = it->second;
1724
0
    const auto& cell = cells_by_offset.find(offset);
1725
1726
0
    return cache_type_to_string(cell->second.file_block->cache_type());
1727
0
}
1728
1729
void BlockFileCache::change_cache_type(const UInt128Wrapper& hash, size_t offset,
1730
                                       FileCacheType new_type,
1731
42
                                       std::lock_guard<std::mutex>& cache_lock) {
1732
42
    if (auto iter = _files.find(hash); iter != _files.end()) {
1733
42
        auto& file_blocks = iter->second;
1734
42
        if (auto cell_it = file_blocks.find(offset); cell_it != file_blocks.end()) {
1735
41
            FileBlockCell& cell = cell_it->second;
1736
41
            auto& cur_queue = get_queue(cell.file_block->cache_type());
1737
41
            DCHECK(cell.queue_iterator.has_value());
1738
41
            cur_queue.remove(*cell.queue_iterator, cache_lock);
1739
41
            _lru_recorder->record_queue_event(
1740
41
                    cell.file_block->cache_type(), CacheLRULogType::REMOVE,
1741
41
                    cell.file_block->get_hash_value(), cell.file_block->offset(), cell.size());
1742
41
            auto& new_queue = get_queue(new_type);
1743
41
            cell.queue_iterator =
1744
41
                    new_queue.add(hash, offset, cell.file_block->range().size(), cache_lock);
1745
41
            _lru_recorder->record_queue_event(new_type, CacheLRULogType::ADD,
1746
41
                                              cell.file_block->get_hash_value(),
1747
41
                                              cell.file_block->offset(), cell.size());
1748
41
        }
1749
42
    }
1750
42
}
1751
1752
// @brief: get a path's disk capacity used percent, inode used percent
1753
// @param: path
1754
// @param: percent.first disk used percent, percent.second inode used percent
1755
2.03k
int disk_used_percentage(const std::string& path, std::pair<int, int>* percent) {
1756
2.03k
    struct statfs stat;
1757
2.03k
    int ret = statfs(path.c_str(), &stat);
1758
2.03k
    if (ret != 0) {
1759
2
        return ret;
1760
2
    }
1761
    // https://github.com/coreutils/coreutils/blob/master/src/df.c#L1195
1762
    // v->used = stat.f_blocks - stat.f_bfree
1763
    // nonroot_total = stat.f_blocks - stat.f_bfree + stat.f_bavail
1764
2.03k
    uintmax_t u100 = (stat.f_blocks - stat.f_bfree) * 100;
1765
2.03k
    uintmax_t nonroot_total = stat.f_blocks - stat.f_bfree + stat.f_bavail;
1766
2.03k
    int capacity_percentage = int(u100 / nonroot_total + (u100 % nonroot_total != 0));
1767
1768
2.03k
    unsigned long long inode_free = stat.f_ffree;
1769
2.03k
    unsigned long long inode_total = stat.f_files;
1770
2.03k
    int inode_percentage = cast_set<int>(inode_free * 100 / inode_total);
1771
2.03k
    percent->first = capacity_percentage;
1772
2.03k
    percent->second = 100 - inode_percentage;
1773
1774
    // Add sync point for testing
1775
2.03k
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::disk_used_percentage:1", percent);
1776
1777
2.03k
    return 0;
1778
2.03k
}
1779
1780
10
std::string BlockFileCache::reset_capacity(size_t new_capacity) {
1781
10
    using namespace std::chrono;
1782
10
    int64_t space_released = 0;
1783
10
    size_t old_capacity = 0;
1784
10
    std::stringstream ss;
1785
10
    ss << "finish reset_capacity, path=" << _cache_base_path;
1786
10
    auto adjust_start_time = steady_clock::time_point();
1787
10
    {
1788
10
        SCOPED_CACHE_LOCK(_mutex, this);
1789
10
        if (new_capacity < _capacity && new_capacity < _cur_cache_size) {
1790
1
            int64_t need_remove_size = _cur_cache_size - new_capacity;
1791
4
            auto remove_blocks = [&](LRUQueue& queue) -> int64_t {
1792
4
                int64_t queue_released = 0;
1793
4
                std::vector<FileBlockCell*> to_evict;
1794
13
                for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1795
13
                    if (need_remove_size <= 0) {
1796
1
                        break;
1797
1
                    }
1798
12
                    need_remove_size -= entry_size;
1799
12
                    space_released += entry_size;
1800
12
                    queue_released += entry_size;
1801
12
                    auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1802
12
                    if (!cell->releasable()) {
1803
0
                        cell->file_block->set_deleting();
1804
0
                        continue;
1805
0
                    }
1806
12
                    to_evict.push_back(cell);
1807
12
                }
1808
12
                for (auto& cell : to_evict) {
1809
12
                    FileBlockSPtr file_block = cell->file_block;
1810
12
                    std::lock_guard block_lock(file_block->_mutex);
1811
12
                    remove(file_block, cache_lock, block_lock);
1812
12
                }
1813
4
                return queue_released;
1814
4
            };
1815
1
            int64_t queue_released = remove_blocks(_disposable_queue);
1816
1
            ss << " disposable_queue released " << queue_released;
1817
1
            queue_released = remove_blocks(_normal_queue);
1818
1
            ss << " normal_queue released " << queue_released;
1819
1
            queue_released = remove_blocks(_index_queue);
1820
1
            ss << " index_queue released " << queue_released;
1821
1
            queue_released = remove_blocks(_ttl_queue);
1822
1
            ss << " ttl_queue released " << queue_released;
1823
1824
1
            _disk_resource_limit_mode = true;
1825
1
            _disk_limit_mode_metrics->set_value(1);
1826
1
            ss << " total_space_released=" << space_released;
1827
1
        }
1828
10
        old_capacity = _capacity;
1829
10
        _capacity = new_capacity;
1830
10
        _cache_capacity_metrics->set_value(_capacity);
1831
10
    }
1832
10
    auto use_time = duration_cast<milliseconds>(steady_clock::time_point() - adjust_start_time);
1833
10
    LOG(INFO) << "Finish tag deleted block. path=" << _cache_base_path
1834
10
              << " use_time=" << cast_set<int64_t>(use_time.count());
1835
10
    ss << " old_capacity=" << old_capacity << " new_capacity=" << new_capacity;
1836
10
    LOG(INFO) << ss.str();
1837
10
    return ss.str();
1838
10
}
1839
1840
1.88k
void BlockFileCache::check_disk_resource_limit() {
1841
1.88k
    if (_storage->get_type() != FileCacheStorageType::DISK) {
1842
804
        return;
1843
804
    }
1844
1845
1.08k
    bool previous_mode = _disk_resource_limit_mode;
1846
1.08k
    if (_capacity > _cur_cache_size) {
1847
1.08k
        _disk_resource_limit_mode = false;
1848
1.08k
        _disk_limit_mode_metrics->set_value(0);
1849
1.08k
    }
1850
1.08k
    std::pair<int, int> percent;
1851
1.08k
    int ret = disk_used_percentage(_cache_base_path, &percent);
1852
1.08k
    if (ret != 0) {
1853
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
1854
1
        return;
1855
1
    }
1856
1.08k
    auto [space_percentage, inode_percentage] = percent;
1857
2.16k
    auto is_insufficient = [](const int& percentage) {
1858
2.16k
        return percentage >= config::file_cache_enter_disk_resource_limit_mode_percent;
1859
2.16k
    };
1860
1.08k
    DCHECK_GE(space_percentage, 0);
1861
1.08k
    DCHECK_LE(space_percentage, 100);
1862
1.08k
    DCHECK_GE(inode_percentage, 0);
1863
1.08k
    DCHECK_LE(inode_percentage, 100);
1864
    // ATTN: due to that can be changed dynamically, set it to default value if it's invalid
1865
    // FIXME: reject with config validator
1866
1.08k
    if (config::file_cache_enter_disk_resource_limit_mode_percent <
1867
1.08k
        config::file_cache_exit_disk_resource_limit_mode_percent) {
1868
1
        LOG_WARNING("config error, set to default value")
1869
1
                .tag("enter", config::file_cache_enter_disk_resource_limit_mode_percent)
1870
1
                .tag("exit", config::file_cache_exit_disk_resource_limit_mode_percent);
1871
1
        config::file_cache_enter_disk_resource_limit_mode_percent = 88;
1872
1
        config::file_cache_exit_disk_resource_limit_mode_percent = 80;
1873
1
    }
1874
1.08k
    bool is_space_insufficient = is_insufficient(space_percentage);
1875
1.08k
    bool is_inode_insufficient = is_insufficient(inode_percentage);
1876
1.08k
    if (is_space_insufficient || is_inode_insufficient) {
1877
1
        _disk_resource_limit_mode = true;
1878
1
        _disk_limit_mode_metrics->set_value(1);
1879
1.08k
    } else if (_disk_resource_limit_mode &&
1880
1.08k
               (space_percentage < config::file_cache_exit_disk_resource_limit_mode_percent) &&
1881
1.08k
               (inode_percentage < config::file_cache_exit_disk_resource_limit_mode_percent)) {
1882
0
        _disk_resource_limit_mode = false;
1883
0
        _disk_limit_mode_metrics->set_value(0);
1884
0
    }
1885
1.08k
    if (previous_mode != _disk_resource_limit_mode) {
1886
        // add log for disk resource limit mode switching
1887
2
        if (_disk_resource_limit_mode) {
1888
1
            LOG(WARNING) << "Entering disk resource limit mode: file_cache=" << get_base_path()
1889
1
                         << " space_percent=" << space_percentage
1890
1
                         << " inode_percent=" << inode_percentage
1891
1
                         << " is_space_insufficient=" << is_space_insufficient
1892
1
                         << " is_inode_insufficient=" << is_inode_insufficient
1893
1
                         << " enter threshold="
1894
1
                         << config::file_cache_enter_disk_resource_limit_mode_percent;
1895
1
        } else {
1896
1
            LOG(INFO) << "Exiting disk resource limit mode: file_cache=" << get_base_path()
1897
1
                      << " space_percent=" << space_percentage
1898
1
                      << " inode_percent=" << inode_percentage << " exit threshold="
1899
1
                      << config::file_cache_exit_disk_resource_limit_mode_percent;
1900
1
        }
1901
1.07k
    } else if (_disk_resource_limit_mode) {
1902
        // print log for disk resource limit mode running, but less frequently
1903
0
        LOG_EVERY_N(WARNING, 10) << "file_cache=" << get_base_path()
1904
0
                                 << " space_percent=" << space_percentage
1905
0
                                 << " inode_percent=" << inode_percentage
1906
0
                                 << " is_space_insufficient=" << is_space_insufficient
1907
0
                                 << " is_inode_insufficient=" << is_inode_insufficient
1908
0
                                 << " mode run in resource limit";
1909
0
    }
1910
1.08k
}
1911
1912
953
void BlockFileCache::check_need_evict_cache_in_advance() {
1913
953
    if (_storage->get_type() != FileCacheStorageType::DISK) {
1914
1
        return;
1915
1
    }
1916
1917
952
    std::pair<int, int> percent;
1918
952
    int ret = disk_used_percentage(_cache_base_path, &percent);
1919
952
    if (ret != 0) {
1920
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
1921
1
        return;
1922
1
    }
1923
951
    auto [space_percentage, inode_percentage] = percent;
1924
951
    int size_percentage = static_cast<int>(_cur_cache_size * 100 / _capacity);
1925
2.85k
    auto is_insufficient = [](const int& percentage) {
1926
2.85k
        return percentage >= config::file_cache_enter_need_evict_cache_in_advance_percent;
1927
2.85k
    };
1928
951
    DCHECK_GE(space_percentage, 0);
1929
951
    DCHECK_LE(space_percentage, 100);
1930
951
    DCHECK_GE(inode_percentage, 0);
1931
951
    DCHECK_LE(inode_percentage, 100);
1932
    // ATTN: due to that can be changed dynamically, set it to default value if it's invalid
1933
    // FIXME: reject with config validator
1934
951
    if (config::file_cache_enter_need_evict_cache_in_advance_percent <=
1935
951
        config::file_cache_exit_need_evict_cache_in_advance_percent) {
1936
1
        LOG_WARNING("config error, set to default value")
1937
1
                .tag("enter", config::file_cache_enter_need_evict_cache_in_advance_percent)
1938
1
                .tag("exit", config::file_cache_exit_need_evict_cache_in_advance_percent);
1939
1
        config::file_cache_enter_need_evict_cache_in_advance_percent = 78;
1940
1
        config::file_cache_exit_need_evict_cache_in_advance_percent = 75;
1941
1
    }
1942
951
    bool previous_mode = _need_evict_cache_in_advance;
1943
951
    bool is_space_insufficient = is_insufficient(space_percentage);
1944
951
    bool is_inode_insufficient = is_insufficient(inode_percentage);
1945
951
    bool is_size_insufficient = is_insufficient(size_percentage);
1946
951
    if (is_space_insufficient || is_inode_insufficient || is_size_insufficient) {
1947
90
        _need_evict_cache_in_advance = true;
1948
90
        _need_evict_cache_in_advance_metrics->set_value(1);
1949
861
    } else if (_need_evict_cache_in_advance &&
1950
861
               (space_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
1951
861
               (inode_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
1952
861
               (size_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent)) {
1953
71
        _need_evict_cache_in_advance = false;
1954
71
        _need_evict_cache_in_advance_metrics->set_value(0);
1955
71
    }
1956
951
    if (previous_mode != _need_evict_cache_in_advance) {
1957
        // add log for evict cache in advance mode switching
1958
146
        if (_need_evict_cache_in_advance) {
1959
75
            LOG(WARNING) << "Entering evict cache in advance mode: "
1960
75
                         << "file_cache=" << get_base_path()
1961
75
                         << " space_percent=" << space_percentage
1962
75
                         << " inode_percent=" << inode_percentage
1963
75
                         << " size_percent=" << size_percentage
1964
75
                         << " is_space_insufficient=" << is_space_insufficient
1965
75
                         << " is_inode_insufficient=" << is_inode_insufficient
1966
75
                         << " is_size_insufficient=" << is_size_insufficient << " enter threshold="
1967
75
                         << config::file_cache_enter_need_evict_cache_in_advance_percent;
1968
75
        } else {
1969
71
            LOG(INFO) << "Exiting evict cache in advance mode: "
1970
71
                      << "file_cache=" << get_base_path() << " space_percent=" << space_percentage
1971
71
                      << " inode_percent=" << inode_percentage
1972
71
                      << " size_percent=" << size_percentage << " exit threshold="
1973
71
                      << config::file_cache_exit_need_evict_cache_in_advance_percent;
1974
71
        }
1975
805
    } else if (_need_evict_cache_in_advance) {
1976
        // print log for evict cache in advance mode running, but less frequently
1977
18
        LOG_EVERY_N(WARNING, 10) << "file_cache=" << get_base_path()
1978
3
                                 << " space_percent=" << space_percentage
1979
3
                                 << " inode_percent=" << inode_percentage
1980
3
                                 << " size_percent=" << size_percentage
1981
3
                                 << " is_space_insufficient=" << is_space_insufficient
1982
3
                                 << " is_inode_insufficient=" << is_inode_insufficient
1983
3
                                 << " is_size_insufficient=" << is_size_insufficient
1984
3
                                 << " need evict cache in advance";
1985
18
    }
1986
951
}
1987
1988
153
void BlockFileCache::run_background_monitor() {
1989
153
    Thread::set_self_name("run_background_monitor");
1990
1.88k
    while (!_close) {
1991
1.88k
        int64_t interval_ms = config::file_cache_background_monitor_interval_ms;
1992
1.88k
        TEST_SYNC_POINT_CALLBACK("BlockFileCache::set_sleep_time", &interval_ms);
1993
1.88k
        check_disk_resource_limit();
1994
1.88k
        if (config::enable_evict_file_cache_in_advance) {
1995
945
            check_need_evict_cache_in_advance();
1996
945
        } else {
1997
941
            _need_evict_cache_in_advance = false;
1998
941
            _need_evict_cache_in_advance_metrics->set_value(0);
1999
941
        }
2000
2001
1.88k
        {
2002
1.88k
            std::unique_lock close_lock(_close_mtx);
2003
1.88k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2004
1.88k
            if (_close) {
2005
150
                break;
2006
150
            }
2007
1.88k
        }
2008
        // report
2009
1.73k
        {
2010
1.73k
            SCOPED_CACHE_LOCK(_mutex, this);
2011
1.73k
            _cur_cache_size_metrics->set_value(_cur_cache_size);
2012
1.73k
            _cur_ttl_cache_size_metrics->set_value(_cur_cache_size -
2013
1.73k
                                                   _index_queue.get_capacity(cache_lock) -
2014
1.73k
                                                   _normal_queue.get_capacity(cache_lock) -
2015
1.73k
                                                   _disposable_queue.get_capacity(cache_lock));
2016
1.73k
            _cur_ttl_cache_lru_queue_cache_size_metrics->set_value(
2017
1.73k
                    _ttl_queue.get_capacity(cache_lock));
2018
1.73k
            _cur_ttl_cache_lru_queue_element_count_metrics->set_value(
2019
1.73k
                    _ttl_queue.get_elements_num(cache_lock));
2020
1.73k
            _cur_normal_queue_cache_size_metrics->set_value(_normal_queue.get_capacity(cache_lock));
2021
1.73k
            _cur_normal_queue_element_count_metrics->set_value(
2022
1.73k
                    _normal_queue.get_elements_num(cache_lock));
2023
1.73k
            _cur_index_queue_cache_size_metrics->set_value(_index_queue.get_capacity(cache_lock));
2024
1.73k
            _cur_index_queue_element_count_metrics->set_value(
2025
1.73k
                    _index_queue.get_elements_num(cache_lock));
2026
1.73k
            _cur_disposable_queue_cache_size_metrics->set_value(
2027
1.73k
                    _disposable_queue.get_capacity(cache_lock));
2028
1.73k
            _cur_disposable_queue_element_count_metrics->set_value(
2029
1.73k
                    _disposable_queue.get_elements_num(cache_lock));
2030
2031
            // Update meta store write queue size if storage is FSFileCacheStorage
2032
1.73k
            if (_storage->get_type() == FileCacheStorageType::DISK) {
2033
948
                auto* fs_storage = dynamic_cast<FSFileCacheStorage*>(_storage.get());
2034
948
                if (fs_storage != nullptr) {
2035
948
                    auto* meta_store = fs_storage->get_meta_store();
2036
948
                    if (meta_store != nullptr) {
2037
948
                        _meta_store_write_queue_size_metrics->set_value(
2038
948
                                meta_store->get_write_queue_size());
2039
948
                    }
2040
948
                }
2041
948
            }
2042
2043
1.73k
            if (_num_read_blocks->get_value() > 0) {
2044
686
                _hit_ratio->set_value((double)_num_hit_blocks->get_value() /
2045
686
                                      (double)_num_read_blocks->get_value());
2046
686
            }
2047
1.73k
            if (_num_read_blocks_5m && _num_read_blocks_5m->get_value() > 0) {
2048
673
                _hit_ratio_5m->set_value((double)_num_hit_blocks_5m->get_value() /
2049
673
                                         (double)_num_read_blocks_5m->get_value());
2050
673
            }
2051
1.73k
            if (_num_read_blocks_1h && _num_read_blocks_1h->get_value() > 0) {
2052
673
                _hit_ratio_1h->set_value((double)_num_hit_blocks_1h->get_value() /
2053
673
                                         (double)_num_read_blocks_1h->get_value());
2054
673
            }
2055
2056
1.73k
            if (_no_warmup_num_hit_blocks->get_value() > 0) {
2057
644
                _no_warmup_hit_ratio->set_value((double)_no_warmup_num_hit_blocks->get_value() /
2058
644
                                                (double)_no_warmup_num_read_blocks->get_value());
2059
644
            }
2060
1.73k
            if (_no_warmup_num_hit_blocks_5m && _no_warmup_num_hit_blocks_5m->get_value() > 0) {
2061
641
                _no_warmup_hit_ratio_5m->set_value(
2062
641
                        (double)_no_warmup_num_hit_blocks_5m->get_value() /
2063
641
                        (double)_no_warmup_num_read_blocks_5m->get_value());
2064
641
            }
2065
1.73k
            if (_no_warmup_num_hit_blocks_1h && _no_warmup_num_hit_blocks_1h->get_value() > 0) {
2066
641
                _no_warmup_hit_ratio_1h->set_value(
2067
641
                        (double)_no_warmup_num_hit_blocks_1h->get_value() /
2068
641
                        (double)_no_warmup_num_read_blocks_1h->get_value());
2069
641
            }
2070
1.73k
        }
2071
1.73k
    }
2072
153
}
2073
2074
153
void BlockFileCache::run_background_gc() {
2075
153
    Thread::set_self_name("run_background_gc");
2076
153
    FileCacheKey key;
2077
153
    size_t batch_count = 0;
2078
46.5k
    while (!_close) {
2079
46.5k
        int64_t interval_ms = config::file_cache_background_gc_interval_ms;
2080
46.5k
        size_t batch_limit = config::file_cache_remove_block_qps_limit * interval_ms / 1000;
2081
46.5k
        {
2082
46.5k
            std::unique_lock close_lock(_close_mtx);
2083
46.5k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2084
46.5k
            if (_close) {
2085
150
                break;
2086
150
            }
2087
46.5k
        }
2088
2089
132k
        while (batch_count < batch_limit && _recycle_keys.try_dequeue(key)) {
2090
86.1k
            int64_t duration_ns = 0;
2091
86.1k
            Status st;
2092
86.1k
            {
2093
86.1k
                SCOPED_RAW_TIMER(&duration_ns);
2094
86.1k
                st = _storage->remove(key);
2095
86.1k
            }
2096
86.1k
            *_storage_async_remove_latency_us << (duration_ns / 1000);
2097
2098
86.1k
            if (!st.ok()) {
2099
0
                LOG_WARNING("").error(st);
2100
0
            }
2101
86.1k
            batch_count++;
2102
86.1k
        }
2103
46.4k
        *_recycle_keys_length_recorder << _recycle_keys.size_approx();
2104
46.4k
        batch_count = 0;
2105
46.4k
    }
2106
153
}
2107
2108
153
void BlockFileCache::run_background_evict_in_advance() {
2109
153
    Thread::set_self_name("run_background_evict_in_advance");
2110
153
    LOG(INFO) << "Starting background evict in advance thread";
2111
153
    int64_t batch = 0;
2112
8.87k
    while (!_close) {
2113
8.86k
        {
2114
8.86k
            std::unique_lock close_lock(_close_mtx);
2115
8.86k
            _close_cv.wait_for(
2116
8.86k
                    close_lock,
2117
8.86k
                    std::chrono::milliseconds(config::file_cache_evict_in_advance_interval_ms));
2118
8.86k
            if (_close) {
2119
150
                LOG(INFO) << "Background evict in advance thread exiting due to cache closing";
2120
150
                break;
2121
150
            }
2122
8.86k
        }
2123
8.71k
        batch = config::file_cache_evict_in_advance_batch_bytes;
2124
2125
        // Skip if eviction not needed or too many pending recycles
2126
8.71k
        if (!_need_evict_cache_in_advance ||
2127
8.71k
            _recycle_keys.size_approx() >=
2128
8.33k
                    config::file_cache_evict_in_advance_recycle_keys_num_threshold) {
2129
8.33k
            continue;
2130
8.33k
        }
2131
2132
386
        int64_t duration_ns = 0;
2133
386
        {
2134
386
            SCOPED_CACHE_LOCK(_mutex, this);
2135
386
            SCOPED_RAW_TIMER(&duration_ns);
2136
386
            try_evict_in_advance(batch, cache_lock);
2137
386
        }
2138
386
        *_evict_in_advance_latency_us << (duration_ns / 1000);
2139
386
    }
2140
153
}
2141
2142
153
void BlockFileCache::run_background_block_lru_update() {
2143
153
    Thread::set_self_name("run_background_block_lru_update");
2144
153
    std::vector<FileBlockSPtr> batch;
2145
5.06k
    while (!_close) {
2146
5.06k
        int64_t interval_ms = config::file_cache_background_block_lru_update_interval_ms;
2147
5.06k
        size_t batch_limit =
2148
5.06k
                config::file_cache_background_block_lru_update_qps_limit * interval_ms / 1000;
2149
5.06k
        {
2150
5.06k
            std::unique_lock close_lock(_close_mtx);
2151
5.06k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2152
5.06k
            if (_close) {
2153
150
                break;
2154
150
            }
2155
5.06k
        }
2156
2157
4.91k
        batch.clear();
2158
4.91k
        batch.reserve(batch_limit);
2159
4.91k
        size_t drained = _need_update_lru_blocks.drain(batch_limit, &batch);
2160
4.91k
        if (drained == 0) {
2161
4.26k
            *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2162
4.26k
            continue;
2163
4.26k
        }
2164
2165
642
        int64_t duration_ns = 0;
2166
642
        {
2167
642
            SCOPED_CACHE_LOCK(_mutex, this);
2168
642
            SCOPED_RAW_TIMER(&duration_ns);
2169
139k
            for (auto& block : batch) {
2170
139k
                update_block_lru(block, cache_lock);
2171
139k
            }
2172
642
        }
2173
642
        *_update_lru_blocks_latency_us << (duration_ns / 1000);
2174
642
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2175
642
    }
2176
153
}
2177
2178
std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>>
2179
2
BlockFileCache::get_hot_blocks_meta(const UInt128Wrapper& hash) const {
2180
2
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
2181
2
                               std::chrono::steady_clock::now().time_since_epoch())
2182
2
                               .count();
2183
2
    SCOPED_CACHE_LOCK(_mutex, this);
2184
2
    std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>> blocks_meta;
2185
2
    if (auto iter = _files.find(hash); iter != _files.end()) {
2186
5
        for (auto& pair : _files.find(hash)->second) {
2187
5
            const FileBlockCell* cell = &pair.second;
2188
5
            if (cell->file_block->cache_type() != FileCacheType::DISPOSABLE) {
2189
4
                if (cell->file_block->cache_type() == FileCacheType::TTL ||
2190
4
                    (cell->atime != 0 &&
2191
3
                     cur_time - cell->atime <
2192
3
                             get_queue(cell->file_block->cache_type()).get_hot_data_interval())) {
2193
3
                    blocks_meta.emplace_back(pair.first, cell->size(),
2194
3
                                             cell->file_block->cache_type(),
2195
3
                                             cell->file_block->expiration_time());
2196
3
                }
2197
4
            }
2198
5
        }
2199
2
    }
2200
2
    return blocks_meta;
2201
2
}
2202
2203
bool BlockFileCache::try_reserve_during_async_load(size_t size,
2204
4
                                                   std::lock_guard<std::mutex>& cache_lock) {
2205
4
    size_t removed_size = 0;
2206
4
    size_t normal_queue_size = _normal_queue.get_capacity(cache_lock);
2207
4
    size_t disposable_queue_size = _disposable_queue.get_capacity(cache_lock);
2208
4
    size_t index_queue_size = _index_queue.get_capacity(cache_lock);
2209
2210
4
    std::vector<FileBlockCell*> to_evict;
2211
4
    auto collect_eliminate_fragments = [&](LRUQueue& queue) {
2212
4
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
2213
4
            if (!_disk_resource_limit_mode || removed_size >= size) {
2214
3
                break;
2215
3
            }
2216
1
            auto* cell = get_cell(entry_key, entry_offset, cache_lock);
2217
2218
1
            DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << entry_key.to_string()
2219
0
                         << ", offset: " << entry_offset;
2220
2221
1
            size_t cell_size = cell->size();
2222
1
            DCHECK(entry_size == cell_size);
2223
2224
1
            if (cell->releasable()) {
2225
1
                auto& file_block = cell->file_block;
2226
2227
1
                std::lock_guard block_lock(file_block->_mutex);
2228
1
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
2229
1
                to_evict.push_back(cell);
2230
1
                removed_size += cell_size;
2231
1
            }
2232
1
        }
2233
3
    };
2234
4
    if (disposable_queue_size != 0) {
2235
0
        collect_eliminate_fragments(get_queue(FileCacheType::DISPOSABLE));
2236
0
    }
2237
4
    if (normal_queue_size != 0) {
2238
3
        collect_eliminate_fragments(get_queue(FileCacheType::NORMAL));
2239
3
    }
2240
4
    if (index_queue_size != 0) {
2241
0
        collect_eliminate_fragments(get_queue(FileCacheType::INDEX));
2242
0
    }
2243
4
    std::string reason = "async load";
2244
4
    remove_file_blocks(to_evict, cache_lock, true, reason);
2245
2246
4
    return !_disk_resource_limit_mode || removed_size >= size;
2247
4
}
2248
2249
30
void BlockFileCache::clear_need_update_lru_blocks() {
2250
30
    _need_update_lru_blocks.clear();
2251
30
    *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2252
30
}
2253
2254
28
void BlockFileCache::pause_ttl_manager() {
2255
28
    if (_ttl_mgr) {
2256
4
        _ttl_mgr->stop();
2257
4
    }
2258
28
}
2259
2260
28
void BlockFileCache::resume_ttl_manager() {
2261
28
    if (_ttl_mgr) {
2262
4
        _ttl_mgr->resume();
2263
4
    }
2264
28
}
2265
2266
28
std::string BlockFileCache::clear_file_cache_directly() {
2267
28
    pause_ttl_manager();
2268
28
    _lru_dumper->remove_lru_dump_files();
2269
28
    using namespace std::chrono;
2270
28
    std::stringstream ss;
2271
28
    auto start = steady_clock::now();
2272
28
    std::string result;
2273
28
    {
2274
28
        SCOPED_CACHE_LOCK(_mutex, this);
2275
28
        LOG_INFO("start clear_file_cache_directly").tag("path", _cache_base_path);
2276
2277
28
        std::string clear_msg;
2278
28
        auto s = _storage->clear(clear_msg);
2279
28
        if (!s.ok()) {
2280
1
            result = clear_msg;
2281
27
        } else {
2282
27
            int64_t num_files = _files.size();
2283
27
            int64_t cache_size = _cur_cache_size;
2284
27
            int64_t index_queue_size = _index_queue.get_elements_num(cache_lock);
2285
27
            int64_t normal_queue_size = _normal_queue.get_elements_num(cache_lock);
2286
27
            int64_t disposible_queue_size = _disposable_queue.get_elements_num(cache_lock);
2287
27
            int64_t ttl_queue_size = _ttl_queue.get_elements_num(cache_lock);
2288
2289
27
            int64_t clear_fd_duration = 0;
2290
27
            {
2291
                // clear FDCache to release fd
2292
27
                SCOPED_RAW_TIMER(&clear_fd_duration);
2293
5.12k
                for (const auto& [file_key, file_blocks] : _files) {
2294
5.12k
                    for (const auto& [offset, file_block_cell] : file_blocks) {
2295
5.12k
                        AccessKeyAndOffset access_key_and_offset(file_key, offset);
2296
5.12k
                        FDCache::instance()->remove_file_reader(access_key_and_offset);
2297
5.12k
                    }
2298
5.12k
                }
2299
27
            }
2300
2301
27
            _files.clear();
2302
27
            _cur_cache_size = 0;
2303
27
            _cur_ttl_size = 0;
2304
27
            _time_to_key.clear();
2305
27
            _key_to_time.clear();
2306
27
            _index_queue.clear(cache_lock);
2307
27
            _normal_queue.clear(cache_lock);
2308
27
            _disposable_queue.clear(cache_lock);
2309
27
            _ttl_queue.clear(cache_lock);
2310
2311
            // Update cache metrics immediately so consumers observe the cleared state
2312
            // without waiting for the next background monitor round.
2313
27
            _cur_cache_size_metrics->set_value(0);
2314
27
            _cur_ttl_cache_size_metrics->set_value(0);
2315
27
            _cur_ttl_cache_lru_queue_cache_size_metrics->set_value(0);
2316
27
            _cur_ttl_cache_lru_queue_element_count_metrics->set_value(0);
2317
27
            _cur_normal_queue_cache_size_metrics->set_value(0);
2318
27
            _cur_normal_queue_element_count_metrics->set_value(0);
2319
27
            _cur_index_queue_cache_size_metrics->set_value(0);
2320
27
            _cur_index_queue_element_count_metrics->set_value(0);
2321
27
            _cur_disposable_queue_cache_size_metrics->set_value(0);
2322
27
            _cur_disposable_queue_element_count_metrics->set_value(0);
2323
2324
27
            clear_need_update_lru_blocks();
2325
2326
27
            ss << "finish clear_file_cache_directly"
2327
27
               << " path=" << _cache_base_path << " time_elapsed_ms="
2328
27
               << duration_cast<milliseconds>(steady_clock::now() - start).count()
2329
27
               << " fd_clear_time_ms=" << (clear_fd_duration / 1000000)
2330
27
               << " num_files=" << num_files << " cache_size=" << cache_size
2331
27
               << " index_queue_size=" << index_queue_size
2332
27
               << " normal_queue_size=" << normal_queue_size
2333
27
               << " disposible_queue_size=" << disposible_queue_size
2334
27
               << "ttl_queue_size=" << ttl_queue_size;
2335
27
            result = ss.str();
2336
27
            LOG(INFO) << result;
2337
27
        }
2338
28
    }
2339
28
    _lru_dumper->remove_lru_dump_files();
2340
28
    resume_ttl_manager();
2341
28
    return result;
2342
28
}
2343
2344
266k
std::map<size_t, FileBlockSPtr> BlockFileCache::get_blocks_by_key(const UInt128Wrapper& hash) {
2345
266k
    std::map<size_t, FileBlockSPtr> offset_to_block;
2346
266k
    SCOPED_CACHE_LOCK(_mutex, this);
2347
266k
    if (_files.contains(hash)) {
2348
238k
        for (auto& [offset, cell] : _files[hash]) {
2349
238k
            if (cell.file_block->state() == FileBlock::State::DOWNLOADED) {
2350
234k
                cell.file_block->_owned_by_cached_reader = true;
2351
234k
                offset_to_block.emplace(offset, cell.file_block);
2352
234k
            }
2353
238k
        }
2354
234k
    }
2355
266k
    return offset_to_block;
2356
266k
}
2357
2358
0
void BlockFileCache::update_ttl_atime(const UInt128Wrapper& hash) {
2359
0
    SCOPED_CACHE_LOCK(_mutex, this);
2360
0
    if (auto iter = _files.find(hash); iter != _files.end()) {
2361
0
        for (auto& [_, cell] : iter->second) {
2362
0
            cell.update_atime();
2363
0
        }
2364
0
    };
2365
0
}
2366
2367
153
void BlockFileCache::run_background_lru_log_replay() {
2368
153
    Thread::set_self_name("run_background_lru_log_replay");
2369
8.86k
    while (!_close) {
2370
8.86k
        int64_t interval_ms = config::file_cache_background_lru_log_replay_interval_ms;
2371
8.86k
        {
2372
8.86k
            std::unique_lock close_lock(_close_mtx);
2373
8.86k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2374
8.86k
            if (_close) {
2375
150
                break;
2376
150
            }
2377
8.86k
        }
2378
2379
8.71k
        _lru_recorder->replay_queue_event(FileCacheType::TTL);
2380
8.71k
        _lru_recorder->replay_queue_event(FileCacheType::INDEX);
2381
8.71k
        _lru_recorder->replay_queue_event(FileCacheType::NORMAL);
2382
8.71k
        _lru_recorder->replay_queue_event(FileCacheType::DISPOSABLE);
2383
2384
8.71k
        if (config::enable_evaluate_shadow_queue_diff) {
2385
0
            SCOPED_CACHE_LOCK(_mutex, this);
2386
0
            _lru_recorder->evaluate_queue_diff(_ttl_queue, "ttl", cache_lock);
2387
0
            _lru_recorder->evaluate_queue_diff(_index_queue, "index", cache_lock);
2388
0
            _lru_recorder->evaluate_queue_diff(_normal_queue, "normal", cache_lock);
2389
0
            _lru_recorder->evaluate_queue_diff(_disposable_queue, "disposable", cache_lock);
2390
0
        }
2391
8.71k
    }
2392
153
}
2393
2394
1.39k
void BlockFileCache::dump_lru_queues(bool force) {
2395
1.39k
    std::unique_lock dump_lock(_dump_lru_queues_mtx);
2396
1.39k
    if (config::file_cache_background_lru_dump_tail_record_num > 0 &&
2397
1.39k
        !ExecEnv::GetInstance()->get_is_upgrading()) {
2398
1.39k
        _lru_dumper->dump_queue("disposable", force);
2399
1.39k
        _lru_dumper->dump_queue("normal", force);
2400
1.39k
        _lru_dumper->dump_queue("index", force);
2401
1.39k
        _lru_dumper->dump_queue("ttl", force);
2402
1.39k
        _lru_dumper->set_first_dump_done();
2403
1.39k
    }
2404
1.39k
}
2405
2406
153
void BlockFileCache::run_background_lru_dump() {
2407
153
    Thread::set_self_name("run_background_lru_dump");
2408
1.55k
    while (!_close) {
2409
1.55k
        int64_t interval_ms = config::file_cache_background_lru_dump_interval_ms;
2410
1.55k
        {
2411
1.55k
            std::unique_lock close_lock(_close_mtx);
2412
1.55k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2413
1.55k
            if (_close) {
2414
150
                break;
2415
150
            }
2416
1.55k
        }
2417
1.40k
        dump_lru_queues(false);
2418
1.40k
    }
2419
153
}
2420
2421
153
void BlockFileCache::restore_lru_queues_from_disk(std::lock_guard<std::mutex>& cache_lock) {
2422
    // keep this order coz may be duplicated in different queue, we use the first appearence
2423
153
    _lru_dumper->restore_queue(_ttl_queue, "ttl", cache_lock);
2424
153
    _lru_dumper->restore_queue(_index_queue, "index", cache_lock);
2425
153
    _lru_dumper->restore_queue(_normal_queue, "normal", cache_lock);
2426
153
    _lru_dumper->restore_queue(_disposable_queue, "disposable", cache_lock);
2427
153
}
2428
2429
1
std::map<std::string, double> BlockFileCache::get_stats() {
2430
1
    std::map<std::string, double> stats;
2431
1
    stats["hits_ratio"] = (double)_hit_ratio->get_value();
2432
1
    stats["hits_ratio_5m"] = (double)_hit_ratio_5m->get_value();
2433
1
    stats["hits_ratio_1h"] = (double)_hit_ratio_1h->get_value();
2434
2435
1
    stats["index_queue_max_size"] = (double)_index_queue.get_max_size();
2436
1
    stats["index_queue_curr_size"] = (double)_cur_index_queue_cache_size_metrics->get_value();
2437
1
    stats["index_queue_max_elements"] = (double)_index_queue.get_max_element_size();
2438
1
    stats["index_queue_curr_elements"] =
2439
1
            (double)_cur_index_queue_element_count_metrics->get_value();
2440
2441
1
    stats["ttl_queue_max_size"] = (double)_ttl_queue.get_max_size();
2442
1
    stats["ttl_queue_curr_size"] = (double)_cur_ttl_cache_lru_queue_cache_size_metrics->get_value();
2443
1
    stats["ttl_queue_max_elements"] = (double)_ttl_queue.get_max_element_size();
2444
1
    stats["ttl_queue_curr_elements"] =
2445
1
            (double)_cur_ttl_cache_lru_queue_element_count_metrics->get_value();
2446
2447
1
    stats["normal_queue_max_size"] = (double)_normal_queue.get_max_size();
2448
1
    stats["normal_queue_curr_size"] = (double)_cur_normal_queue_cache_size_metrics->get_value();
2449
1
    stats["normal_queue_max_elements"] = (double)_normal_queue.get_max_element_size();
2450
1
    stats["normal_queue_curr_elements"] =
2451
1
            (double)_cur_normal_queue_element_count_metrics->get_value();
2452
2453
1
    stats["disposable_queue_max_size"] = (double)_disposable_queue.get_max_size();
2454
1
    stats["disposable_queue_curr_size"] =
2455
1
            (double)_cur_disposable_queue_cache_size_metrics->get_value();
2456
1
    stats["disposable_queue_max_elements"] = (double)_disposable_queue.get_max_element_size();
2457
1
    stats["disposable_queue_curr_elements"] =
2458
1
            (double)_cur_disposable_queue_element_count_metrics->get_value();
2459
2460
1
    stats["need_evict_cache_in_advance"] = (double)_need_evict_cache_in_advance;
2461
1
    stats["disk_resource_limit_mode"] = (double)_disk_resource_limit_mode;
2462
2463
1
    stats["total_removed_counts"] = (double)_num_removed_blocks->get_value();
2464
1
    stats["total_hit_counts"] = (double)_num_hit_blocks->get_value();
2465
1
    stats["total_read_counts"] = (double)_num_read_blocks->get_value();
2466
2467
1
    stats["total_read_size"] = (double)_total_read_size_metrics->get_value();
2468
1
    stats["total_hit_size"] = (double)_total_hit_size_metrics->get_value();
2469
1
    stats["total_removed_size"] = (double)_total_evict_size_metrics->get_value();
2470
2471
1
    return stats;
2472
1
}
2473
2474
// for be UTs
2475
172
std::map<std::string, double> BlockFileCache::get_stats_unsafe() {
2476
172
    std::map<std::string, double> stats;
2477
172
    stats["hits_ratio"] = (double)_hit_ratio->get_value();
2478
172
    stats["hits_ratio_5m"] = (double)_hit_ratio_5m->get_value();
2479
172
    stats["hits_ratio_1h"] = (double)_hit_ratio_1h->get_value();
2480
2481
172
    stats["index_queue_max_size"] = (double)_index_queue.get_max_size();
2482
172
    stats["index_queue_curr_size"] = (double)_index_queue.get_capacity_unsafe();
2483
172
    stats["index_queue_max_elements"] = (double)_index_queue.get_max_element_size();
2484
172
    stats["index_queue_curr_elements"] = (double)_index_queue.get_elements_num_unsafe();
2485
2486
172
    stats["ttl_queue_max_size"] = (double)_ttl_queue.get_max_size();
2487
172
    stats["ttl_queue_curr_size"] = (double)_ttl_queue.get_capacity_unsafe();
2488
172
    stats["ttl_queue_max_elements"] = (double)_ttl_queue.get_max_element_size();
2489
172
    stats["ttl_queue_curr_elements"] = (double)_ttl_queue.get_elements_num_unsafe();
2490
2491
172
    stats["normal_queue_max_size"] = (double)_normal_queue.get_max_size();
2492
172
    stats["normal_queue_curr_size"] = (double)_normal_queue.get_capacity_unsafe();
2493
172
    stats["normal_queue_max_elements"] = (double)_normal_queue.get_max_element_size();
2494
172
    stats["normal_queue_curr_elements"] = (double)_normal_queue.get_elements_num_unsafe();
2495
2496
172
    stats["disposable_queue_max_size"] = (double)_disposable_queue.get_max_size();
2497
172
    stats["disposable_queue_curr_size"] = (double)_disposable_queue.get_capacity_unsafe();
2498
172
    stats["disposable_queue_max_elements"] = (double)_disposable_queue.get_max_element_size();
2499
172
    stats["disposable_queue_curr_elements"] = (double)_disposable_queue.get_elements_num_unsafe();
2500
2501
172
    stats["need_evict_cache_in_advance"] = (double)_need_evict_cache_in_advance;
2502
172
    stats["disk_resource_limit_mode"] = (double)_disk_resource_limit_mode;
2503
2504
172
    stats["total_removed_counts"] = (double)_num_removed_blocks->get_value();
2505
172
    stats["total_hit_counts"] = (double)_num_hit_blocks->get_value();
2506
172
    stats["total_read_counts"] = (double)_num_read_blocks->get_value();
2507
2508
172
    stats["total_read_size"] = (double)_total_read_size_metrics->get_value();
2509
172
    stats["total_hit_size"] = (double)_total_hit_size_metrics->get_value();
2510
172
    stats["total_removed_size"] = (double)_total_evict_size_metrics->get_value();
2511
2512
172
    return stats;
2513
172
}
2514
2515
template void BlockFileCache::remove(FileBlockSPtr file_block,
2516
                                     std::lock_guard<std::mutex>& cache_lock,
2517
                                     std::lock_guard<std::mutex>& block_lock, bool sync);
2518
2519
1
Status BlockFileCache::report_file_cache_inconsistency(std::vector<std::string>& results) {
2520
1
    InconsistencyContext inconsistency_context;
2521
1
    RETURN_IF_ERROR(check_file_cache_consistency(inconsistency_context));
2522
1
    auto n = inconsistency_context.types.size();
2523
1
    results.reserve(n);
2524
1
    for (size_t i = 0; i < n; i++) {
2525
0
        std::string result;
2526
0
        result += "File cache info in manager:\n";
2527
0
        result += inconsistency_context.infos_in_manager[i].to_string();
2528
0
        result += "File cache info in storage:\n";
2529
0
        result += inconsistency_context.infos_in_storage[i].to_string();
2530
0
        result += inconsistency_context.types[i].to_string();
2531
0
        result += "\n";
2532
0
        results.push_back(std::move(result));
2533
0
    }
2534
1
    return Status::OK();
2535
1
}
2536
2537
1
Status BlockFileCache::check_file_cache_consistency(InconsistencyContext& inconsistency_context) {
2538
1
    std::lock_guard<std::mutex> cache_lock(_mutex);
2539
1
    std::vector<FileCacheInfo> infos_in_storage;
2540
1
    RETURN_IF_ERROR(_storage->get_file_cache_infos(infos_in_storage, cache_lock));
2541
1
    std::unordered_set<AccessKeyAndOffset, KeyAndOffsetHash> confirmed_blocks;
2542
1
    for (const auto& info_in_storage : infos_in_storage) {
2543
0
        confirmed_blocks.insert({info_in_storage.hash, info_in_storage.offset});
2544
0
        auto* cell = get_cell(info_in_storage.hash, info_in_storage.offset, cache_lock);
2545
0
        if (cell == nullptr || cell->file_block == nullptr) {
2546
0
            inconsistency_context.infos_in_manager.emplace_back();
2547
0
            inconsistency_context.infos_in_storage.push_back(info_in_storage);
2548
0
            inconsistency_context.types.emplace_back(InconsistencyType::NOT_LOADED);
2549
0
            continue;
2550
0
        }
2551
0
        FileCacheInfo info_in_manager {
2552
0
                .hash = info_in_storage.hash,
2553
0
                .expiration_time = cell->file_block->expiration_time(),
2554
0
                .size = cell->size(),
2555
0
                .offset = info_in_storage.offset,
2556
0
                .is_tmp = cell->file_block->state() == FileBlock::State::DOWNLOADING,
2557
0
                .cache_type = cell->file_block->cache_type()};
2558
0
        InconsistencyType inconsistent_type;
2559
0
        if (info_in_storage.is_tmp != info_in_manager.is_tmp) {
2560
0
            inconsistent_type |= InconsistencyType::TMP_FILE_EXPECT_DOWNLOADING_STATE;
2561
0
        }
2562
0
        size_t expected_size =
2563
0
                info_in_manager.is_tmp ? cell->dowloading_size() : info_in_manager.size;
2564
0
        if (info_in_storage.size != expected_size) {
2565
0
            inconsistent_type |= InconsistencyType::SIZE_INCONSISTENT;
2566
0
        }
2567
        // Only if it is not a tmp file need we check the cache type.
2568
0
        if ((inconsistent_type & InconsistencyType::TMP_FILE_EXPECT_DOWNLOADING_STATE) == 0 &&
2569
0
            info_in_storage.cache_type != info_in_manager.cache_type) {
2570
0
            inconsistent_type |= InconsistencyType::CACHE_TYPE_INCONSISTENT;
2571
0
        }
2572
0
        if (info_in_storage.expiration_time != info_in_manager.expiration_time) {
2573
0
            inconsistent_type |= InconsistencyType::EXPIRATION_TIME_INCONSISTENT;
2574
0
        }
2575
0
        if (inconsistent_type != InconsistencyType::NONE) {
2576
0
            inconsistency_context.infos_in_manager.push_back(info_in_manager);
2577
0
            inconsistency_context.infos_in_storage.push_back(info_in_storage);
2578
0
            inconsistency_context.types.push_back(inconsistent_type);
2579
0
        }
2580
0
    }
2581
2582
1
    for (const auto& [hash, offset_to_cell] : _files) {
2583
0
        for (const auto& [offset, cell] : offset_to_cell) {
2584
0
            if (confirmed_blocks.contains({hash, offset})) {
2585
0
                continue;
2586
0
            }
2587
0
            const auto& block = cell.file_block;
2588
0
            inconsistency_context.infos_in_manager.emplace_back(
2589
0
                    hash, block->expiration_time(), cell.size(), offset,
2590
0
                    cell.file_block->state() == FileBlock::State::DOWNLOADING, block->cache_type());
2591
0
            inconsistency_context.infos_in_storage.emplace_back();
2592
0
            inconsistency_context.types.emplace_back(InconsistencyType::MISSING_IN_STORAGE);
2593
0
        }
2594
0
    }
2595
1
    return Status::OK();
2596
1
}
2597
2598
} // namespace doris::io