Coverage Report

Created: 2026-11-03 13:05

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 <unordered_set>
37
#include <vector>
38
39
#include "io/cache/block_file_cache_ttl_mgr.h"
40
#include "io/cache/cache_lru_dumper.h"
41
#include "io/cache/file_block.h"
42
#include "io/cache/file_cache_common.h"
43
#include "io/cache/file_cache_storage.h"
44
#include "io/cache/lru_queue_recorder.h"
45
#include "runtime/runtime_profile.h"
46
47
namespace doris::io {
48
using RecycleFileCacheKeys = moodycamel::ConcurrentQueue<FileCacheKey>;
49
50
class LockScopedTimer {
51
public:
52
766k
    LockScopedTimer() : start_(std::chrono::steady_clock::now()) {}
53
766k
    ~LockScopedTimer() {
54
766k
        auto end = std::chrono::steady_clock::now();
55
766k
        auto duration_us =
56
766k
                std::chrono::duration_cast<std::chrono::microseconds>(end - start_).count();
57
766k
        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
766k
    }
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
766k
    std::chrono::time_point<std::chrono::steady_clock> start_time =                               \
70
766k
            std::chrono::steady_clock::now();                                                     \
71
766k
    std::lock_guard cache_lock(MUTEX);                                                            \
72
766k
    std::chrono::time_point<std::chrono::steady_clock> acq_time =                                 \
73
766k
            std::chrono::steady_clock::now();                                                     \
74
766k
    auto duration_us =                                                                            \
75
766k
            std::chrono::duration_cast<std::chrono::microseconds>(acq_time - start_time).count(); \
76
766k
    *(cache->_cache_lock_wait_time_us) << duration_us;                                            \
77
766k
    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
766k
    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
300
            : file_blocks(std::move(file_blocks_)) {}
90
25
    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
427
    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
2.70k
    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
730k
    void update_atime() const {
156
730k
        atime = std::chrono::duration_cast<std::chrono::seconds>(
157
730k
                        std::chrono::steady_clock::now().time_since_epoch())
158
730k
                        .count();
159
730k
    }
160
161
    /// Pointer to file block is always hold by the cache itself. Every other strong reference
162
    /// means somebody is still using the block. CachedRemoteFileReader keeps only weak references
163
    /// in its direct-read map, so however many readers know about a block, they do not keep it
164
    /// busy.
165
107k
    bool releasable() const { return file_block.use_count() == 1; }
166
167
751k
    size_t size() const { return file_block->_block_range.size(); }
168
169
    FileBlockCell() = default;
170
    FileBlockCell(FileBlockSPtr file_block, std::lock_guard<std::mutex>& cache_lock);
171
    FileBlockCell(FileBlockCell&& other) noexcept
172
230k
            : file_block(std::move(other.file_block)),
173
230k
              queue_iterator(other.queue_iterator),
174
230k
              atime(other.atime) {
175
230k
        file_block->cell = this;
176
230k
    }
177
178
    FileBlockCell& operator=(const FileBlockCell&) = delete;
179
    FileBlockCell(const FileBlockCell&) = delete;
180
181
0
    size_t dowloading_size() const { return file_block->_downloaded_size; }
182
};
183
184
class BlockFileCache {
185
    friend class FSFileCacheStorage;
186
    friend class MemFileCacheStorage;
187
    friend class FileBlock;
188
    friend struct FileBlocksHolder;
189
    friend class CacheLRUDumper;
190
    friend class LRUQueueRecorder;
191
    friend struct FileBlockCell;
192
    friend class BlockFileCacheTest;
193
194
public:
195
    // hash the file_name to uint128
196
    static UInt128Wrapper hash(const std::string& path);
197
198
    BlockFileCache(const std::string& cache_base_path, const FileCacheSettings& cache_settings);
199
200
    virtual ~BlockFileCache();
201
202
    /// Restore cache from local filesystem.
203
    Status initialize();
204
205
    /// Cache capacity in bytes.
206
14
    [[nodiscard]] size_t capacity() const { return _capacity; }
207
208
    // try to release all releasable block
209
    // it maybe hang the io/system
210
    size_t try_release();
211
212
1.77k
    [[nodiscard]] const std::string& get_base_path() const { return _cache_base_path; }
213
214
    // Get storage for inspection
215
0
    FileCacheStorage* get_storage() const { return _storage.get(); }
216
217
    /**
218
         * Given an `offset` and `size` representing [offset, offset + size) bytes interval,
219
         * return list of cached non-overlapping non-empty
220
         * file blocks `[block1, ..., blockN]` which intersect with given interval.
221
         *
222
         * blocks in returned list are ordered in ascending order and represent a full contiguous
223
         * interval (no holes). Each block in returned list has state: DOWNLOADED, DOWNLOADING or EMPTY.
224
         *
225
         * As long as pointers to returned file blocks are hold
226
         * it is guaranteed that these file blocks are not removed from cache.
227
         */
228
    FileBlocksHolder get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
229
                                CacheContext& context);
230
231
    /// Whether existing DOWNLOADED/DOWNLOADING blocks fully cover `[offset, offset + size)`.
232
    /// Handles arbitrary block boundaries, including restored upload blocks. May load metadata,
233
    /// but never reserves cache cells, waits for downloads or touches LRU state.
234
    bool is_range_downloaded_or_downloading(const UInt128Wrapper& hash, size_t offset, size_t size,
235
                                            const CacheContext& context);
236
237
    /// Probe the block-aligned `[offset, offset + size)` range without creating cache cells or
238
    /// touching LRU state. The result contains one ordered slot per cache block; each slot is null
239
    /// on miss or owns an existing block that starts at and covers the slot. A final short slot can
240
    /// be covered by a full-size block preallocated by a file writer. `context` supplies cache
241
    /// metadata when lazy loading is required.
242
    FileBlocksProbeResult probe(const UInt128Wrapper& hash, size_t offset, size_t size,
243
                                const CacheContext& context);
244
245
    /// Touch `block` after a successful local read, provided it is still the cached cell. The
246
    /// supplied `context` controls the target LRU queue and query-level accounting.
247
    void touch_probe_block_if_cached(const FileBlockSPtr& block, const CacheContext& context);
248
249
    /// Check whether `block` is being deleted while taking cache/block locks in canonical order.
250
    bool is_block_deleting(const FileBlockSPtr& block) const;
251
252
    /// Return this cache disk's async-write manager.
253
469
    AsyncCacheWriteManager* async_write_manager() const { return _async_write_manager.get(); }
254
255
    /// Return this cache disk's inflight payload index.
256
149
    InflightWriteBufferIndex* inflight_write_buffer_index() const {
257
149
        return _inflight_write_buffer_index.get();
258
149
    }
259
260
    /**
261
     * Return existing downloaded blocks only if they fully cover [offset, offset + size).
262
     * This lookup is read-only: it does not reserve cache space or create EMPTY blocks.
263
     */
264
    Status get_downloaded_blocks_if_fully_covered(const UInt128Wrapper& hash, size_t offset,
265
                                                  size_t size, const CacheContext& context,
266
                                                  FileBlocks* blocks, bool* fully_covered);
267
268
    /// Diagnostic snapshot of resident DOWNLOADED intervals, clipped to the requested range.
269
    /// Handles irregular block boundaries; never loads metadata, reserves space or touches LRU.
270
    std::vector<FileBlock::Range> downloaded_ranges(const UInt128Wrapper& hash, size_t offset,
271
                                                    size_t size);
272
273
    /**
274
     * record blocks read directly by CachedRemoteFileReader
275
     */
276
    void add_need_update_lru_block(FileBlockSPtr block);
277
278
    /**
279
     * Clear all cached data for this cache instance async
280
     *
281
     * @returns summary message
282
     */
283
    std::string clear_file_cache_async();
284
    std::string clear_file_cache_sync();
285
286
    /**
287
     * Reset the cache capacity. If the new_capacity is smaller than _capacity, the redundant data will be remove async.
288
     *
289
     * @returns summary message
290
     */
291
    std::string reset_capacity(size_t new_capacity);
292
293
    std::map<size_t, FileBlockSPtr> get_blocks_by_key(const UInt128Wrapper& hash);
294
295
    /// For debug and UT
296
    std::string dump_structure(const UInt128Wrapper& hash);
297
    std::string dump_single_cache_type(const UInt128Wrapper& hash, size_t offset);
298
299
    void dump_lru_queues(bool force);
300
301
    [[nodiscard]] size_t get_used_cache_size(FileCacheType type) const;
302
303
    [[nodiscard]] size_t get_file_blocks_num(FileCacheType type) const;
304
305
    // change the block cache type
306
    void change_cache_type(const UInt128Wrapper& hash, size_t offset, FileCacheType new_type,
307
                           std::lock_guard<std::mutex>& cache_lock);
308
309
    // remove all blocks that belong to the key
310
    void remove_if_cached(const UInt128Wrapper& key);
311
    void remove_if_cached_async(const UInt128Wrapper& key);
312
313
    // Reset the block size and keep FileBlock, LRU queue, and cache counters consistent.
314
    void reset_range(const UInt128Wrapper&, size_t offset, size_t old_size, size_t new_size,
315
                     std::lock_guard<std::mutex>& cache_lock);
316
317
    // get the hotest blocks message by key
318
    // The tuple is composed of <offset, size, cache_type, expiration_time>
319
    [[nodiscard]] std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>>
320
    get_hot_blocks_meta(const UInt128Wrapper& hash) const;
321
322
    [[nodiscard]] bool get_async_open_success() const { return _async_open_done; }
323
324
    // The manager that keeps cached blocks in the cache type their tablet's TTL asks for.
325
    // Exposed so that tests can drive it deterministically rather than race its threads.
326
    BlockFileCacheTtlMgr* get_ttl_mgr() { return _ttl_mgr.get(); }
327
328
    BlockFileCache& operator=(const BlockFileCache&) = delete;
329
    BlockFileCache(const BlockFileCache&) = delete;
330
331
    // try to reserve the new space for the new block if the cache is full
332
    bool try_reserve(const UInt128Wrapper& hash, const CacheContext& context, size_t offset,
333
                     size_t size, std::lock_guard<std::mutex>& cache_lock);
334
335
    /**
336
     * Proactively evict cache blocks to free up space before cache is full.
337
     * 
338
     * This function attempts to evict blocks from both NORMAL and TTL queues to maintain 
339
     * cache size below high watermark. Unlike try_reserve() which blocks until space is freed,
340
     * this function initiates asynchronous eviction in background.
341
     * 
342
     * @param size Number of bytes to try to evict
343
     * @param cache_lock Lock that must be held while accessing cache data structures
344
     * 
345
     * @pre Caller must hold cache_lock
346
     * @pre _need_evict_cache_in_advance must be true
347
     * @pre _recycle_keys queue must have capacity for evicted blocks
348
     */
349
    void try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock);
