Coverage Report

Created: 2026-08-06 12:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/block_file_cache.h
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
18
#pragma once
19
20
#include <bvar/bvar.h>
21
#include <concurrentqueue.h>
22
23
#include <algorithm>
24
#include <array>
25
#include <atomic>
26
#include <boost/lockfree/spsc_queue.hpp>
27
#include <condition_variable>
28
#include <functional>
29
#include <limits>
30
#include <memory>
31
#include <mutex>
32
#include <optional>
33
#include <thread>
34
#include <unordered_map>
35
#include <vector>
36
37
#include "io/cache/block_file_cache_ttl_mgr.h"
38
#include "io/cache/cache_lru_dumper.h"
39
#include "io/cache/file_block.h"
40
#include "io/cache/file_cache_common.h"
41
#include "io/cache/file_cache_storage.h"
42
#include "io/cache/lru_queue_recorder.h"
43
#include "runtime/runtime_profile.h"
44
#include "util/threadpool.h"
45
46
namespace doris::io {
47
using RecycleFileCacheKeys = moodycamel::ConcurrentQueue<FileCacheKey>;
48
49
class LockScopedTimer {
50
public:
51
545k
    LockScopedTimer() : start_(std::chrono::steady_clock::now()) {}
52
545k
    ~LockScopedTimer() {
53
545k
        auto end = std::chrono::steady_clock::now();
54
545k
        auto duration_us =
55
545k
                std::chrono::duration_cast<std::chrono::microseconds>(end - start_).count();
56
545k
        if (duration_us > config::cache_lock_held_long_tail_threshold_us) {
57
0
            LOG(WARNING) << "Lock held time " << std::to_string(duration_us) << "us. "
58
0
                         << get_stack_trace();
59
0
        }
60
545k
    }
61
62
private:
63
    std::chrono::time_point<std::chrono::steady_clock> start_;
64
};
65
66
// Note: the cache_lock is scoped, so do not add do...while(0) here.
67
#define SCOPED_CACHE_LOCK(MUTEX, cache)                                                           \
68
542k
    std::chrono::time_point<std::chrono::steady_clock> start_time =                               \
69
542k
            std::chrono::steady_clock::now();                                                     \
70
542k
    std::lock_guard cache_lock(MUTEX);                                                            \
71
542k
    std::chrono::time_point<std::chrono::steady_clock> acq_time =                                 \
72
542k
            std::chrono::steady_clock::now();                                                     \
73
542k
    auto duration_us =                                                                            \
74
542k
            std::chrono::duration_cast<std::chrono::microseconds>(acq_time - start_time).count(); \
75
542k
    *(cache->_cache_lock_wait_time_us) << duration_us;                                            \
76
542k
    if (duration_us > config::cache_lock_wait_long_tail_threshold_us) {                           \
77
0
        LOG(WARNING) << "Lock wait time " << std::to_string(duration_us) << "us. "                \
78
0
                     << get_stack_trace() << std::endl;                                           \
79
0
    }                                                                                             \
80
542k
    LockScopedTimer cache_lock_timer;
81
82
class FSFileCacheStorage;
83
84
// NeedUpdateLRUBlocks keeps FileBlockSPtr entries that require LRU updates in a
85
// deduplicated, sharded container. Entries are keyed by the raw FileBlock
86
// pointer so that multiple shared_ptr copies of the same block are treated as a
87
// single pending update. The structure is thread-safe and optimized for high
88
// contention insert/drain workloads in the background update thread.
89
// Note that Blocks are updated in batch, internal order is not important.
90
class NeedUpdateLRUBlocks {
91
public:
92
277
    NeedUpdateLRUBlocks() = default;
93
94
    // Insert a block into the pending set. Returns true only when the block
95
    // was not already queued. Null inputs are ignored.
96
    bool insert(FileBlockSPtr block, size_t max_queue_size = std::numeric_limits<size_t>::max());
97
98
    // Drain up to `limit` unique blocks into `output`. The method returns how
99
    // many blocks were actually drained and shrinks the internal size
100
    // accordingly.
101
    size_t drain(size_t limit, std::vector<FileBlockSPtr>* output);
102
103
    // Remove every pending block from the structure and reset the size.
104
    void clear();
105
106
    // Thread-safe approximate size of queued unique blocks.
107
133k
    size_t size() const { return _size.load(std::memory_order_relaxed); }
108
109
private:
110
    static constexpr size_t kShardCount = 64;
111
    static constexpr size_t kShardMask = kShardCount - 1;
112
113
    struct Shard {
114
        std::mutex mutex;
115
        std::unordered_map<FileBlock*, FileBlockSPtr> entries;
116
    };
117
118
    size_t shard_index(FileBlock* ptr) const;
119
    void decrease_size(size_t delta);
120
121
    std::array<Shard, kShardCount> _shards;
122
    std::atomic<size_t> _size {0};
123
};
124
125
// The BlockFileCache is responsible for the management of the blocks
126
// The current strategies are lru and ttl.
127
128
struct FileBlockCell {
129
    friend class FileBlock;
130
131
    FileBlockSPtr file_block;
132
    /// Iterator is put here on first reservation attempt, if successful.
133
    std::optional<LRUQueue::Iterator> queue_iterator;
134
135
    mutable int64_t atime {0};
136
1.15M
    void update_atime() const {
137
1.15M
        atime = std::chrono::duration_cast<std::chrono::seconds>(
138
1.15M
                        std::chrono::steady_clock::now().time_since_epoch())
139
1.15M
                        .count();
140
1.15M
    }
141
142
    /// Pointer to file block is always hold by the cache itself.
143
    /// Apart from pointer in cache, it can be hold by cache users, when they call
144
    /// getorSet(), but cache users always hold it via FileBlocksHolder.
145
359M
    bool releasable() const {
146
359M
        return (file_block.use_count() == 1 ||
147
359M
                (file_block.use_count() == 2 && file_block->_owned_by_cached_reader));
148
359M
    }
149
150
361M
    size_t size() const { return file_block->_block_range.size(); }
151
152
    FileBlockCell() = default;
153
    FileBlockCell(FileBlockSPtr file_block, std::lock_guard<std::mutex>& cache_lock);
154
    FileBlockCell(FileBlockCell&& other) noexcept
155
802k
            : file_block(std::move(other.file_block)),
156
802k
              queue_iterator(other.queue_iterator),
157
802k
              atime(other.atime) {
158
802k
        file_block->cell = this;
159
802k
    }
160
161
    FileBlockCell& operator=(const FileBlockCell&) = delete;
162
    FileBlockCell(const FileBlockCell&) = delete;
163
164
0
    size_t dowloading_size() const { return file_block->_downloaded_size; }
165
};
166
167
class BlockFileCache {
168
    friend class FSFileCacheStorage;
169
    friend class MemFileCacheStorage;
170
    friend class FileBlock;
171
    friend struct FileBlocksHolder;
172
    friend class CacheLRUDumper;
173
    friend class LRUQueueRecorder;
174
    friend struct FileBlockCell;
175
    friend class BlockFileCacheTest;
176
177
public:
178
    // hash the file_name to uint128
179
    static UInt128Wrapper hash(const std::string& path);
180
181
    BlockFileCache(const std::string& cache_base_path, const FileCacheSettings& cache_settings);
182
183
269
    virtual ~BlockFileCache() {
184
269
        {
185
269
            std::lock_guard lock(_close_mtx);
186
269
            _close = true;
187
269
        }
188
269
        _close_cv.notify_all();
189
269
        if (_cache_background_monitor_thread.joinable()) {
190
239
            _cache_background_monitor_thread.join();
191
239
        }
192
269
        if (_cache_background_gc_thread.joinable()) {
193
239
            _cache_background_gc_thread.join();
194
239
        }
195
269
        if (_cache_background_evict_in_advance_thread.joinable()) {
196
239
            _cache_background_evict_in_advance_thread.join();
197
239
        }
198
269
        if (_cache_background_lru_dump_thread.joinable()) {
199
239
            _cache_background_lru_dump_thread.join();
200
239
        }
201
269
        if (_cache_background_lru_log_replay_thread.joinable()) {
202
239
            _cache_background_lru_log_replay_thread.join();
203
239
        }
204
269
        if (_cache_background_block_lru_update_thread.joinable()) {
205
239
            _cache_background_block_lru_update_thread.join();
206
239
        }
207
269
        if (_ttl_mgr) {
208
208
            _ttl_mgr.reset();
209
208
        }
210
269
    }
211
212
    /// Restore cache from local filesystem.
213
    Status initialize();
214
215
    /// Cache capacity in bytes.
216
14
    [[nodiscard]] size_t capacity() const { return _capacity; }
217
218
    // try to release all releasable block
219
    // it maybe hang the io/system
220
    size_t try_release();
221
222
2.94k
    [[nodiscard]] const std::string& get_base_path() const { return _cache_base_path; }
223
224
    // Get storage for inspection
225
1
    FileCacheStorage* get_storage() const { return _storage.get(); }
226
227
    /**
228
         * Given an `offset` and `size` representing [offset, offset + size) bytes interval,
229
         * return list of cached non-overlapping non-empty
230
         * file blocks `[block1, ..., blockN]` which intersect with given interval.
231
         *
232
         * blocks in returned list are ordered in ascending order and represent a full contiguous
233
         * interval (no holes). Each block in returned list has state: DOWNLOADED, DOWNLOADING or EMPTY.
234
         *
235
         * As long as pointers to returned file blocks are hold
236
         * it is guaranteed that these file blocks are not removed from cache.
237
         */
238
    FileBlocksHolder get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
239
                                CacheContext& context);
240
241
    /**
242
     * Return existing downloaded blocks only if they fully cover [offset, offset + size).
243
     * This lookup is read-only: it does not reserve cache space or create EMPTY blocks.
244
     */
245
    Status get_downloaded_blocks_if_fully_covered(const UInt128Wrapper& hash, size_t offset,
246
                                                  size_t size, const CacheContext& context,
247
                                                  FileBlocks* blocks, bool* fully_covered);
248
249
    /**
250
     * record blocks read directly by CachedRemoteFileReader
251
     */
252
    void add_need_update_lru_block(FileBlockSPtr block);
253
254
    /**
255
     * Clear all cached data for this cache instance async
256
     *
257
     * @returns summary message
258
     */
259
    std::string clear_file_cache_async();
260
    std::string clear_file_cache_sync();
261
262
    /**
263
     * Reset the cache capacity. If the new_capacity is smaller than _capacity, the redundant data will be remove async.
264
     *
265
     * @returns summary message
266
     */
267
    std::string reset_capacity(size_t new_capacity);
268
269
    std::map<size_t, FileBlockSPtr> get_blocks_by_key(const UInt128Wrapper& hash);
270
271
    /// For debug and UT
272
    std::string dump_structure(const UInt128Wrapper& hash);
273
    std::string dump_single_cache_type(const UInt128Wrapper& hash, size_t offset);
274
275
    void dump_lru_queues(bool force);
276
277
    [[nodiscard]] size_t get_used_cache_size(FileCacheType type) const;
278
279
    [[nodiscard]] size_t get_file_blocks_num(FileCacheType type) const;
280
281
    // change the block cache type
282
    void change_cache_type(const UInt128Wrapper& hash, size_t offset, FileCacheType new_type,
283
                           std::lock_guard<std::mutex>& cache_lock);
284
285
    // remove all blocks that belong to the key
286
    void remove_if_cached(const UInt128Wrapper& key);
287
    void remove_if_cached_async(const UInt128Wrapper& key);
288
289
    // Reset the block size and keep FileBlock, LRU queue, and cache counters consistent.
290
    void reset_range(const UInt128Wrapper&, size_t offset, size_t old_size, size_t new_size,
291
                     std::lock_guard<std::mutex>& cache_lock);
292
293
    // get the hotest blocks message by key
294
    // The tuple is composed of <offset, size, cache_type, expiration_time>
295
    [[nodiscard]] std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>>
296
    get_hot_blocks_meta(const UInt128Wrapper& hash) const;
297
298
    [[nodiscard]] bool get_async_open_success() const { return _async_open_done; }
299
300
    BlockFileCache& operator=(const BlockFileCache&) = delete;
301
    BlockFileCache(const BlockFileCache&) = delete;
302
303
    // try to reserve the new space for the new block if the cache is full
304
    bool try_reserve(const UInt128Wrapper& hash, const CacheContext& context, size_t offset,
305
                     size_t size, std::lock_guard<std::mutex>& cache_lock);
306
307
    /**
308
     * Proactively evict cache blocks to free up space before cache is full.
309
     * 
310
     * This function attempts to evict blocks from both NORMAL and TTL queues to maintain 
311
     * cache size below high watermark. Unlike try_reserve() which blocks until space is freed,
312
     * this function initiates asynchronous eviction in background.
313
     * 
314
     * @param size Number of bytes to try to evict
315
     * @param cache_lock Lock that must be held while accessing cache data structures
316
     * 
317
     * @pre Caller must hold cache_lock
318
     * @pre _need_evict_cache_in_advance must be true
319
     * @pre _recycle_keys queue must have capacity for evicted blocks
320
     */
321
    void try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock);
