Coverage Report

Created: 2026-06-27 16:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/block_file_cache.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Interpreters/Cache/FileCache.cpp
19
// and modified by Doris
20
21
#include "io/cache/block_file_cache.h"
22
23
#include <gen_cpp/file_cache.pb.h>
24
25
#include <cstdio>
26
#include <exception>
27
#include <fstream>
28
#include <unordered_set>
29
30
#include "common/status.h"
31
#include "cpp/sync_point.h"
32
#include "runtime/exec_env.h"
33
34
#if defined(__APPLE__)
35
#include <sys/mount.h>
36
#else
37
#include <sys/statfs.h>
38
#endif
39
40
#include <chrono> // IWYU pragma: keep
41
#include <mutex>
42
#include <ranges>
43
44
#include "common/cast_set.h"
45
#include "common/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
24.2M
bool NeedUpdateLRUBlocks::insert(FileBlockSPtr block, size_t max_queue_size) {
76
24.2M
    if (!block || max_queue_size == 0) {
77
1
        return false;
78
1
    }
79
24.2M
    bool reserved = false;
80
24.2M
    try {
81
24.2M
        auto* raw_ptr = block.get();
82
24.2M
        auto idx = shard_index(raw_ptr);
83
24.2M
        auto& shard = _shards[idx];
84
24.2M
        std::lock_guard lock(shard.mutex);
85
24.2M
        if (shard.entries.contains(raw_ptr)) {
86
24.2M
            return false;
87
24.2M
        }
88
18.4E
        size_t cur_size = _size.load(std::memory_order_relaxed);
89
18.4E
        while (cur_size < max_queue_size) {
90
170k
            if (_size.compare_exchange_weak(cur_size, cur_size + 1, std::memory_order_relaxed)) {
91
170k
                reserved = true;
92
170k
                break;
93
170k
            }
94
170k
        }
95
18.4E
        if (!reserved) {
96
1
            return false;
97
1
        }
98
18.4E
        auto [_, inserted] = shard.entries.emplace(raw_ptr, std::move(block));
99
18.4E
        DORIS_CHECK(inserted);
100
18.4E
        return true;
101
18.4E
    } 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
24.2M
}
114
115
// Drain up to `limit` unique blocks to the caller, keeping the structure consistent on failures.
116
1.17k
size_t NeedUpdateLRUBlocks::drain(size_t limit, std::vector<FileBlockSPtr>* output) {
117
1.17k
    if (limit == 0 || output == nullptr) {
118
2
        return 0;
119
2
    }
120
1.17k
    size_t drained = 0;
121
1.17k
    try {
122
1.17k
        output->reserve(output->size() + std::min(limit, size()));
123
75.2k
        for (auto& shard : _shards) {
124
75.2k
            if (drained >= limit) {
125
1
                break;
126
1
            }
127
75.2k
            std::lock_guard lock(shard.mutex);
128
75.2k
            auto it = shard.entries.begin();
129
75.2k
            size_t shard_drained = 0;
130
244k
            while (it != shard.entries.end() && drained + shard_drained < limit) {
131
169k
                output->emplace_back(std::move(it->second));
132
169k
                it = shard.entries.erase(it);
133
169k
                ++shard_drained;
134
169k
            }
135
75.2k
            if (shard_drained > 0) {
136
804
                decrease_size(shard_drained);
137
804
                drained += shard_drained;
138
804
            }
139
75.2k
        }
140
1.17k
    } 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
1.17k
    return drained;
146
1.17k
}
147
148
// Remove every pending block, guarding against unexpected exceptions.
149
26
void NeedUpdateLRUBlocks::clear() {
150
26
    try {
151
1.66k
        for (auto& shard : _shards) {
152
1.66k
            std::lock_guard lock(shard.mutex);
153
1.66k
            if (!shard.entries.empty()) {
154
2
                auto removed = shard.entries.size();
155
2
                shard.entries.clear();
156
2
                decrease_size(removed);
157
2
            }
158
1.66k
        }
159
26
    } 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
26
}
165
166
806
void NeedUpdateLRUBlocks::decrease_size(size_t delta) {
167
806
    size_t cur_size = _size.load(std::memory_order_relaxed);
168
806
    while (true) {
169
806
        DORIS_CHECK_GE(cur_size, delta);
170
806
        if (_size.compare_exchange_weak(cur_size, cur_size - delta, std::memory_order_relaxed)) {
171
806
            return;
172
806
        }
173
806
    }
174
806
}
175
176
24.2M
size_t NeedUpdateLRUBlocks::shard_index(FileBlock* ptr) const {
177
24.2M
    DCHECK(ptr != nullptr);
178
24.2M
    return std::hash<FileBlock*> {}(ptr)&kShardMask;
179
24.2M
}
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
2.04M
UInt128Wrapper BlockFileCache::hash(const std::string& path) {
444
2.04M
    uint128_t value;
445
2.04M
    sip_hash128(path.data(), path.size(), reinterpret_cast<char*>(&value));
446
2.04M
    return UInt128Wrapper(value);
447
2.04M
}
448
449
BlockFileCache::QueryFileCacheContextHolderPtr BlockFileCache::get_query_context_holder(
450
8
        const TUniqueId& query_id, int file_cache_query_limit_percent) {
451
8
    SCOPED_CACHE_LOCK(_mutex, this);
452
8
    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
7
    auto context = get_or_set_query_context(query_id, cache_lock, file_cache_query_limit_percent);
459
7
    return std::make_unique<QueryFileCacheContextHolder>(query_id, this, context);
460
8
}
461
462
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_query_context(
463
17.3k
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock) {
464
17.3k
    auto query_iter = _query_map.find(query_id);
465
17.3k
    return (query_iter == _query_map.end()) ? nullptr : query_iter->second;
466
17.3k
}
467
468
6
void BlockFileCache::remove_query_context(const TUniqueId& query_id) {
469
6
    SCOPED_CACHE_LOCK(_mutex, this);
470
6
    const auto& query_iter = _query_map.find(query_id);
471
472
6
    if (query_iter != _query_map.end() && query_iter->second.use_count() <= 1) {
473
5
        _query_map.erase(query_iter);
474
5
    }
475
6
}
476
477
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_or_set_query_context(
478
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock,
479
7
        int file_cache_query_limit_percent) {
480
7
    if (query_id.lo == 0 && query_id.hi == 0) {
481
1
        return nullptr;
482
1
    }
483
484
6
    auto context = get_query_context(query_id, cache_lock);
485
6
    if (context) {
486
1
        return context;
487
1
    }
488
489
5
    size_t file_cache_query_limit_size = _capacity * file_cache_query_limit_percent / 100;
490
5
    if (file_cache_query_limit_size < 268435456) {
491
5
        LOG(WARNING) << "The user-set file cache query limit (" << file_cache_query_limit_size
492
5
                     << " bytes) is less than the 256MB recommended minimum. "
493
5
                     << "Consider increasing the session variable 'file_cache_query_limit_percent'"
494
5
                     << " from its current value " << file_cache_query_limit_percent << "%.";
495
5
    }
496
5
    auto query_context = std::make_shared<QueryFileCacheContext>(file_cache_query_limit_size);
497
5
    auto query_iter = _query_map.emplace(query_id, query_context).first;
498
5
    return query_iter->second;
499
6
}
500
501
void BlockFileCache::QueryFileCacheContext::remove(const UInt128Wrapper& hash, size_t offset,
502
20
                                                   std::lock_guard<std::mutex>& cache_lock) {
503
20
    auto pair = std::make_pair(hash, offset);
504
20
    auto record = records.find(pair);
505
20
    DCHECK(record != records.end());
506
20
    auto iter = record->second;
507
20
    records.erase(pair);
508
20
    lru_queue.remove(iter, cache_lock);
509
20
}
510
511
void BlockFileCache::QueryFileCacheContext::reserve(const UInt128Wrapper& hash, size_t offset,
512
                                                    size_t size,
513
30
                                                    std::lock_guard<std::mutex>& cache_lock) {
514
30
    auto pair = std::make_pair(hash, offset);
515
30
    if (records.find(pair) == records.end()) {
516
29
        auto queue_iter = lru_queue.add(hash, offset, size, cache_lock);
517
29
        records.insert({pair, queue_iter});
518
29
    }
519
30
}
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
169k
                                      std::lock_guard<std::mutex>& cache_lock) {
563
169k
    if (!block) {
564
1
        return;
565
1
    }
566
567
169k
    FileBlockCell* cell = get_cell(block->get_hash_value(), block->offset(), cache_lock);
568
169k
    if (!cell || cell->file_block.get() != block.get()) {
569
785
        return;
570
785
    }
571
572
168k
    if (cell->queue_iterator) {
573
168k
        auto& queue = get_queue(block->cache_type());
574
168k
        queue.move_to_end(*cell->queue_iterator, cache_lock);
575
168k
        _lru_recorder->record_queue_event(block->cache_type(), CacheLRULogType::MOVETOBACK,
576
168k
                                          block->_key.hash, block->_key.offset,
577
168k
                                          block->_block_range.size());
578
168k
    }
579
168k
    cell->update_atime();
580
168k
}
581
582
void BlockFileCache::use_cell(const FileBlockCell& cell, FileBlocks* result, bool move_iter_flag,
583
744k
                              std::lock_guard<std::mutex>& cache_lock) {
584
744k
    if (result) {
585
744k
        result->push_back(cell.file_block);
586
744k
    }
587
588
744k
    auto& queue = get_queue(cell.file_block->cache_type());
589
    /// Move to the end of the queue. The iterator remains valid.
590
744k
    if (!config::enable_file_cache_async_touch_on_get_or_set && cell.queue_iterator &&
591
744k
        move_iter_flag) {
592
550k
        queue.move_to_end(*cell.queue_iterator, cache_lock);
593
550k
        _lru_recorder->record_queue_event(cell.file_block->cache_type(),
594
550k
                                          CacheLRULogType::MOVETOBACK, cell.file_block->_key.hash,
595
550k
                                          cell.file_block->_key.offset, cell.size());
596
550k
    }
597
598
744k
    cell.update_atime();
599
744k
}
600
601
template <class T>
602
    requires IsXLock<T>