350
351
    void update_ttl_atime(const UInt128Wrapper& hash);
352
353
    std::map<std::string, double> get_stats();
354
355
    // for be UTs
356
    std::map<std::string, double> get_stats_unsafe();
357
    [[nodiscard]] size_t need_update_lru_blocks_size_unsafe() const {
358
        return _need_update_lru_blocks.size();
359
    }
360
361
    using AccessRecord =
362
            std::unordered_map<AccessKeyAndOffset, LRUQueue::Iterator, KeyAndOffsetHash>;
363
364
    /// Used to track and control the cache access of each query.
365
    /// Through it, we can realize the processing of different queries by the cache layer.
366
    struct QueryFileCacheContext {
367
        LRUQueue lru_queue;
368
        AccessRecord records;
369
370
5
        QueryFileCacheContext(size_t max_cache_size) : lru_queue(max_cache_size, 0, 0) {}
371
372
        void remove(const UInt128Wrapper& hash, size_t offset,
373
                    std::lock_guard<std::mutex>& cache_lock);
374
375
        void reserve(const UInt128Wrapper& hash, size_t offset, size_t size,
376
                     std::lock_guard<std::mutex>& cache_lock);
377
378
69
        size_t get_max_cache_size() const { return lru_queue.get_max_size(); }
379
380
48
        size_t get_cache_size(std::lock_guard<std::mutex>& cache_lock) const {
381
48
            return lru_queue.get_capacity(cache_lock);
382
48
        }
383
384
50
        LRUQueue& queue() { return lru_queue; }
385
    };