322
323
    void update_ttl_atime(const UInt128Wrapper& hash);
324
325
    std::map<std::string, double> get_stats();
326
327
    // for be UTs
328
    std::map<std::string, double> get_stats_unsafe();
329
    [[nodiscard]] size_t need_update_lru_blocks_size_unsafe() const {
330
        return _need_update_lru_blocks.size();
331
    }
332
333
    using AccessRecord =
334
            std::unordered_map<AccessKeyAndOffset, LRUQueue::Iterator, KeyAndOffsetHash>;
335
336
    /// Used to track and control the cache access of each query.
337
    /// Through it, we can realize the processing of different queries by the cache layer.
338
    struct QueryFileCacheContext {
339
        LRUQueue lru_queue;
340
        AccessRecord records;
341
342
5
        QueryFileCacheContext(size_t max_cache_size) : lru_queue(max_cache_size, 0, 0) {}
343
344
        void remove(const UInt128Wrapper& hash, size_t offset,
345
                    std::lock_guard<std::mutex>& cache_lock);
346
347
        void reserve(const UInt128Wrapper& hash, size_t offset, size_t size,
348
                     std::lock_guard<std::mutex>& cache_lock);
349
350
69
        size_t get_max_cache_size() const { return lru_queue.get_max_size(); }
351
352
48
        size_t get_cache_size(std::lock_guard<std::mutex>& cache_lock) const {
353
48
            return lru_queue.get_capacity(cache_lock);
354
48
        }
355
356
50
        LRUQueue& queue() { return lru_queue; }
357
    };
