Coverage Report

Created: 2026-06-22 22:00

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