386
387
    using QueryFileCacheContextPtr = std::shared_ptr<QueryFileCacheContext>;
388
    using QueryFileCacheContextMap = std::unordered_map<TUniqueId, QueryFileCacheContextPtr>;
389
390
    QueryFileCacheContextPtr get_query_context(const TUniqueId& query_id,
391
                                               std::lock_guard<std::mutex>&);
392
393
    void remove_query_context(const TUniqueId& query_id);
394
395
    QueryFileCacheContextPtr get_or_set_query_context(const TUniqueId& query_id,
396
                                                      std::lock_guard<std::mutex>& cache_lock,
397
                                                      int file_cache_query_limit_percent);
398
399
    /// Save a query context information, and adopt different cache policies
400
    /// for different queries through the context cache layer.
401
    struct QueryFileCacheContextHolder {
402
        QueryFileCacheContextHolder(const TUniqueId& query_id, BlockFileCache* mgr,
403
                                    QueryFileCacheContextPtr context)
404
7
                : query_id(query_id), mgr(mgr), context(context) {}
405
406
        QueryFileCacheContextHolder& operator=(const QueryFileCacheContextHolder&) = delete;
407
        QueryFileCacheContextHolder(const QueryFileCacheContextHolder&) = delete;
408
409
7
        ~QueryFileCacheContextHolder() {
410
            /// If only the query_map and the current holder hold the context_query,
411
            /// the query has been completed and the query_context is released.
412
7
            if (context) {
413
6
                context.reset();
414
6
                mgr->remove_query_context(query_id);
415
6
            }
416
7
        }
417
418
        const TUniqueId& query_id;
419
        BlockFileCache* mgr = nullptr;
420
        QueryFileCacheContextPtr context;
421
    };