358
359
    using QueryFileCacheContextPtr = std::shared_ptr<QueryFileCacheContext>;
360
    using QueryFileCacheContextMap = std::unordered_map<TUniqueId, QueryFileCacheContextPtr>;
361
362
    QueryFileCacheContextPtr get_query_context(const TUniqueId& query_id,
363
                                               std::lock_guard<std::mutex>&);
364
365
    void remove_query_context(const TUniqueId& query_id);
366
367
    QueryFileCacheContextPtr get_or_set_query_context(const TUniqueId& query_id,
368
                                                      std::lock_guard<std::mutex>& cache_lock,
369
                                                      int file_cache_query_limit_percent);
370
371
    /// Save a query context information, and adopt different cache policies
372
    /// for different queries through the context cache layer.
373
    struct QueryFileCacheContextHolder {
374
        QueryFileCacheContextHolder(const TUniqueId& query_id, BlockFileCache* mgr,
375
                                    QueryFileCacheContextPtr context)
376
7
                : query_id(query_id), mgr(mgr), context(context) {}
377
378
        QueryFileCacheContextHolder& operator=(const QueryFileCacheContextHolder&) = delete;
379
        QueryFileCacheContextHolder(const QueryFileCacheContextHolder&) = delete;
380
381
7
        ~QueryFileCacheContextHolder() {
382
            /// If only the query_map and the current holder hold the context_query,
383
            /// the query has been completed and the query_context is released.
384
7
            if (context) {
385
6
                context.reset();
386
6
                mgr->remove_query_context(query_id);
387
6
            }
388
7
        }
389
390
        const TUniqueId& query_id;
391
        BlockFileCache* mgr = nullptr;
392
        QueryFileCacheContextPtr context;
393
    };
