Coverage Report

Created: 2026-06-29 14:34

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