422
    using QueryFileCacheContextHolderPtr = std::unique_ptr<QueryFileCacheContextHolder>;
423
    QueryFileCacheContextHolderPtr get_query_context_holder(const TUniqueId& query_id,
424
                                                            int file_cache_query_limit_percent);
425
426
0
    int64_t approximate_available_cache_size() const {
427
0
        return std::max<int64_t>(
428
0
                _cache_capacity_metrics->get_value() - _cur_cache_size_metrics->get_value(), 0);
429
0
    }
430
431
    Status report_file_cache_inconsistency(std::vector<std::string>& results);
432
    Status check_file_cache_consistency(InconsistencyContext& inconsistency_context);
433
434
private:
435
    // Shared scan used by both clear modes. It keeps the FileBlock holder lifecycle intact:
436
    // releasable blocks are removed immediately, while blocks held by readers are only marked
437
    // deleting and are later removed by FileBlocksHolder destruction or, when the last holder
438
    // does not release through FileBlock::release_cache_reference(), by run_background_gc().
439
    std::string clear_file_cache_impl(bool sync_remove);
440
441
    LRUQueue& get_queue(FileCacheType type);
442
    const LRUQueue& get_queue(FileCacheType type) const;
443
444
    template <class T, class U>
445
        requires IsXLock<T> && IsXLock<U>