394
    using QueryFileCacheContextHolderPtr = std::unique_ptr<QueryFileCacheContextHolder>;
395
    QueryFileCacheContextHolderPtr get_query_context_holder(const TUniqueId& query_id,
396
                                                            int file_cache_query_limit_percent);
397
398
4.68k
    int64_t approximate_available_cache_size() const {
399
4.68k
        return std::max<int64_t>(
400
4.68k
                _cache_capacity_metrics->get_value() - _cur_cache_size_metrics->get_value(), 0);
401
4.68k
    }
402
403
    Status report_file_cache_inconsistency(std::vector<std::string>& results);
404
    Status check_file_cache_consistency(InconsistencyContext& inconsistency_context);
405
406
private:
407
    // Shared scan used by both clear modes. It keeps the FileBlock holder lifecycle intact:
408
    // releasable blocks are removed immediately, while blocks held by readers are only marked
409
    // deleting and are later removed by FileBlocksHolder destruction.
410
    std::string clear_file_cache_impl(bool sync_remove);
411
412
    LRUQueue& get_queue(FileCacheType type);
413
    const LRUQueue& get_queue(FileCacheType type) const;
414
415
    template <class T, class U>
416
        requires IsXLock<T> && IsXLock<U>
417
    void remove(FileBlockSPtr file_block, T& cache_lock, U& segment_lock, bool sync = true);