603
FileBlockCell* BlockFileCache::get_cell(const UInt128Wrapper& hash, size_t offset,
604
11.5M
                                        T& /* cache_lock */) {
605
11.5M
    auto it = _files.find(hash);
606
11.5M
    if (it == _files.end()) {
607
281
        return nullptr;
608
281
    }
609
610
11.5M
    auto& offsets = it->second;
611
11.5M
    auto cell_it = offsets.find(offset);
612
11.5M
    if (cell_it == offsets.end()) {
613
41
        return nullptr;
614
41
    }
615
616
11.5M
    return &cell_it->second;
617
11.5M
}
618
619
936k
bool BlockFileCache::need_to_move(FileCacheType cell_type, FileCacheType query_type) const {
620
936k
    return query_type != FileCacheType::DISPOSABLE && cell_type != FileCacheType::DISPOSABLE;
621
936k
}
622
623
FileBlocks BlockFileCache::get_impl(const UInt128Wrapper& hash, const CacheContext& context,
624
                                    const FileBlock::Range& range,
625
912k
                                    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
912k
    auto it = _files.find(hash);
629
912k
    if (it == _files.end()) {
630
156k
        if (_async_open_done) {
631
156k
            return {};
632
156k
        }
633
1
        FileCacheKey key;
634
1
        key.hash = hash;
635
1
        key.meta.type = context.cache_type;
636
1
        key.meta.expiration_time = context.expiration_time;
637
1
        key.meta.tablet_id = context.tablet_id;
638
1
        _storage->load_blocks_directly_unlocked(this, key, cache_lock);
639
640
1
        it = _files.find(hash);
641
1
        if (it == _files.end()) [[unlikely]] {
642
1
            return {};
643
1
        }
644
1
    }
645
646
756k
    auto& file_blocks = it->second;
647
756k
    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
756k
    FileBlocks result;
659
756k
    auto block_it = file_blocks.lower_bound(range.left);
660
756k
    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.32k
        const auto& cell = file_blocks.rbegin()->second;
669
6.32k
        if (cell.file_block->range().right < range.left) {
670
6.30k
            return {};
671
6.30k
        }
672
673
14
        use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
674
14
                 cache_lock);
675
749k
    } else { /// block_it <-- segmment{k}
676
749k
        if (block_it != file_blocks.begin()) {
677
3.45k
            const auto& prev_cell = std::prev(block_it)->second;
678
3.45k
            const auto& prev_cell_range = prev_cell.file_block->range();
679
680
3.45k
            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
3.45k
        }
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.49M
        while (block_it != file_blocks.end()) {
700
752k
            const auto& cell = block_it->second;
701
752k
            if (range.right < cell.file_block->range().left) {
702
7.57k
                break;
703
7.57k
            }
704
705
744k
            use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
706
744k
                     cache_lock);
707
744k
            ++block_it;
708
744k
        }
709
749k
    }
710
711
749k
    return result;
712
756k
}
713
714
24.2M
void BlockFileCache::add_need_update_lru_block(FileBlockSPtr block) {
715
24.2M
    int64_t queue_limit = config::file_cache_background_block_lru_update_queue_max_size;
716
24.2M
    size_t max_queue_size = queue_limit <= 0 ? 0 : static_cast<size_t>(queue_limit);
717
24.2M
    if (_need_update_lru_blocks.insert(std::move(block), max_queue_size)) {
718
170k
        *_need_update_lru_blocks_produce_metrics << 1;
719
170k
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
720
170k
    }
721
24.2M
}
722
723
4
std::string BlockFileCache::clear_file_cache_async() {
724
4
    return clear_file_cache_impl(false);
725
4
}
726
727
20
std::string BlockFileCache::clear_file_cache_sync() {
728
20
    return clear_file_cache_impl(true);
729
20
}
730
731
24
std::string BlockFileCache::clear_file_cache_impl(bool sync_remove) {
732
24
    const char* action = sync_remove ? "clear_file_cache_sync" : "clear_file_cache_async";
733
24
    LOG(INFO) << "start " << action << ", path=" << _cache_base_path;
734
24
    _lru_dumper->remove_lru_dump_files();
735
24
    int64_t num_cells_all = 0;
736
24
    int64_t num_cells_to_delete = 0;
737
24
    int64_t num_cells_wait_recycle = 0;
738
24
    int64_t num_files_all = 0;
739
24
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::clear_file_cache_async");
740
24
    {
741
24
        SCOPED_CACHE_LOCK(_mutex, this);
742
743
24
        std::vector<FileBlockCell*> deleting_cells;
744
5.13k
        for (auto& [_, offset_to_cell] : _files) {
745
5.13k
            ++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.13k
        }
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
24
        clear_need_update_lru_blocks();
773
24
    }
774
775
24
    std::stringstream ss;
776
24
    ss << "finish " << action << ", path=" << _cache_base_path << " sync_remove=" << sync_remove
777
24
       << " num_files_all=" << num_files_all << " num_cells_all=" << num_cells_all
778
24
       << " num_cells_to_delete=" << num_cells_to_delete
779
24
       << " num_cells_wait_recycle=" << num_cells_wait_recycle;
780
24
    auto msg = ss.str();
781
24
    LOG(INFO) << msg;
782
24
    _lru_dumper->remove_lru_dump_files();
783
24
    return msg;
784
24
}
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
170k
                                                  std::lock_guard<std::mutex>& cache_lock) {
790
170k
    DCHECK(size > 0);
791
792
170k
    auto current_pos = offset;
793
170k
    auto end_pos_non_included = offset + size;
794
795
170k
    size_t current_size = 0;
796
170k
    size_t remaining_size = size;
797
798
170k
    FileBlocks file_blocks;
799
373k
    while (current_pos < end_pos_non_included) {
800
202k
        current_size = std::min(remaining_size, _max_file_block_size);
801
202k
        remaining_size -= current_size;
802
202k
        state = try_reserve(hash, context, current_pos, current_size, cache_lock)
803
202k
                        ? state
804
202k
                        : FileBlock::State::SKIP_CACHE;
805
202k
        if (state == FileBlock::State::SKIP_CACHE) [[unlikely]] {
806
59.2k
            FileCacheKey key;
807
59.2k
            key.hash = hash;
808
59.2k
            key.offset = current_pos;
809
59.2k
            key.meta.type = context.cache_type;
810
59.2k
            key.meta.expiration_time = context.expiration_time;
811
59.2k
            key.meta.tablet_id = context.tablet_id;
812
59.2k
            auto file_block = std::make_shared<FileBlock>(key, current_size, this,
813
59.2k
                                                          FileBlock::State::SKIP_CACHE);
814
59.2k
            file_blocks.push_back(std::move(file_block));
815
143k
        } else {
816
143k
            auto* cell = add_cell(hash, context, current_pos, current_size, state, cache_lock);
817
143k
            if (cell) {
818
143k
                file_blocks.push_back(cell->file_block);
819
143k
                if (!context.is_cold_data) {
820
143k
                    cell->update_atime();
821
143k
                }
822
143k
            }
823
143k
            if (_ttl_mgr && context.tablet_id != 0) {
824
131k
                _ttl_mgr->register_tablet_id(context.tablet_id);
825
131k
            }
826
143k
        }
827
828
202k
        current_pos += current_size;
829
202k
    }
830
831
170k
    DCHECK(file_blocks.empty() || offset + size - 1 == file_blocks.back()->range().right);
832
170k
    return file_blocks;
833
170k
}
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
743k
                                                       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
743k
    auto it = file_blocks.begin();
851
743k
    auto block_range = (*it)->range();
852
853
743k
    size_t current_pos = 0;
854
743k
    if (block_range.left < range.left) {
855
        ///    [_______     -- requested range
856
        /// [_______
857
        /// ^
858
        /// block1
859
860
151
        current_pos = block_range.right + 1;
861
151
        ++it;
862
743k
    } else {
863
743k
        current_pos = range.left;
864
743k
    }
865
866
1.48M
    while (current_pos <= range.right && it != file_blocks.end()) {
867
744k
        block_range = (*it)->range();
868
869
744k
        if (current_pos == block_range.left) {
870
744k
            current_pos = block_range.right + 1;
871
744k
            ++it;
872
744k
            continue;
873
744k
        }
874
875
744k
        DCHECK(current_pos < block_range.left);
876
877
146
        auto hole_size = block_range.left - current_pos;
878
879
146
        file_blocks.splice(it, split_range_into_cells(hash, context, current_pos, hole_size,
880
146
                                                      FileBlock::State::EMPTY, cache_lock));
881
882
146
        current_pos = block_range.right + 1;
883
146
        ++it;
884
146
    }