446
    void remove(FileBlockSPtr file_block, T& cache_lock, U& segment_lock, bool sync = true);
447
448
    FileBlocks get_impl(const UInt128Wrapper& hash, const CacheContext& context,
449
                        const FileBlock::Range& range, std::lock_guard<std::mutex>& cache_lock);
450
451
    template <class T>
452
        requires IsXLock<T>
453
    FileBlockCell* get_cell(const UInt128Wrapper& hash, size_t offset, T& cache_lock);
454
455
    virtual FileBlockCell* add_cell(const UInt128Wrapper& hash, const CacheContext& context,
456
                                    size_t offset, size_t size, FileBlock::State state,
457
                                    std::lock_guard<std::mutex>& cache_lock);
458
459
    Status initialize_unlocked(std::lock_guard<std::mutex>& cache_lock);
460
461
    void update_block_lru(FileBlockSPtr block, std::lock_guard<std::mutex>& cache_lock);
462
463
    void use_cell(const FileBlockCell& cell, FileBlocks* result, bool not_need_move,
464
                  std::lock_guard<std::mutex>& cache_lock);
465
466
    bool try_reserve_for_lru(const UInt128Wrapper& hash, QueryFileCacheContextPtr query_context,
467
                             const CacheContext& context, size_t offset, size_t size,
468
                             std::lock_guard<std::mutex>& cache_lock,
469
                             bool evict_in_advance = false);
470
471
    bool try_reserve_during_async_load(size_t size, std::lock_guard<std::mutex>& cache_lock);
472
473
    std::vector<FileCacheType> get_other_cache_type(FileCacheType cur_cache_type);
474
    std::vector<FileCacheType> get_other_cache_type_without_ttl(FileCacheType cur_cache_type);
475
476
    bool try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t offset, int64_t cur_time,
477
                                      std::lock_guard<std::mutex>& cache_lock,
478
                                      bool evict_in_advance = false);
479
480
    size_t get_available_cache_size(FileCacheType cache_type) const;
481
482
    FileBlocks split_range_into_cells(const UInt128Wrapper& hash, const CacheContext& context,
483
                                      size_t offset, size_t size, FileBlock::State state,
484
                                      std::lock_guard<std::mutex>& cache_lock);
485
486
    std::string dump_structure_unlocked(const UInt128Wrapper& hash,
487
                                        std::lock_guard<std::mutex>& cache_lock);
488
489
    std::string dump_single_cache_type_unlocked(const UInt128Wrapper& hash, size_t offset,
490
                                                std::lock_guard<std::mutex>& cache_lock);
491
492
    void fill_holes_with_empty_file_blocks(FileBlocks& file_blocks, const UInt128Wrapper& hash,
493
                                           const CacheContext& context,
494
                                           const FileBlock::Range& range,
495
                                           std::lock_guard<std::mutex>& cache_lock);
496
497
    size_t get_used_cache_size_unlocked(FileCacheType type,
498
                                        std::lock_guard<std::mutex>& cache_lock) const;
499
500
    void check_disk_resource_limit();
501
    void check_need_evict_cache_in_advance();
502
503
    size_t get_available_cache_size_unlocked(FileCacheType type,
504
                                             std::lock_guard<std::mutex>& cache_lock) const;
505
506
    size_t get_file_blocks_num_unlocked(FileCacheType type,
507
                                        std::lock_guard<std::mutex>& cache_lock) const;
508
509
    bool need_to_move(FileCacheType cell_type, FileCacheType query_type) const;
510
511
    void run_background_monitor();
512
    void run_background_gc();
513
    void run_background_lru_log_replay();
514
    size_t replay_lru_logs_once();
515
    void run_background_lru_dump();
516
    void restore_lru_queues_from_disk(std::lock_guard<std::mutex>& cache_lock);
517
    void run_background_evict_in_advance();
518
    void run_background_block_lru_update();