418
419
    FileBlocks get_impl(const UInt128Wrapper& hash, const CacheContext& context,
420
                        const FileBlock::Range& range, std::lock_guard<std::mutex>& cache_lock);
421
422
    template <class T>
423
        requires IsXLock<T>
424
    FileBlockCell* get_cell(const UInt128Wrapper& hash, size_t offset, T& cache_lock);
425
426
    virtual FileBlockCell* add_cell(const UInt128Wrapper& hash, const CacheContext& context,
427
                                    size_t offset, size_t size, FileBlock::State state,
428
                                    std::lock_guard<std::mutex>& cache_lock);
429
430
    Status initialize_unlocked(std::lock_guard<std::mutex>& cache_lock);
431
432
    void update_block_lru(FileBlockSPtr block, std::lock_guard<std::mutex>& cache_lock);
433
434
    void use_cell(const FileBlockCell& cell, FileBlocks* result, bool not_need_move,
435
                  std::lock_guard<std::mutex>& cache_lock);
436
437
    bool try_reserve_for_lru(const UInt128Wrapper& hash, QueryFileCacheContextPtr query_context,
438
                             const CacheContext& context, size_t offset, size_t size,
439
                             std::lock_guard<std::mutex>& cache_lock,
440
                             bool evict_in_advance = false);
441
442
    bool try_reserve_during_async_load(size_t size, std::lock_guard<std::mutex>& cache_lock);
443
444
    std::vector<FileCacheType> get_other_cache_type(FileCacheType cur_cache_type);
445
    std::vector<FileCacheType> get_other_cache_type_without_ttl(FileCacheType cur_cache_type);
446
447
    bool try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t offset, int64_t cur_time,
448
                                      std::lock_guard<std::mutex>& cache_lock,
449
                                      bool evict_in_advance = false);
450
451
    size_t get_available_cache_size(FileCacheType cache_type) const;
452
453
    FileBlocks split_range_into_cells(const UInt128Wrapper& hash, const CacheContext& context,
454
                                      size_t offset, size_t size, FileBlock::State state,
455
                                      std::lock_guard<std::mutex>& cache_lock);
456
457
    std::string dump_structure_unlocked(const UInt128Wrapper& hash,
458
                                        std::lock_guard<std::mutex>& cache_lock);
459
460
    std::string dump_single_cache_type_unlocked(const UInt128Wrapper& hash, size_t offset,
461
                                                std::lock_guard<std::mutex>& cache_lock);
462
463
    void fill_holes_with_empty_file_blocks(FileBlocks& file_blocks, const UInt128Wrapper& hash,
464
                                           const CacheContext& context,
465
                                           const FileBlock::Range& range,
466
                                           std::lock_guard<std::mutex>& cache_lock);
467
468
    size_t get_used_cache_size_unlocked(FileCacheType type,
469
                                        std::lock_guard<std::mutex>& cache_lock) const;
470
471
    void check_disk_resource_limit();
472
    void check_need_evict_cache_in_advance();
473
474
    size_t get_available_cache_size_unlocked(FileCacheType type,
475
                                             std::lock_guard<std::mutex>& cache_lock) const;
476
477
    size_t get_file_blocks_num_unlocked(FileCacheType type,
478
                                        std::lock_guard<std::mutex>& cache_lock) const;
479
480
    bool need_to_move(FileCacheType cell_type, FileCacheType query_type) const;
481
482
    void run_background_monitor();
483
    void run_background_gc();
484
    void run_background_lru_log_replay();
485
    size_t replay_lru_logs_once();
486
    void run_background_lru_dump();
487
    void restore_lru_queues_from_disk(std::lock_guard<std::mutex>& cache_lock);
488
    void run_background_evict_in_advance();
489
    void run_background_block_lru_update();