885
886
743k
    if (current_pos <= range.right) {
887
        ///   ________]     -- requested range
888
        ///   _____]
889
        ///        ^
890
        /// blockN
891
892
1.45k
        auto hole_size = range.right - current_pos + 1;
893
894
1.45k
        file_blocks.splice(file_blocks.end(),
895
1.45k
                           split_range_into_cells(hash, context, current_pos, hole_size,
896
1.45k
                                                  FileBlock::State::EMPTY, cache_lock));
897
1.45k
    }
898
743k
}
899
900
FileBlocksHolder BlockFileCache::get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
901
912k
                                            CacheContext& context) {
902
912k
    FileBlock::Range range(offset, offset + size - 1);
903
904
912k
    ReadStatistics* stats = context.stats;
905
912k
    DCHECK(stats != nullptr);
906
912k
    MonotonicStopWatch sw;
907
912k
    sw.start();
908
912k
    FileBlocks file_blocks;
909
912k
    std::vector<FileBlockSPtr> need_update_lru_blocks;
910
912k
    const bool async_touch_on_get_or_set = config::enable_file_cache_async_touch_on_get_or_set;
911
912k
    int64_t duration = 0;
912
912k
    {
913
912k
        ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->increment();
914
912k
        std::lock_guard cache_lock(_mutex);
915
912k
        ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->decrement();
916
912k
        stats->lock_wait_timer += sw.elapsed_time();
917
912k
        SCOPED_RAW_TIMER(&duration);
918
        /// Get all blocks which intersect with the given range.
919
912k
        {
920
912k
            SCOPED_RAW_TIMER(&stats->get_timer);
921
912k
            file_blocks = get_impl(hash, context, range, cache_lock);
922
912k
        }
923
924
912k
        if (file_blocks.empty()) {
925
168k
            SCOPED_RAW_TIMER(&stats->set_timer);
926
168k
            file_blocks = split_range_into_cells(hash, context, offset, size,
927
168k
                                                 FileBlock::State::EMPTY, cache_lock);
928
743k
        } else {
929
743k
            SCOPED_RAW_TIMER(&stats->set_timer);
930
743k
            fill_holes_with_empty_file_blocks(file_blocks, hash, context, range, cache_lock);
931
743k
        }
932
912k
        DCHECK(!file_blocks.empty());
933
912k
        *_num_read_blocks << file_blocks.size();
934
912k
        if (!context.is_warmup) {
935
911k
            *_no_warmup_num_read_blocks << file_blocks.size();
936
911k
        }
937
912k
        if (async_touch_on_get_or_set) {
938
193k
            need_update_lru_blocks.reserve(file_blocks.size());
939
193k
        }
940
947k
        for (auto& block : file_blocks) {
941
947k
            size_t block_size = block->range().size();
942
947k
            *_total_read_size_metrics << block_size;
943
947k
            if (block->state_unsafe() == FileBlock::State::DOWNLOADED) {
944
738k
                *_num_hit_blocks << 1;
945
738k
                *_total_hit_size_metrics << block_size;
946
738k
                if (!context.is_warmup) {
947
738k
                    *_no_warmup_num_hit_blocks << 1;
948
738k
                }
949
738k
                if (async_touch_on_get_or_set &&
950
738k
                    need_to_move(block->cache_type(), context.cache_type)) {
951
192k
                    need_update_lru_blocks.emplace_back(block);
952
192k
                }
953
738k
            }
954
947k
        }
955
912k
    }
956
957
912k
    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
912k
    *_get_or_set_latency_us << (duration / 1000);
964
912k
    return FileBlocksHolder(std::move(file_blocks));
965
912k
}
966
967
FileBlockCell* BlockFileCache::add_cell(const UInt128Wrapper& hash, const CacheContext& context,
968
                                        size_t offset, size_t size, FileBlock::State state,
969
243k
                                        std::lock_guard<std::mutex>& cache_lock) {
970
    /// Create a file block cell and put it in `files` map by [hash][offset].
971
243k
    if (size == 0) {
972
0
        return nullptr; /// Empty files are not cached.
973
0
    }
974
975
243k
    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
243k
    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
243k
    auto& offsets = _files[hash];
988
243k
    auto itr = offsets.find(offset);
989
243k
    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
243k
    FileCacheKey key;
997
243k
    key.hash = hash;
998
243k
    key.offset = offset;
999
243k
    key.meta.type = context.cache_type;
1000
243k
    key.meta.expiration_time = context.expiration_time;
1001
243k
    key.meta.tablet_id = context.tablet_id;
1002
243k
    FileBlockCell cell(std::make_shared<FileBlock>(key, size, this, state), cache_lock);
1003
243k
    Status st;
1004
243k
    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
243k
    } 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
243k
    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
243k
    auto& queue = get_queue(cell.file_block->cache_type());
1016
243k
    cell.queue_iterator = queue.add(hash, offset, size, cache_lock);
1017
243k
    _lru_recorder->record_queue_event(cell.file_block->cache_type(), CacheLRULogType::ADD,
1018
243k
                                      cell.file_block->get_hash_value(), cell.file_block->offset(),
1019
243k
                                      cell.size());
1020
1021
243k
    if (cell.file_block->cache_type() == FileCacheType::TTL) {
1022
3.92k
        _cur_ttl_size += cell.size();
1023
3.92k
    }
1024
243k
    auto [it, _] = offsets.insert(std::make_pair(offset, std::move(cell)));
1025
243k
    _cur_cache_size += size;
1026
243k
    return &(it->second);
1027
243k
}
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
1.94M
LRUQueue& BlockFileCache::get_queue(FileCacheType type) {
1057
1.94M
    switch (type) {
1058
347k
    case FileCacheType::INDEX:
1059
347k
        return _index_queue;
1060
210k
    case FileCacheType::DISPOSABLE:
1061
210k
        return _disposable_queue;
1062
1.37M
    case FileCacheType::NORMAL:
1063
1.37M
        return _normal_queue;
1064
7.82k
    case FileCacheType::TTL:
1065
7.82k
        return _ttl_queue;
1066
0
    default:
1067
0
        DCHECK(false);
1068
1.94M
    }
1069
0
    return _normal_queue;
1070
1.94M
}
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
380k
                                        std::string& reason) {
1091
380k
    auto remove_file_block_if = [&](FileBlockCell* cell) {
1092
107k
        FileBlockSPtr file_block = cell->file_block;
1093
107k
        if (file_block) {
1094
107k
            std::lock_guard block_lock(file_block->_mutex);
1095
107k
            remove(file_block, cache_lock, block_lock, sync);
1096
107k
            VLOG_DEBUG << "remove_file_blocks"
1097
0
                       << " hash=" << file_block->get_hash_value().to_string()
1098
0
                       << " offset=" << file_block->offset() << " reason=" << reason;
1099
107k
        }
1100
107k
    };
1101
380k
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1102
380k
}
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
64.7k
                                           size_t& cur_removed_size, bool evict_in_advance) {
1109
11.0M
    for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1110
11.0M
        if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1111
3.38k
            break;
1112
3.38k
        }
1113
11.0M
        auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1114
1115
11.0M
        DCHECK(cell) << "Cache became inconsistent. key: " << entry_key.to_string()
1116
0
                     << ", offset: " << entry_offset;
1117
1118
11.0M
        size_t cell_size = cell->size();
1119
11.0M
        DCHECK(entry_size == cell_size);
1120
1121
11.0M
        if (cell->releasable()) {
1122
106k
            auto& file_block = cell->file_block;
1123
1124
106k
            std::lock_guard block_lock(file_block->_mutex);
1125
106k
            DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1126
106k
            to_evict.push_back(cell);
1127
106k
            removed_size += cell_size;
1128
106k
            cur_removed_size += cell_size;
1129
106k
        }
1130
11.0M
    }
1131
64.7k
}
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
202k
                                 std::lock_guard<std::mutex>& cache_lock) {
1147
202k
    if (!_async_open_done) {
1148
4
        return try_reserve_during_async_load(size, cache_lock);
1149
4
    }
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
202k
    if (_disk_resource_limit_mode) {
1153
1
        size = 5 * size;
1154
1
    }
1155
1156
202k
    auto query_context = config::enable_file_cache_query_limit &&
1157
202k
                                         (context.query_id.hi != 0 || context.query_id.lo != 0)
1158
202k
                                 ? get_query_context(context.query_id, cache_lock)
1159
202k
                                 : nullptr;
1160
202k
    if (!query_context) {
1161
202k
        return try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock);
1162
202k
    } else if (query_context->get_cache_size(cache_lock) + size <=
1163
31
               query_context->get_max_cache_size()) {
1164
16
        return try_reserve_for_lru(hash, query_context, context, offset, size, cache_lock);
1165
16
    }
1166
15
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1167
15
                               std::chrono::steady_clock::now().time_since_epoch())
1168
15
                               .count();
1169
15
    auto& queue = get_queue(context.cache_type);
1170
15
    size_t removed_size = 0;
1171
15
    size_t ghost_remove_size = 0;
1172
15
    size_t queue_size = queue.get_capacity(cache_lock);