519
520
    bool try_reserve_from_other_queue_by_time_interval(FileCacheType cur_type,
521
                                                       std::vector<FileCacheType> other_cache_types,
522
                                                       size_t size, int64_t cur_time,
523
                                                       std::lock_guard<std::mutex>& cache_lock,
524
                                                       bool evict_in_advance);
525
526
    bool try_reserve_from_other_queue_by_size(FileCacheType cur_type,
527
                                              std::vector<FileCacheType> other_cache_types,
528
                                              size_t size, std::lock_guard<std::mutex>& cache_lock,
529
                                              bool evict_in_advance);
530
531
    bool is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
532
                     bool evict_in_advance) const;
533
534
    void remove_file_blocks(std::vector<FileBlockCell*>&, std::lock_guard<std::mutex>&, bool sync,
535
                            std::string& reason);
536
537
    void find_evict_candidates(LRUQueue& queue, size_t size, size_t cur_cache_size,
538
                               size_t& removed_size, std::vector<FileBlockCell*>& to_evict,
539
                               std::lock_guard<std::mutex>& cache_lock, size_t& cur_removed_size,
540
                               bool evict_in_advance);
541
542
    Status check_ofstream_status(std::ofstream& out, std::string& filename);
543
    Status dump_one_lru_entry(std::ofstream& out, std::string& filename, const UInt128Wrapper& hash,
544
                              size_t offset, size_t size);
545
    Status finalize_dump(std::ofstream& out, size_t entry_num, std::string& tmp_filename,
546
                         std::string& final_filename, size_t& file_size);
547
    Status check_ifstream_status(std::ifstream& in, std::string& filename);
548
    Status parse_dump_footer(std::ifstream& in, std::string& filename, size_t& entry_num);
549
    Status parse_one_lru_entry(std::ifstream& in, std::string& filename, UInt128Wrapper& hash,
550
                               size_t& offset, size_t& size);
551
    void remove_lru_dump_files();
552
553
    void clear_need_update_lru_blocks();
554
555
    // Marks a cell that cannot be erased yet as deleting and remembers it in _deleting_blocks, so
556
    // that the block is still reclaimed when its last reference is dropped without going through
557
    // FileBlock::release_cache_reference(). This is the only place that sets a block deleting.
558
    template <class T>
559
        requires IsXLock<T>
560
    void mark_cell_deleting(FileBlockCell& cell, T& cache_lock);
561
562
    // Removes up to batch_limit blocks that were marked deleting and are not referenced any
563
    // more. Returns how many of them were removed.
564
    size_t recycle_deleting_blocks(size_t batch_limit);
565
566
    // info
567
    std::string _cache_base_path;
568
    size_t _capacity = 0;
569
    size_t _max_file_block_size = 0;
570
571
    mutable std::mutex _mutex;
572
    bool _close {false};
573
    std::mutex _close_mtx;
574
    std::condition_variable _close_cv;
575
    std::thread _cache_background_monitor_thread;
576
    std::thread _cache_background_gc_thread;
577
    std::thread _cache_background_evict_in_advance_thread;
578
    std::thread _cache_background_lru_dump_thread;
579
    std::thread _cache_background_lru_log_replay_thread;
580
    std::thread _cache_background_block_lru_update_thread;
581
    std::atomic_bool _async_open_done {false};
582
    // disk space or inode is less than the specified value
583
    std::atomic<bool> _disk_resource_limit_mode {false};
584
    std::atomic<bool> _need_evict_cache_in_advance {false};
585
    bool _is_initialized {false};
586
587
    // strategy
588
    using FileBlocksByOffset = std::map<size_t, FileBlockCell>;
589
    using CachedFiles = std::unordered_map<UInt128Wrapper, FileBlocksByOffset, KeyHash>;
590
    CachedFiles _files;
591
    QueryFileCacheContextMap _query_map;
592
    size_t _cur_cache_size = 0;
593
    size_t _cur_ttl_size = 0;
594
    std::multimap<uint64_t, UInt128Wrapper> _time_to_key;