490
491
    bool try_reserve_from_other_queue_by_time_interval(FileCacheType cur_type,
492
                                                       std::vector<FileCacheType> other_cache_types,
493
                                                       size_t size, int64_t cur_time,
494
                                                       std::lock_guard<std::mutex>& cache_lock,
495
                                                       bool evict_in_advance);
496
497
    bool try_reserve_from_other_queue_by_size(FileCacheType cur_type,
498
                                              std::vector<FileCacheType> other_cache_types,
499
                                              size_t size, std::lock_guard<std::mutex>& cache_lock,
500
                                              bool evict_in_advance);
501
502
    bool is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
503
                     bool evict_in_advance) const;
504
505
    void remove_file_blocks(std::vector<FileBlockCell*>&, std::lock_guard<std::mutex>&, bool sync,
506
                            std::string& reason);
507
508
    void find_evict_candidates(LRUQueue& queue, size_t size, size_t cur_cache_size,
509
                               size_t& removed_size, std::vector<FileBlockCell*>& to_evict,
510
                               std::lock_guard<std::mutex>& cache_lock, size_t& cur_removed_size,
511
                               bool evict_in_advance);
512
513
    Status check_ofstream_status(std::ofstream& out, std::string& filename);
514
    Status dump_one_lru_entry(std::ofstream& out, std::string& filename, const UInt128Wrapper& hash,
515
                              size_t offset, size_t size);
516
    Status finalize_dump(std::ofstream& out, size_t entry_num, std::string& tmp_filename,
517
                         std::string& final_filename, size_t& file_size);
518
    Status check_ifstream_status(std::ifstream& in, std::string& filename);
519
    Status parse_dump_footer(std::ifstream& in, std::string& filename, size_t& entry_num);
520
    Status parse_one_lru_entry(std::ifstream& in, std::string& filename, UInt128Wrapper& hash,
521
                               size_t& offset, size_t& size);
522
    void remove_lru_dump_files();
523
524
    void clear_need_update_lru_blocks();
525
526
    // info
527
    std::string _cache_base_path;
528
    size_t _capacity = 0;
529
    size_t _max_file_block_size = 0;
530
531
    mutable std::mutex _mutex;
532
    bool _close {false};
533
    std::mutex _close_mtx;
534
    std::condition_variable _close_cv;
535
    std::thread _cache_background_monitor_thread;
536
    std::thread _cache_background_gc_thread;
537
    std::thread _cache_background_evict_in_advance_thread;
538
    std::thread _cache_background_lru_dump_thread;
539
    std::thread _cache_background_lru_log_replay_thread;
540
    std::thread _cache_background_block_lru_update_thread;
541
    std::atomic_bool _async_open_done {false};
542
    // disk space or inode is less than the specified value
543
    bool _disk_resource_limit_mode {false};
544
    bool _need_evict_cache_in_advance {false};
545
    bool _is_initialized {false};
546
547
    // strategy
548
    using FileBlocksByOffset = std::map<size_t, FileBlockCell>;
549
    using CachedFiles = std::unordered_map<UInt128Wrapper, FileBlocksByOffset, KeyHash>;
550
    CachedFiles _files;
551
    QueryFileCacheContextMap _query_map;
552
    size_t _cur_cache_size = 0;
553
    size_t _cur_ttl_size = 0;
554
    std::multimap<uint64_t, UInt128Wrapper> _time_to_key;
555
    std::unordered_map<UInt128Wrapper, uint64_t, KeyHash> _key_to_time;
556
    // The three queues are level queue.
557
    // It means as level1/level2/level3 queue.
558
    // but the level2 is maximum.
559
    // If some datas are importance, we can cache it into index queue
560
    // If some datas are just use once, we can cache it into disposable queue
561
    // The size proportion is [1:17:2].
562
    LRUQueue _index_queue;
563
    LRUQueue _normal_queue;
564
    LRUQueue _disposable_queue;
565
    LRUQueue _ttl_queue;
566
567
    // keys for async remove
568
    RecycleFileCacheKeys _recycle_keys;
569
570
    std::unique_ptr<LRUQueueRecorder> _lru_recorder;
571
    std::unique_ptr<CacheLRUDumper> _lru_dumper;
572
    std::unique_ptr<BlockFileCacheTtlMgr> _ttl_mgr;
573
574
    // metrics
575
    std::shared_ptr<bvar::Status<size_t>> _cache_capacity_metrics;
576
    std::shared_ptr<bvar::Status<size_t>> _cur_cache_size_metrics;