1173
15
    size_t cur_cache_size = _cur_cache_size;
1174
15
    size_t query_context_cache_size = query_context->get_cache_size(cache_lock);
1175
1176
15
    std::vector<LRUQueue::Iterator> ghost;
1177
15
    std::vector<FileBlockCell*> to_evict;
1178
1179
15
    size_t max_size = queue.get_max_size();
1180
48
    auto is_overflow = [&] {
1181
48
        return _disk_resource_limit_mode ? removed_size < size
1182
48
                                         : cur_cache_size + size - removed_size > _capacity ||
1183
48
                                                   (queue_size + size - removed_size > max_size) ||
1184
48
                                                   (query_context_cache_size + size -
1185
38
                                                            (removed_size + ghost_remove_size) >
1186
38
                                                    query_context->get_max_cache_size());
1187
48
    };
1188
1189
    /// Select the cache from the LRU queue held by query for expulsion.
1190
35
    for (auto iter = query_context->queue().begin(); iter != query_context->queue().end(); iter++) {
1191
33
        if (!is_overflow()) {
1192
13
            break;
1193
13
        }
1194
1195
20
        auto* cell = get_cell(iter->hash, iter->offset, cache_lock);
1196
1197
20
        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
16
        } else {
1203
16
            size_t cell_size = cell->size();
1204
16
            DCHECK(iter->size == cell_size);
1205
1206
16
            if (cell->releasable()) {
1207
16
                auto& file_block = cell->file_block;
1208
1209
16
                std::lock_guard block_lock(file_block->_mutex);
1210
16
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1211
16
                to_evict.push_back(cell);
1212
16
                removed_size += cell_size;
1213
16
            }
1214
16
        }
1215
20
    }
1216
1217
16
    auto remove_file_block_if = [&](FileBlockCell* cell) {
1218
16
        FileBlockSPtr file_block = cell->file_block;
1219
16
        if (file_block) {
1220
16
            query_context->remove(file_block->get_hash_value(), file_block->offset(), cache_lock);
1221
16
            std::lock_guard block_lock(file_block->_mutex);
1222
16
            remove(file_block, cache_lock, block_lock);
1223
16
        }
1224
16
    };
1225
1226
15
    for (auto& iter : ghost) {
1227
4
        query_context->remove(iter->hash, iter->offset, cache_lock);
1228
4
    }
1229
1230
15
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1231
1232
15
    if (is_overflow() &&
1233
15
        !try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock)) {
1234
1
        return false;
1235
1
    }
1236
14
    query_context->reserve(hash, offset, size, cache_lock);
1237
14
    return true;
1238
15
}
1239
1240
471
void BlockFileCache::try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock) {
1241
471
    UInt128Wrapper hash = UInt128Wrapper();
1242
471
    size_t offset = 0;
1243
471
    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
471
    context.cache_type = FileCacheType::NORMAL;
1251
471
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1252
471
    context.cache_type = FileCacheType::TTL;
1253
471
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1254
471
}
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
112k
void BlockFileCache::remove_if_cached_async(const UInt128Wrapper& file_key) {
1279
112k
    std::string reason = "remove_if_cached_async";
1280
112k
    SCOPED_CACHE_LOCK(_mutex, this);
1281
1282
112k
    auto iter = _files.find(file_key);
1283
112k
    std::vector<FileBlockCell*> to_remove;
1284
112k
    if (iter != _files.end()) {
1285
24.7k
        for (auto& [_, cell] : iter->second) {
1286
24.7k
            *_gc_evict_bytes_metrics << cell.size();
1287
24.7k
            *_gc_evict_count_metrics << 1;
1288
24.7k
            if (cell.releasable()) {
1289
721
                to_remove.push_back(&cell);
1290
24.0k
            } else {
1291
24.0k
                cell.file_block->set_deleting();
1292
24.0k
            }
1293
24.7k
        }
1294
19.4k
    }
1295
112k
    remove_file_blocks(to_remove, cache_lock, false, reason);
1296
112k
}
1297
1298
std::vector<FileCacheType> BlockFileCache::get_other_cache_type_without_ttl(
1299
203k
        FileCacheType cur_cache_type) {
1300
203k
    switch (cur_cache_type) {
1301
4.38k
    case FileCacheType::TTL:
1302
4.38k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1303
72.3k
    case FileCacheType::INDEX:
1304
72.3k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL};
1305
124k
    case FileCacheType::NORMAL:
1306
124k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX};
1307
2.84k
    case FileCacheType::DISPOSABLE:
1308
2.84k
        return {FileCacheType::NORMAL, FileCacheType::INDEX};
1309
0
    default:
1310
0
        return {};
1311
203k
    }
1312
0
    return {};
1313
203k
}
1314
1315
62.8k
std::vector<FileCacheType> BlockFileCache::get_other_cache_type(FileCacheType cur_cache_type) {
1316
62.8k
    switch (cur_cache_type) {
1317
753
    case FileCacheType::TTL:
1318
753
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1319
38.5k
    case FileCacheType::INDEX:
1320
38.5k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::TTL};
1321
22.0k
    case FileCacheType::NORMAL:
1322
22.0k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX, FileCacheType::TTL};
1323
1.57k
    case FileCacheType::DISPOSABLE:
1324
1.57k
        return {FileCacheType::NORMAL, FileCacheType::INDEX, FileCacheType::TTL};
1325
0
    default:
1326
0
        return {};
1327
62.8k
    }
1328
0
    return {};
1329
62.8k
}
1330
1331
void BlockFileCache::reset_range(const UInt128Wrapper& hash, size_t offset, size_t old_size,
1332
5.97k
                                 size_t new_size, std::lock_guard<std::mutex>& cache_lock) {
1333
5.97k
    DCHECK(_files.find(hash) != _files.end() &&
1334
5.97k
           _files.find(hash)->second.find(offset) != _files.find(hash)->second.end());
1335
5.97k
    FileBlockCell* cell = get_cell(hash, offset, cache_lock);
1336
5.97k
    DCHECK(cell != nullptr);
1337
5.97k
    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
5.97k
    DCHECK_EQ(cell->file_block->_block_range.size(), old_size);
1344
5.97k
    if (cell->queue_iterator) {
1345
5.97k
        auto& queue = get_queue(cell->file_block->cache_type());
1346
5.97k
        DCHECK(queue.contains(hash, offset, cache_lock));
1347
5.97k
        queue.resize(*cell->queue_iterator, new_size, cache_lock);
1348
5.97k
        _lru_recorder->record_queue_event(cell->file_block->cache_type(), CacheLRULogType::RESIZE,
1349
5.97k
                                          cell->file_block->get_hash_value(),
1350
5.97k
                                          cell->file_block->offset(), new_size);
1351
5.97k
    }
1352
5.97k
    cell->file_block->_block_range.right = cell->file_block->_block_range.left + new_size - 1;
1353
5.97k
    _cur_cache_size -= old_size;
1354
5.97k
    _cur_cache_size += new_size;
1355
5.97k
    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
5.97k
}
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
203k
        int64_t cur_time, std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1364
203k
    size_t removed_size = 0;
1365
203k
    size_t cur_cache_size = _cur_cache_size;
1366
203k
    std::vector<FileBlockCell*> to_evict;
1367
411k
    for (FileCacheType cache_type : other_cache_types) {
1368
411k
        auto& queue = get_queue(cache_type);
1369
411k
        size_t remove_size_per_type = 0;
1370
411k
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1371
376k
            if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1372
252k
                break;
1373
252k
            }
1374
124k
            auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1375
124k
            DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << entry_key.to_string()
1376
0
                         << ", offset: " << entry_offset;
1377
1378
124k
            size_t cell_size = cell->size();
1379
124k
            DCHECK(entry_size == cell_size);
1380
1381
124k
            if (cell->atime == 0 ? true : cell->atime + queue.get_hot_data_interval() > cur_time) {
1382
124k
                break;
1383
124k
            }
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
411k
        *(_evict_by_time_metrics_matrix[cache_type][cur_type]) << remove_size_per_type;
1395
411k
    }
1396
203k
    bool is_sync_removal = !evict_in_advance;
1397
203k
    std::string reason = std::string("try_reserve_by_time ") +
1398
203k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1399
203k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1400
1401
203k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1402
203k
}
1403
1404
bool BlockFileCache::is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
1405
11.6M
                                 bool evict_in_advance) const {
1406
11.6M
    bool ret = false;
1407
11.6M
    if (evict_in_advance) { // we don't need to check _need_evict_cache_in_advance
1408
338k
        ret = (removed_size < need_size);
1409
338k
        return ret;
1410
338k
    }
1411
11.3M
    if (_disk_resource_limit_mode) {
1412
4
        ret = (removed_size < need_size);
1413
11.3M
    } else {
1414
11.3M
        ret = (cur_cache_size + need_size - removed_size > _capacity);
1415
11.3M
    }
1416
11.3M
    return ret;
1417
11.6M
}
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.00k
        std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1422
2.00k
    size_t removed_size = 0;
1423
2.00k
    size_t cur_cache_size = _cur_cache_size;
1424
2.00k
    std::vector<FileBlockCell*> to_evict;
1425
    // we follow the privilege defined in get_other_cache_types to evict