595
    std::unordered_map<UInt128Wrapper, uint64_t, KeyHash> _key_to_time;
596
    // The three queues are level queue.
597
    // It means as level1/level2/level3 queue.
598
    // but the level2 is maximum.
599
    // If some datas are importance, we can cache it into index queue
600
    // If some datas are just use once, we can cache it into disposable queue
601
    // The size proportion is [1:17:2].
602
    LRUQueue _index_queue;
603
    LRUQueue _normal_queue;
604
    LRUQueue _disposable_queue;
605
    LRUQueue _ttl_queue;
606
607
    // keys for async remove
608
    RecycleFileCacheKeys _recycle_keys;
609
610
    // Blocks that were busy when something asked to delete them. They keep sitting in _files
611
    // until their last reference goes away. Only FileBlocksHolder and FileBlocksProbeResult
612
    // release through FileBlock::release_cache_reference(), which is the one path that notices
613
    // is_deleting and removes the block; every other reference holder just drops its shared_ptr
614
    // and would strand the block here forever. run_background_gc() rechecks these candidates and
615
    // removes the ones that became releasable.
616
    //
617
    // Invariant: holds exactly the keys of the cells in _files whose block is deleting. A key is
618
    // added by mark_cell_deleting() and erased by remove() together with its cell, so a block
619
    // created later at the same offset is never taken for the one that was marked.
620
    std::unordered_set<AccessKeyAndOffset, KeyAndOffsetHash> _deleting_blocks;
621
622
    std::unique_ptr<LRUQueueRecorder> _lru_recorder;
623
    std::unique_ptr<CacheLRUDumper> _lru_dumper;
624
    std::unique_ptr<BlockFileCacheTtlMgr> _ttl_mgr;
625
626
    std::unique_ptr<InflightWriteBufferIndex> _inflight_write_buffer_index;
627
    std::unique_ptr<AsyncCacheWriteManager> _async_write_manager;
628
629
    // metrics
630
    std::shared_ptr<bvar::Status<size_t>> _cache_capacity_metrics;
631
    std::shared_ptr<bvar::Status<size_t>> _cur_cache_size_metrics;
632
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_size_metrics;
633
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_cache_size_metrics;
634
    std::shared_ptr<bvar::Status<size_t>> _cur_ttl_cache_lru_queue_element_count_metrics;
635
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_element_count_metrics;
636
    std::shared_ptr<bvar::Status<size_t>> _cur_normal_queue_cache_size_metrics;
637
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_element_count_metrics;
638
    std::shared_ptr<bvar::Status<size_t>> _cur_index_queue_cache_size_metrics;
639
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_element_count_metrics;
640
    std::shared_ptr<bvar::Status<size_t>> _cur_disposable_queue_cache_size_metrics;
641
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _queue_evict_size_metrics;
642
    std::shared_ptr<bvar::Adder<size_t>> _total_read_size_metrics;
643
    std::shared_ptr<bvar::Adder<size_t>> _total_hit_size_metrics;
644
    std::shared_ptr<bvar::Adder<size_t>> _total_evict_size_metrics;
645
    std::shared_ptr<bvar::Adder<size_t>> _evict_not_downloaded_size_metrics;
646
    std::shared_ptr<bvar::Adder<size_t>> _evict_not_downloaded_num_metrics;
647
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_bytes_metrics;
648
    std::shared_ptr<bvar::Adder<size_t>> _gc_evict_count_metrics;
649
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_time_metrics_matrix[4][4];
650
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_size_metrics_matrix[4][4];
651
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_self_lru_metrics_matrix[4];
652
    std::shared_ptr<bvar::Adder<size_t>> _evict_by_try_release;
653
654
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_5m;
655
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_5m;
656
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_hit_blocks_1h;
657
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _num_read_blocks_1h;
658
659
    std::shared_ptr<bvar::Adder<size_t>> _num_read_blocks;
660
    std::shared_ptr<bvar::Adder<size_t>> _num_hit_blocks;
