Coverage Report

Created: 2026-06-03 00:07

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