Coverage Report

Created: 2026-08-20 20:03

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