Coverage Report

Created: 2026-07-12 14:58

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