661
    std::shared_ptr<bvar::Adder<size_t>> _num_removed_blocks;
662
663
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_read_blocks;
664
    std::shared_ptr<bvar::Adder<size_t>> _no_warmup_num_hit_blocks;
665
666
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_5m;
667
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_5m;
668
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_hit_blocks_1h;
669
    std::shared_ptr<bvar::Window<bvar::Adder<size_t>>> _no_warmup_num_read_blocks_1h;
670
671
    std::shared_ptr<bvar::Status<double>> _hit_ratio;
672
    std::shared_ptr<bvar::Status<double>> _hit_ratio_5m;
673
    std::shared_ptr<bvar::Status<double>> _hit_ratio_1h;
674
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio;
675
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_5m;
676
    std::shared_ptr<bvar::Status<double>> _no_warmup_hit_ratio_1h;
677
    std::shared_ptr<bvar::Status<size_t>> _disk_limit_mode_metrics;
678
    std::shared_ptr<bvar::Status<size_t>> _need_evict_cache_in_advance_metrics;
679
    std::shared_ptr<bvar::Status<size_t>> _meta_store_write_queue_size_metrics;
680
681
    std::shared_ptr<bvar::LatencyRecorder> _cache_lock_wait_time_us;
682
    std::shared_ptr<bvar::LatencyRecorder> _get_or_set_latency_us;
683
    std::shared_ptr<bvar::LatencyRecorder> _probe_latency_us;
684
    std::shared_ptr<bvar::LatencyRecorder> _storage_sync_remove_latency_us;
685
    std::shared_ptr<bvar::LatencyRecorder> _storage_retry_sync_remove_latency_us;
686
    std::shared_ptr<bvar::LatencyRecorder> _storage_async_remove_latency_us;
687
    std::shared_ptr<bvar::LatencyRecorder> _evict_in_advance_latency_us;
688
    std::shared_ptr<bvar::LatencyRecorder> _recycle_keys_length_recorder;
689
    std::shared_ptr<bvar::Status<size_t>> _deleting_block_count_metrics;
690
    std::shared_ptr<bvar::Adder<size_t>> _recycle_deleting_blocks_metrics;
691
    std::shared_ptr<bvar::LatencyRecorder> _update_lru_blocks_latency_us;
692
    std::shared_ptr<bvar::LatencyRecorder> _need_update_lru_blocks_length_recorder;
693
    std::shared_ptr<bvar::Adder<size_t>> _need_update_lru_blocks_produce_metrics;
694
    std::shared_ptr<bvar::Adder<size_t>> _need_update_lru_blocks_consume_metrics;
695
    std::shared_ptr<bvar::LatencyRecorder> _ttl_gc_latency_us;
696
697
    std::shared_ptr<bvar::LatencyRecorder> _shadow_queue_levenshtein_distance;
698
    std::array<std::shared_ptr<bvar::LatencyRecorder>, 4> _lru_recorder_queue_length_recorder;
699
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _lru_recorder_queue_produce_metrics;
700
    std::array<std::shared_ptr<bvar::Adder<size_t>>, 4> _lru_recorder_queue_consume_metrics;
701
    std::array<std::shared_ptr<bvar::Status<size_t>>, 4>
702
            _lru_recorder_shadow_queue_element_count_metrics;
703
    std::shared_ptr<bvar::Adder<size_t>> _lru_recorder_log_replay_idle_metrics;
704
    // keep _storage last so it will deconstruct first
705
    // otherwise, load_cache_info_into_memory might crash
706
    // coz it will use other members of BlockFileCache
707
    // so join this async load thread first
708
    std::unique_ptr<FileCacheStorage> _storage;
709
    std::shared_ptr<bvar::LatencyRecorder> _lru_dump_latency_us;
710
    std::mutex _dump_lru_queues_mtx;
711
    NeedUpdateLRUBlocks _need_update_lru_blocks;
712
};
713
714
} // namespace doris::io