1426
6.00k
    for (FileCacheType cache_type : other_cache_types) {
1427
6.00k
        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.00k
        size_t cur_queue_size = queue.get_capacity(cache_lock);
1432
6.00k
        size_t cur_queue_max_size = queue.get_max_size();
1433
6.00k
        if (cur_queue_size <= cur_queue_max_size) {
1434
3.54k
            continue;
1435
3.54k
        }
1436
2.46k
        size_t cur_removed_size = 0;
1437
2.46k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1438
2.46k
                              cur_removed_size, evict_in_advance);
1439
2.46k
        *(_evict_by_size_metrics_matrix[cache_type][cur_type]) << cur_removed_size;
1440
2.46k
    }
1441
2.00k
    bool is_sync_removal = !evict_in_advance;
1442
2.00k
    std::string reason = std::string("try_reserve_by_size") +
1443
2.00k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1444
2.00k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1445
2.00k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1446
2.00k
}
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
203k
                                                  bool evict_in_advance) {
1452
    // currently, TTL cache is not considered as a candidate
1453
203k
    auto other_cache_types = get_other_cache_type_without_ttl(cur_cache_type);
1454
203k
    bool reserve_success = try_reserve_from_other_queue_by_time_interval(
1455
203k
            cur_cache_type, other_cache_types, size, cur_time, cache_lock, evict_in_advance);
1456
203k
    if (reserve_success || !config::file_cache_enable_evict_from_other_queue_by_size) {
1457
140k
        return reserve_success;
1458
140k
    }
1459
1460
62.8k
    other_cache_types = get_other_cache_type(cur_cache_type);
1461
62.8k
    auto& cur_queue = get_queue(cur_cache_type);
1462
62.8k
    size_t cur_queue_size = cur_queue.get_capacity(cache_lock);
1463
62.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
62.8k
    if (_cur_cache_size + size > _capacity && cur_queue_size + size > cur_queue_max_size) {
1466
60.8k
        return false;
1467
60.8k
    }
1468
2.00k
    return try_reserve_from_other_queue_by_size(cur_cache_type, other_cache_types, size, cache_lock,
1469
2.00k
                                                evict_in_advance);
1470
62.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
203k
                                         bool evict_in_advance) {
1477
203k
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1478
203k
                               std::chrono::steady_clock::now().time_since_epoch())
1479
203k
                               .count();
1480
203k
    if (!try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock,
1481
203k
                                      evict_in_advance)) {
1482
62.2k
        auto& queue = get_queue(context.cache_type);
1483
62.2k
        size_t removed_size = 0;
1484
62.2k
        size_t cur_cache_size = _cur_cache_size;
1485
1486
62.2k
        std::vector<FileBlockCell*> to_evict;
1487
62.2k
        size_t cur_removed_size = 0;
1488
62.2k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1489
62.2k
                              cur_removed_size, evict_in_advance);
1490
62.2k
        bool is_sync_removal = !evict_in_advance;
1491
62.2k
        std::string reason = std::string("try_reserve for cache type ") +
1492
62.2k
                             cache_type_to_string(context.cache_type) +
1493
62.2k
                             " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1494
62.2k
        remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1495
62.2k
        *(_evict_by_self_lru_metrics_matrix[context.cache_type]) << cur_removed_size;
1496
1497
62.2k
        if (is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1498
59.3k
            return false;
1499
59.3k
        }
1500
62.2k
    }
1501
1502
144k
    if (query_context) {
1503
16
        query_context->reserve(hash, offset, size, cache_lock);
1504
16
    }
1505
144k
    return true;
1506
203k
}
1507
1508
template <class T, class U>
1509
    requires IsXLock<T> && IsXLock<U>
1510
237k
void BlockFileCache::remove(FileBlockSPtr file_block, T& cache_lock, U& block_lock, bool sync) {
1511
237k
    auto hash = file_block->get_hash_value();
1512
237k
    auto offset = file_block->offset();
1513
237k
    auto type = file_block->cache_type();
1514
237k
    auto expiration_time = file_block->expiration_time();
1515
237k
    auto tablet_id = file_block->tablet_id();
1516
237k
    auto* cell = get_cell(hash, offset, cache_lock);
1517
237k
    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
237k
    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
237k
    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
237k
    DCHECK(cell->queue_iterator);
1550
237k
    if (cell->queue_iterator) {
1551
237k
        auto& queue = get_queue(file_block->cache_type());
1552
237k
        queue.remove(*cell->queue_iterator, cache_lock);
1553
237k
        _lru_recorder->record_queue_event(file_block->cache_type(), CacheLRULogType::REMOVE,
1554
237k
                                          cell->file_block->get_hash_value(),
1555
237k
                                          cell->file_block->offset(), cell->size());
1556
237k
    }
1557
237k
    *_queue_evict_size_metrics[static_cast<int>(file_block->cache_type())]
1558
237k
            << file_block->range().size();
1559
237k
    *_total_evict_size_metrics << file_block->range().size();
1560
1561
237k
    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
237k
    if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADED) {
1566
212k
        FileCacheKey key;
1567
212k
        key.hash = hash;
1568
212k
        key.offset = offset;
1569
212k
        key.meta.type = type;
1570
212k
        key.meta.expiration_time = expiration_time;
1571
212k
        key.meta.tablet_id = tablet_id;
1572
212k
        if (sync) {
1573
118k
            int64_t duration_ns = 0;
1574
118k
            Status st;
1575
118k
            {
1576
118k
                SCOPED_RAW_TIMER(&duration_ns);
1577
118k
                st = _storage->remove(key);
1578
118k
            }
1579
118k
            *_storage_sync_remove_latency_us << (duration_ns / 1000);
1580
118k
            if (!st.ok()) {
1581
0
                LOG_WARNING("").error(st);
1582
0
            }
1583
118k
        } 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
93.2k
            bool ret = _recycle_keys.enqueue(key);
1588
93.2k
            if (ret) [[likely]] {
1589
93.2k
                *_recycle_keys_length_recorder << _recycle_keys.size_approx();
1590
93.2k
            } 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
93.2k
        }
1604
212k
    } else if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADING) {
1605
100
        file_block->set_deleting();
1606
100
        return;
1607
100
    }
1608
237k
    _cur_cache_size -= file_block->range().size();
1609
237k
    if (FileCacheType::TTL == type) {
1610
1.29k
        _cur_ttl_size -= file_block->range().size();
1611
1.29k
    }
1612
237k
    auto it = _files.find(hash);
1613
237k
    if (it != _files.end()) {
1614
237k
        it->second.erase(file_block->offset());
1615
237k
        if (it->second.empty()) {
1616
109k
            _files.erase(hash);
1617
109k
        }
1618
237k
    }
1619
237k
    *_num_removed_blocks << 1;