577
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_size_metrics;
578
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_cache_size_metrics;
579
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_element_count_metrics;
580
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_element_count_metrics;
581
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_cache_size_metrics;
582
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_element_count_metrics;
583
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_cache_size_metrics;
584
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_element_count_metrics;
585
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_cache_size_metrics;
586
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _queue_evict_size_metrics;
587
    std::shared_ptr<bvar::Adder<size_t>> _total_read_size_metrics;
588
    std::shared_ptr<bvar::Adder<size_t>> _total_hit_size_metrics;
589
    std::shared_ptr<bvar::Adder<size_t>> _total_evict_size_metrics;
590
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_bytes_metrics;
591
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_count_metrics;
592
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_time_metrics_matrix[4][4];
593
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_size_metrics_matrix[4][4];
594
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_self_lru_metrics_matrix[4];
595
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_try_release;
596
597
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_5m;
598
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_5m;
599
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_1h;
600
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_1h;
601
602
    std::shared_ptr<bvar::Adder<size_t>> _num_read_blocks;
603
    std::shared_ptr<bvar::Adder<size_t>> _num_hit_blocks;
604
    std::shared_ptr<bvar::Adder<size_t>> _num_removed_blocks;
605
606
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_read_blocks;
607
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_hit_blocks;
608
609
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_5m;
610
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_5m;
611
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_1h;
612
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_1h;
613
614
    std::shared_ptr<bvar::Status<double>> _hit_ratio;
615
    std::shared_ptr<bvar::Status<double>> _hit_ratio_5m;
616
    std::shared_ptr<bvar::Status<double>> _hit_ratio_1h;
617
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio;
618
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_5m;
619
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_1h;
620
    std::shared_ptr<bvar::Status<size_t>> _disk_limit_mode_metrics;
621
    std::shared_ptr<bvar::Status<size_t>> _need_evict_cache_in_advance_metrics;
622
    std::shared_ptr<bvar::Status<size_t>> _meta_store_write_queue_size_metrics;
623
624
    std::shared_ptr<bvar::LatencyRecorder> _cache_lock_wait_time_us;
625
    std::shared_ptr<bvar::LatencyRecorder> _get_or_set_latency_us;
626
    std::shared_ptr<bvar::LatencyRecorder> _storage_sync_remove_latency_us;
627
    std::shared_ptr<bvar::LatencyRecorder> _storage_retry_sync_remove_latency_us;
628
    std::shared_ptr<bvar::LatencyRecorder> _storage_async_remove_latency_us;
629
    std::shared_ptr<bvar::LatencyRecorder> _evict_in_advance_latency_us;
630
    std::shared_ptr<bvar::LatencyRecorder> _recycle_keys_length_recorder;
631
    std::shared_ptr<bvar::LatencyRecorder> _update_lru_blocks_latency_us;
632
    std::shared_ptr<bvar::LatencyRecorder> _need_update_lru_blocks_length_recorder;
633
    std::shared_ptr<bvar::Adder<size_t>> _need_update_lru_blocks_produce_metrics;
634
    std::shared_ptr<bvar::Adder<size_t>> _need_update_lru_blocks_consume_metrics;
635
    std::shared_ptr<bvar::LatencyRecorder> _ttl_gc_latency_us;
636
637
    std::shared_ptr<bvar::LatencyRecorder> _shadow_queue_levenshtein_distance;
638
    std::array<std::shared_ptr<bvar::LatencyRecorder>, 4> _lru_recorder_queue_length_recorder;
639
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _lru_recorder_queue_produce_metrics;
640
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _lru_recorder_queue_consume_metrics;
641
    std::array<std::shared_ptr<bvar::Status<size_t>>, 4>
642
            _lru_recorder_shadow_queue_element_count_metrics;
643
    std::shared_ptr<bvar::Adder<size_t>> _lru_recorder_log_replay_idle_metrics;
644
    // keep _storage last so it will deconstruct first
645
    // otherwise, load_cache_info_into_memory might crash
646
    // coz it will use other members of BlockFileCache
647
    // so join this async load thread first
648
    std::unique_ptr<FileCacheStorage> _storage;
649
    std::shared_ptr<bvar::LatencyRecorder> _lru_dump_latency_us;
650
    std::mutex _dump_lru_queues_mtx;
651
    NeedUpdateLRUBlocks _need_update_lru_blocks;
652
};
653
654
} // namespace doris::io