1620
237k
}
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
243k
        : file_block(file_block) {
1655
243k
    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
243k
    switch (file_block->_download_state) {
1663
100k
    case FileBlock::State::DOWNLOADED:
1664
243k
    case FileBlock::State::EMPTY:
1665
243k
    case FileBlock::State::SKIP_CACHE: {
1666
243k
        break;
1667
243k
    }
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
243k
    }
1672
243k
    if (file_block->cache_type() == FileCacheType::TTL) {
1673
3.92k
        update_atime();
1674
3.92k
    }
1675
243k
}
1676
1677
LRUQueue::Iterator LRUQueue::add(const UInt128Wrapper& hash, size_t offset, size_t size,
1678
486k
                                 std::lock_guard<std::mutex>& /* cache_lock */) {
1679
486k
    cache_size += size;
1680
486k
    auto iter = queue.insert(queue.end(), FileKeyAndOffset(hash, offset, size));
1681
486k
    map.insert(std::make_pair(std::make_pair(hash, offset), iter));
1682
486k
    return iter;
1683
486k
}
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.42M
void LRUQueue::move_to_end(Iterator queue_it, std::lock_guard<std::mutex>& /* cache_lock */) {
1703
1.42M
    queue.splice(queue.end(), queue, queue_it);
1704
1.42M
}
1705
1706
void LRUQueue::resize(Iterator queue_it, size_t new_size,
1707
11.9k
                      std::lock_guard<std::mutex>& /* cache_lock */) {
1708
11.9k
    cache_size -= queue_it->size;
1709
11.9k
    queue_it->size = new_size;
1710
11.9k
    cache_size += new_size;
1711
11.9k
}
1712
bool LRUQueue::contains(const UInt128Wrapper& hash, size_t offset,
1713
5.97k
                        std::lock_guard<std::mutex>& /* cache_lock */) const {
1714
5.97k
    return map.find(std::make_pair(hash, offset)) != map.end();
1715
5.97k
}
1716
1717
LRUQueue::Iterator LRUQueue::get(const UInt128Wrapper& hash, size_t offset,
1718
962k
                                 std::lock_guard<std::mutex>& /* cache_lock */) const {
1719
962k
    auto itr = map.find(std::make_pair(hash, offset));
1720
962k
    if (itr != map.end()) {
1721
960k
        return itr->second;
1722
960k
    }
1723
1.99k
    return std::list<FileKeyAndOffset>::iterator();
1724
962k
}
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
43
                                       std::lock_guard<std::mutex>& cache_lock) {
1823
43
    if (auto iter = _files.find(hash); iter != _files.end()) {
1824
43
        auto& file_blocks = iter->second;
1825
43
        if (auto cell_it = file_blocks.find(offset); cell_it != file_blocks.end()) {
1826
42
            FileBlockCell& cell = cell_it->second;
1827
42
            auto& cur_queue = get_queue(cell.file_block->cache_type());
1828
42
            DCHECK(cell.queue_iterator.has_value());
1829
42
            cur_queue.remove(*cell.queue_iterator, cache_lock);
1830
42
            _lru_recorder->record_queue_event(
1831
42
                    cell.file_block->cache_type(), CacheLRULogType::REMOVE,
1832
42
                    cell.file_block->get_hash_value(), cell.file_block->offset(), cell.size());
1833
42
            auto& new_queue = get_queue(new_type);
1834
42
            cell.queue_iterator =
1835
42
                    new_queue.add(hash, offset, cell.file_block->range().size(), cache_lock);
1836
42
            _lru_recorder->record_queue_event(new_type, CacheLRULogType::ADD,
1837
42
                                              cell.file_block->get_hash_value(),
1838
42
                                              cell.file_block->offset(), cell.size());
1839
42
        }
1840
43
    }
1841
43
}
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
2.44k
int disk_used_percentage(const std::string& path, std::pair<int, int>* percent) {
1847
2.44k
    struct statfs stat;
1848
2.44k
    int ret = statfs(path.c_str(), &stat);
1849
2.44k
    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
2.44k
    uintmax_t u100 = (stat.f_blocks - stat.f_bfree) * 100;
1856
2.44k
    uintmax_t nonroot_total = stat.f_blocks - stat.f_bfree + stat.f_bavail;
1857
2.44k
    int capacity_percentage = int(u100 / nonroot_total + (u100 % nonroot_total != 0));
1858
1859
2.44k
    unsigned long long inode_free = stat.f_ffree;
1860
2.44k
    unsigned long long inode_total = stat.f_files;
1861
2.44k
    int inode_percentage = cast_set<int>(inode_free * 100 / inode_total);
1862
2.44k
    percent->first = capacity_percentage;
1863
2.44k
    percent->second = 100 - inode_percentage;
1864
1865
    // Add sync point for testing
1866
2.44k
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::disk_used_percentage:1", percent);
1867
1868
2.44k
    return 0;
1869
2.44k
}
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
1.31k
void BlockFileCache::check_disk_resource_limit() {
1932
1.31k
    if (_storage->get_type() != FileCacheStorageType::DISK) {
1933
23
        return;
1934
23
    }
1935
1936
1.28k
    bool previous_mode = _disk_resource_limit_mode;
1937
1.28k
    if (_capacity > _cur_cache_size) {
1938
1.28k
        _disk_resource_limit_mode = false;
1939
1.28k
        _disk_limit_mode_metrics->set_value(0);
1940
1.28k
    }
1941
1.28k
    std::pair<int, int> percent;
1942
1.28k
    int ret = disk_used_percentage(_cache_base_path, &percent);
1943
1.28k
    if (ret != 0) {
1944
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
1945
1
        return;
1946
1
    }
1947
1.28k
    auto [space_percentage, inode_percentage] = percent;
1948
2.57k
    auto is_insufficient = [](const int& percentage) {
1949
2.57k
        return percentage >= config::file_cache_enter_disk_resource_limit_mode_percent;
1950
2.57k
    };
1951
1.28k
    DCHECK_GE(space_percentage, 0);
1952
1.28k
    DCHECK_LE(space_percentage, 100);
1953
1.28k
    DCHECK_GE(inode_percentage, 0);
1954
1.28k
    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
1.28k
    if (config::file_cache_enter_disk_resource_limit_mode_percent <
1958
1.28k
        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
1.28k
    bool is_space_insufficient = is_insufficient(space_percentage);
1966
1.28k
    bool is_inode_insufficient = is_insufficient(inode_percentage);
1967
1.28k
    if (is_space_insufficient || is_inode_insufficient) {
1968
1
        _disk_resource_limit_mode = true;
1969
1
        _disk_limit_mode_metrics->set_value(1);
1970
1.28k
    } else if (_disk_resource_limit_mode &&
1971
1.28k
               (space_percentage < config::file_cache_exit_disk_resource_limit_mode_percent) &&
1972
1.28k
               (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
1.28k
    if (previous_mode != _disk_resource_limit_mode) {
1977
        // add log for disk resource limit mode switching
1978
2
        if (_disk_resource_limit_mode) {
1979
1
            LOG(WARNING) << "Entering disk resource limit mode: file_cache=" << get_base_path()
1980
1
                         << " space_percent=" << space_percentage
1981
1
                         << " inode_percent=" << inode_percentage
1982
1
                         << " is_space_insufficient=" << is_space_insufficient
1983
1
                         << " is_inode_insufficient=" << is_inode_insufficient
1984
1
                         << " enter threshold="
1985
1
                         << config::file_cache_enter_disk_resource_limit_mode_percent;
1986
1
        } else {
1987
1
            LOG(INFO) << "Exiting disk resource limit mode: file_cache=" << get_base_path()
1988
1
                      << " space_percent=" << space_percentage
1989
1
                      << " inode_percent=" << inode_percentage << " exit threshold="
1990
1
                      << config::file_cache_exit_disk_resource_limit_mode_percent;
1991
1
        }
1992
1.28k
    } 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
1.28k
}
2002
2003
1.15k
void BlockFileCache::check_need_evict_cache_in_advance() {
2004
1.15k
    if (_storage->get_type() != FileCacheStorageType::DISK) {
2005
1
        return;
2006
1
    }
2007
2008
1.15k
    std::pair<int, int> percent;
2009
1.15k
    int ret = disk_used_percentage(_cache_base_path, &percent);
2010
1.15k
    if (ret != 0) {
2011
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
2012
1
        return;
2013
1
    }
2014
1.15k
    auto [space_percentage, inode_percentage] = percent;
2015
1.15k
    int size_percentage = static_cast<int>(_cur_cache_size * 100 / _capacity);
2016
3.46k
    auto is_insufficient = [](const int& percentage) {
2017
3.46k
        return percentage >= config::file_cache_enter_need_evict_cache_in_advance_percent;
2018
3.46k
    };
2019
1.15k
    DCHECK_GE(space_percentage, 0);
2020
1.15k
    DCHECK_LE(space_percentage, 100);
2021
1.15k
    DCHECK_GE(inode_percentage, 0);
2022
1.15k
    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
1.15k
    if (config::file_cache_enter_need_evict_cache_in_advance_percent <=
2026
1.15k
        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
1.15k
    bool previous_mode = _need_evict_cache_in_advance;
2034
1.15k
    bool is_space_insufficient = is_insufficient(space_percentage);
2035
1.15k
    bool is_inode_insufficient = is_insufficient(inode_percentage);
2036
1.15k
    bool is_size_insufficient = is_insufficient(size_percentage);
2037
1.15k
    if (is_space_insufficient || is_inode_insufficient || is_size_insufficient) {
2038
108
        _need_evict_cache_in_advance = true;
2039
108
        _need_evict_cache_in_advance_metrics->set_value(1);
2040
1.04k
    } else if (_need_evict_cache_in_advance &&
2041
1.04k
               (space_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
2042
1.04k
               (inode_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
2043
1.04k
               (size_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent)) {
2044
53
        _need_evict_cache_in_advance = false;
2045
53
        _need_evict_cache_in_advance_metrics->set_value(0);
2046
53
    }
2047
1.15k
    if (previous_mode != _need_evict_cache_in_advance) {
2048
        // add log for evict cache in advance mode switching
2049
110
        if (_need_evict_cache_in_advance) {
2050
57
            LOG(WARNING) << "Entering evict cache in advance mode: "
2051
57
                         << "file_cache=" << get_base_path()
2052
57
                         << " space_percent=" << space_percentage
2053
57
                         << " inode_percent=" << inode_percentage
2054
57
                         << " size_percent=" << size_percentage
2055
57
                         << " is_space_insufficient=" << is_space_insufficient
2056
57
                         << " is_inode_insufficient=" << is_inode_insufficient
2057
57
                         << " is_size_insufficient=" << is_size_insufficient << " enter threshold="
2058
57
                         << config::file_cache_enter_need_evict_cache_in_advance_percent;
2059
57
        } else {
2060
53
            LOG(INFO) << "Exiting evict cache in advance mode: "
2061
53
                      << "file_cache=" << get_base_path() << " space_percent=" << space_percentage
2062
53
                      << " inode_percent=" << inode_percentage
2063
53
                      << " size_percent=" << size_percentage << " exit threshold="
2064
53
                      << config::file_cache_exit_need_evict_cache_in_advance_percent;
2065
53
        }
2066
1.04k
    } else if (_need_evict_cache_in_advance) {
2067
        // print log for evict cache in advance mode running, but less frequently
2068
54
        LOG_EVERY_N(WARNING, 10) << "file_cache=" << get_base_path()
2069
6
                                 << " space_percent=" << space_percentage
2070
6
                                 << " inode_percent=" << inode_percentage
2071
6
                                 << " size_percent=" << size_percentage
2072
6
                                 << " is_space_insufficient=" << is_space_insufficient
2073
6
                                 << " is_inode_insufficient=" << is_inode_insufficient
2074
6
                                 << " is_size_insufficient=" << is_size_insufficient
2075
6
                                 << " need evict cache in advance";
2076
54
    }
2077
1.15k
}
2078
2079
163
void BlockFileCache::run_background_monitor() {
2080
163
    Thread::set_self_name("run_background_monitor");
2081
1.31k
    while (!_close) {
2082
1.31k
        int64_t interval_ms = config::file_cache_background_monitor_interval_ms;
2083
1.31k
        TEST_SYNC_POINT_CALLBACK("BlockFileCache::set_sleep_time", &interval_ms);
2084
1.31k
        check_disk_resource_limit();
2085
1.31k
        if (config::enable_evict_file_cache_in_advance) {
2086
1.14k
            check_need_evict_cache_in_advance();
2087
1.14k
        } else {
2088
163
            _need_evict_cache_in_advance = false;
2089
163
            _need_evict_cache_in_advance_metrics->set_value(0);
2090
163
        }
2091
2092
1.31k
        {
2093
1.31k
            std::unique_lock close_lock(_close_mtx);
2094
1.31k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2095
1.31k
            if (_close) {
2096
160
                break;
2097
160
            }
2098
1.31k
        }
2099
        // report
2100
1.15k
        {
2101
1.15k
            SCOPED_CACHE_LOCK(_mutex, this);
2102
1.15k
            _cur_cache_size_metrics->set_value(_cur_cache_size);
2103
1.15k
            _cur_ttl_cache_size_metrics->set_value(_cur_cache_size -
2104
1.15k
                                                   _index_queue.get_capacity(cache_lock) -
2105
1.15k
                                                   _normal_queue.get_capacity(cache_lock) -
2106
1.15k
                                                   _disposable_queue.get_capacity(cache_lock));
2107
1.15k
            _cur_ttl_cache_lru_queue_cache_size_metrics->set_value(
2108
1.15k
                    _ttl_queue.get_capacity(cache_lock));
2109
1.15k
            _cur_ttl_cache_lru_queue_element_count_metrics->set_value(
2110
1.15k
                    _ttl_queue.get_elements_num(cache_lock));
2111
1.15k
            _cur_normal_queue_cache_size_metrics->set_value(_normal_queue.get_capacity(cache_lock));
2112
1.15k
            _cur_normal_queue_element_count_metrics->set_value(
2113
1.15k
                    _normal_queue.get_elements_num(cache_lock));
2114
1.15k
            _cur_index_queue_cache_size_metrics->set_value(_index_queue.get_capacity(cache_lock));
2115
1.15k
            _cur_index_queue_element_count_metrics->set_value(
2116
1.15k
                    _index_queue.get_elements_num(cache_lock));
2117
1.15k
            _cur_disposable_queue_cache_size_metrics->set_value(
2118
1.15k
                    _disposable_queue.get_capacity(cache_lock));
2119
1.15k
            _cur_disposable_queue_element_count_metrics->set_value(
2120
1.15k
                    _disposable_queue.get_elements_num(cache_lock));
2121
2122
            // Update meta store write queue size if storage is FSFileCacheStorage
2123
1.15k
            if (_storage->get_type() == FileCacheStorageType::DISK) {
2124
1.14k
                auto* fs_storage = dynamic_cast<FSFileCacheStorage*>(_storage.get());
2125
1.14k
                if (fs_storage != nullptr) {
2126
1.14k
                    auto* meta_store = fs_storage->get_meta_store();
2127
1.14k
                    if (meta_store != nullptr) {
2128
1.14k
                        _meta_store_write_queue_size_metrics->set_value(
2129
1.14k
                                meta_store->get_write_queue_size());
2130
1.14k
                    }
2131
1.14k
                }
2132
1.14k
            }
2133
2134
1.15k
            if (_num_read_blocks->get_value() > 0) {
2135
888
                _hit_ratio->set_value((double)_num_hit_blocks->get_value() /
2136
888
                                      (double)_num_read_blocks->get_value());
2137
888
            }
2138
1.15k
            if (_num_read_blocks_5m && _num_read_blocks_5m->get_value() > 0) {
2139
877
                _hit_ratio_5m->set_value((double)_num_hit_blocks_5m->get_value() /
2140
877
                                         (double)_num_read_blocks_5m->get_value());
2141
877
            }
2142
1.15k
            if (_num_read_blocks_1h && _num_read_blocks_1h->get_value() > 0) {
2143
877
                _hit_ratio_1h->set_value((double)_num_hit_blocks_1h->get_value() /
2144
877
                                         (double)_num_read_blocks_1h->get_value());
2145
877
            }
2146
2147
1.15k
            if (_no_warmup_num_read_blocks->get_value() > 0) {
2148
888
                _no_warmup_hit_ratio->set_value((double)_no_warmup_num_hit_blocks->get_value() /
2149
888
                                                (double)_no_warmup_num_read_blocks->get_value());
2150
888
            }
2151
1.15k
            if (_no_warmup_num_read_blocks_5m && _no_warmup_num_read_blocks_5m->get_value() > 0) {
2152
877
                _no_warmup_hit_ratio_5m->set_value(
2153
877
                        (double)_no_warmup_num_hit_blocks_5m->get_value() /
2154
877
                        (double)_no_warmup_num_read_blocks_5m->get_value());
2155
877
            }
2156
1.15k
            if (_no_warmup_num_read_blocks_1h && _no_warmup_num_read_blocks_1h->get_value() > 0) {
2157
877
                _no_warmup_hit_ratio_1h->set_value(
2158
877
                        (double)_no_warmup_num_hit_blocks_1h->get_value() /
2159
877
                        (double)_no_warmup_num_read_blocks_1h->get_value());
2160
877
            }
2161
1.15k
        }
2162
1.15k
        _lru_recorder->update_shadow_queue_element_count_metrics();
2163
1.15k
    }
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
56.7k
    while (!_close) {
2171
56.7k
        int64_t interval_ms = config::file_cache_background_gc_interval_ms;
2172
56.7k
        size_t batch_limit = config::file_cache_remove_block_qps_limit * interval_ms / 1000;
2173
56.7k
        {
2174
56.7k
            std::unique_lock close_lock(_close_mtx);
2175
56.7k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2176
56.7k
            if (_close) {
2177
160
                break;
2178
160
            }
2179
56.7k
        }
2180
2181
149k
        while (batch_count < batch_limit && _recycle_keys.try_dequeue(key)) {
2182
93.2k
            int64_t duration_ns = 0;
2183
93.2k
            Status st;
2184
93.2k
            {
2185
93.2k
                SCOPED_RAW_TIMER(&duration_ns);
2186
93.2k
                st = _storage->remove(key);
2187
93.2k
            }
2188
93.2k
            *_storage_async_remove_latency_us << (duration_ns / 1000);
2189
2190
93.2k
            if (!st.ok()) {
2191
0
                LOG_WARNING("").error(st);
2192
0
            }
2193
93.2k
            batch_count++;
2194
93.2k
        }
2195
56.6k
        *_recycle_keys_length_recorder << _recycle_keys.size_approx();
2196
56.6k
        batch_count = 0;
2197
56.6k
    }
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
5.96k
    while (!_close) {
2205
5.95k
        {
2206
5.95k
            std::unique_lock close_lock(_close_mtx);
2207
5.95k
            _close_cv.wait_for(
2208
5.95k
                    close_lock,
2209
5.95k
                    std::chrono::milliseconds(config::file_cache_evict_in_advance_interval_ms));
2210
5.95k
            if (_close) {
2211
160
                LOG(INFO) << "Background evict in advance thread exiting due to cache closing";
2212
160
                break;
2213
160
            }
2214
5.95k
        }
2215
5.79k
        batch = config::file_cache_evict_in_advance_batch_bytes;
2216
2217
        // Skip if eviction not needed or too many pending recycles
2218
5.79k
        if (!_need_evict_cache_in_advance ||
2219
5.79k
            _recycle_keys.size_approx() >=
2220
5.32k
                    config::file_cache_evict_in_advance_recycle_keys_num_threshold) {
2221
5.32k
            continue;
2222
5.32k
        }
2223
2224
474
        int64_t duration_ns = 0;
2225
474
        {
2226
474
            SCOPED_CACHE_LOCK(_mutex, this);
2227
474
            SCOPED_RAW_TIMER(&duration_ns);
2228
474
            try_evict_in_advance(batch, cache_lock);
2229
474
        }
2230
474
        *_evict_in_advance_latency_us << (duration_ns / 1000);
2231
474
    }
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
1.33k
    while (!_close) {
2238
1.33k
        int64_t interval_ms = config::file_cache_background_block_lru_update_interval_ms;
2239
1.33k
        size_t batch_limit =
2240
1.33k
                config::file_cache_background_block_lru_update_qps_limit * interval_ms / 1000;
2241
1.33k
        {
2242
1.33k
            std::unique_lock close_lock(_close_mtx);
2243
1.33k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2244
1.33k
            if (_close) {
2245
160
                break;
2246
160
            }
2247
1.33k
        }
2248
2249
1.17k
        batch.clear();
2250
1.17k
        batch.reserve(batch_limit);
2251
1.17k
        size_t drained = _need_update_lru_blocks.drain(batch_limit, &batch);
2252
1.17k
        if (drained == 0) {
2253
371
            *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2254
371
            continue;
2255
371
        }
2256
805
        *_need_update_lru_blocks_consume_metrics << drained;
2257
2258
805
        int64_t duration_ns = 0;
2259
805
        {
2260
805
            SCOPED_CACHE_LOCK(_mutex, this);
2261
805
            SCOPED_RAW_TIMER(&duration_ns);
2262
169k
            for (auto& block : batch) {
2263
169k
                update_block_lru(block, cache_lock);
2264
169k
            }
2265
805
        }
2266
805
        *_update_lru_blocks_latency_us << (duration_ns / 1000);
2267
805
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2268
805
    }
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
4
                                                   std::lock_guard<std::mutex>& cache_lock) {
2298
4
    size_t removed_size = 0;
2299
4
    size_t normal_queue_size = _normal_queue.get_capacity(cache_lock);
2300
4
    size_t disposable_queue_size = _disposable_queue.get_capacity(cache_lock);
2301
4
    size_t index_queue_size = _index_queue.get_capacity(cache_lock);
2302
2303
4
    std::vector<FileBlockCell*> to_evict;
2304
4
    auto collect_eliminate_fragments = [&](LRUQueue& queue) {
2305
4
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
2306
4
            if (!_disk_resource_limit_mode || removed_size >= size) {
2307
3
                break;
2308
3
            }
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
3
    };
2327
4
    if (disposable_queue_size != 0) {
2328
0
        collect_eliminate_fragments(get_queue(FileCacheType::DISPOSABLE));
2329
0
    }
2330
4
    if (normal_queue_size != 0) {
2331
3
        collect_eliminate_fragments(get_queue(FileCacheType::NORMAL));
2332
3
    }
2333
4
    if (index_queue_size != 0) {
2334
0
        collect_eliminate_fragments(get_queue(FileCacheType::INDEX));
2335
0
    }
2336
4
    std::string reason = "async load";
2337
4
    remove_file_blocks(to_evict, cache_lock, true, reason);
2338
2339
4
    return !_disk_resource_limit_mode || removed_size >= size;
2340
4
}
2341
2342
24
void BlockFileCache::clear_need_update_lru_blocks() {
2343
24
    _need_update_lru_blocks.clear();
2344
24
    *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2345
24
}
2346
2347
1.83M
std::map<size_t, FileBlockSPtr> BlockFileCache::get_blocks_by_key(const UInt128Wrapper& hash) {
2348
1.83M
    std::map<size_t, FileBlockSPtr> offset_to_block;
2349
1.83M
    SCOPED_CACHE_LOCK(_mutex, this);
2350
1.83M
    if (_files.contains(hash)) {
2351
1.84M
        for (auto& [offset, cell] : _files[hash]) {
2352
1.84M
            if (cell.file_block->state() == FileBlock::State::DOWNLOADED) {
2353
1.84M
                cell.file_block->_owned_by_cached_reader = true;
2354
1.84M
                offset_to_block.emplace(offset, cell.file_block);
2355
1.84M
            }
2356
1.84M
        }
2357
1.79M
    }
2358
1.83M
    return offset_to_block;
2359
1.83M
}
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
5.09M
    while (!_close) {
2373
5.09M
        int64_t interval_ms = config::file_cache_background_lru_log_replay_interval_ms;
2374
5.09M
        {
2375
5.09M
            std::unique_lock close_lock(_close_mtx);
2376
5.09M
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2377
5.09M
            if (_close) {
2378
139
                break;
2379
139
            }
2380
5.09M
        }
2381
2382
5.09M
        replay_lru_logs_once();
2383
5.09M
    }
2384
163
}
2385
2386
5.09M
size_t BlockFileCache::replay_lru_logs_once() {
2387
5.09M
    size_t replayed = 0;
2388
20.3M
    for (FileCacheType type : LRU_LOG_REPLAY_TYPES) {
2389
20.3M
        replayed += _lru_recorder->replay_queue_event(type);
2390
20.3M
    }
2391
2392
5.09M
    if (replayed == 0) {
2393
4.96M
        *_lru_recorder_log_replay_idle_metrics << 1;
2394
4.96M
    }
2395
2396
5.09M
    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
5.09M
    return replayed;
2404
5.09M
}
2405
2406
104
void BlockFileCache::dump_lru_queues(bool force) {
2407
104
    std::unique_lock dump_lock(_dump_lru_queues_mtx);
2408
104
    if (config::file_cache_background_lru_dump_tail_record_num > 0 &&
2409
104
        !ExecEnv::GetInstance()->get_is_upgrading()) {
2410
104
        _lru_dumper->dump_queue("disposable", force);
2411
104
        _lru_dumper->dump_queue("normal", force);
2412
104
        _lru_dumper->dump_queue("index", force);
2413
104
        _lru_dumper->dump_queue("ttl", force);
2414
104
        _lru_dumper->set_first_dump_done();
2415
104
    }
2416
104
}
2417
2418
163
void BlockFileCache::run_background_lru_dump() {
2419
163
    Thread::set_self_name("run_background_lru_dump");
2420
270
    while (!_close) {
2421
267
        int64_t interval_ms = config::file_cache_background_lru_dump_interval_ms;
2422
267
        {
2423
267
            std::unique_lock close_lock(_close_mtx);
2424
267
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2425
267
            if (_close) {
2426
160
                break;
2427
160
            }
2428
267
        }
2429
107
        dump_lru_queues(false);
2430
107
    }
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
1
std::map<std::string, double> BlockFileCache::get_stats() {
2442
1
    std::map<std::string, double> stats;
2443
1
    stats["hits_ratio"] = (double)_hit_ratio->get_value();
2444
1
    stats["hits_ratio_5m"] = (double)_hit_ratio_5m->get_value();
2445
1
    stats["hits_ratio_1h"] = (double)_hit_ratio_1h->get_value();
2446
2447
1
    stats["index_queue_max_size"] = (double)_index_queue.get_max_size();
2448
1
    stats["index_queue_curr_size"] = (double)_cur_index_queue_cache_size_metrics->get_value();
2449
1
    stats["index_queue_max_elements"] = (double)_index_queue.get_max_element_size();
2450
1
    stats["index_queue_curr_elements"] =
2451
1
            (double)_cur_index_queue_element_count_metrics->get_value();
2452
2453
1
    stats["ttl_queue_max_size"] = (double)_ttl_queue.get_max_size();
2454
1
    stats["ttl_queue_curr_size"] = (double)_cur_ttl_cache_lru_queue_cache_size_metrics->get_value();
2455
1
    stats["ttl_queue_max_elements"] = (double)_ttl_queue.get_max_element_size();
2456
1
    stats["ttl_queue_curr_elements"] =
2457
1
            (double)_cur_ttl_cache_lru_queue_element_count_metrics->get_value();
2458
2459
1
    stats["normal_queue_max_size"] = (double)_normal_queue.get_max_size();
2460
1
    stats["normal_queue_curr_size"] = (double)_cur_normal_queue_cache_size_metrics->get_value();
2461
1
    stats["normal_queue_max_elements"] = (double)_normal_queue.get_max_element_size();
2462
1
    stats["normal_queue_curr_elements"] =
2463
1
            (double)_cur_normal_queue_element_count_metrics->get_value();
2464
2465
1
    stats["disposable_queue_max_size"] = (double)_disposable_queue.get_max_size();
2466
1
    stats["disposable_queue_curr_size"] =
2467
1
            (double)_cur_disposable_queue_cache_size_metrics->get_value();
2468
1
    stats["disposable_queue_max_elements"] = (double)_disposable_queue.get_max_element_size();
2469
1
    stats["disposable_queue_curr_elements"] =
2470
1
            (double)_cur_disposable_queue_element_count_metrics->get_value();
2471
2472
1
    stats["lru_recorder_index_shadow_queue_curr_elements"] =
2473
1
            (double)_lru_recorder_shadow_queue_element_count_metrics[FileCacheType::INDEX]
2474
1
                    ->get_value();
2475
1
    stats["lru_recorder_ttl_shadow_queue_curr_elements"] =
2476
1
            (double)_lru_recorder_shadow_queue_element_count_metrics[FileCacheType::TTL]
2477
1
                    ->get_value();
2478
1
    stats["lru_recorder_normal_shadow_queue_curr_elements"] =
2479
1
            (double)_lru_recorder_shadow_queue_element_count_metrics[FileCacheType::NORMAL]
2480
1
                    ->get_value();
2481
1
    stats["lru_recorder_disposable_shadow_queue_curr_elements"] =
2482
1
            (double)_lru_recorder_shadow_queue_element_count_metrics[FileCacheType::DISPOSABLE]
2483
1
                    ->get_value();
2484
2485
1
    stats["need_evict_cache_in_advance"] = (double)_need_evict_cache_in_advance;
2486
1
    stats["disk_resource_limit_mode"] = (double)_disk_resource_limit_mode;
2487
2488
1
    stats["total_removed_counts"] = (double)_num_removed_blocks->get_value();
2489
1
    stats["total_hit_counts"] = (double)_num_hit_blocks->get_value();
2490
1
    stats["total_read_counts"] = (double)_num_read_blocks->get_value();
2491
2492
1
    stats["total_read_size"] = (double)_total_read_size_metrics->get_value();
2493
1
    stats["total_hit_size"] = (double)_total_hit_size_metrics->get_value();
2494
1
    stats["total_removed_size"] = (double)_total_evict_size_metrics->get_value();
2495
2496
1
    return stats;
2497
1
}
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