Coverage Report

Created: 2026-04-14 05:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/lru_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
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
19
// Use of this source code is governed by a BSD-style license that can be
20
// found in the LICENSE file. See the AUTHORS file for names of contributors.
21
22
#pragma once
23
24
#include <butil/macros.h>
25
#include <bvar/bvar.h>
26
#include <glog/logging.h>
27
#include <gtest/gtest_prod.h>
28
29
#include <atomic>
30
#include <cassert>
31
#include <cstdint>
32
#include <cstdlib>
33
#include <cstring>
34
#include <functional>
35
#include <memory>
36
#include <set>
37
#include <string>
38
#include <utility>
39
40
#include "common/metrics/doris_metrics.h"
41
#include "common/metrics/metrics.h"
42
#include "runtime/memory/lru_cache_value_base.h"
43
44
namespace doris {
45
46
class Cache;
47
class LRUCachePolicy;
48
struct LRUHandle;
49
50
enum LRUCacheType {
51
    SIZE, // The capacity of cache is based on the memory size of cache entry, memory size = handle size + charge.
52
    NUMBER // The capacity of cache is based on the number of cache entry, number = charge, the weight of an entry.
53
};
54
55
static constexpr LRUCacheType DEFAULT_LRU_CACHE_TYPE = LRUCacheType::SIZE;
56
static constexpr uint32_t DEFAULT_LRU_CACHE_NUM_SHARDS = 32;
57
static constexpr size_t DEFAULT_LRU_CACHE_ELEMENT_COUNT_CAPACITY = 0;
58
static constexpr bool DEFAULT_LRU_CACHE_IS_LRU_K = false;
59
60
class CacheKey {
61
public:
62
0
    CacheKey() : _size(0) {}
63
    // Create a slice that refers to d[0,n-1].
64
19.4M
    CacheKey(const char* d, size_t n) : _data(d), _size(n) {}
65
66
    // Create a slice that refers to the contents of "s"
67
23.9M
    CacheKey(const std::string& s) : _data(s.data()), _size(s.size()) {}
68
69
    // Create a slice that refers to s[0,strlen(s)-1]
70
    CacheKey(const char* s) : _data(s), _size(strlen(s)) {}
71
72
    ~CacheKey() = default;
73
74
    // Return a pointer to the beginning of the referenced data
75
59.9M
    const char* data() const { return _data; }
76
77
    // Return the length (in bytes) of the referenced data
78
83.3M
    size_t size() const { return _size; }
79
80
    // Return true if the length of the referenced data is zero
81
0
    bool empty() const { return _size == 0; }
82
83
    // Return the ith byte in the referenced data.
84
    // REQUIRES: n < size()
85
0
    char operator[](size_t n) const {
86
0
        assert(n < size());
87
0
        return _data[n];
88
0
    }
89
90
    // Change this slice to refer to an empty array
91
0
    void clear() {
92
0
        _data = nullptr;
93
0
        _size = 0;
94
0
    }
95
96
    // Drop the first "n" bytes from this slice.
97
0
    void remove_prefix(size_t n) {
98
0
        assert(n <= size());
99
0
        _data += n;
100
0
        _size -= n;
101
0
    }
102
103
    // Return a string that contains the copy of the referenced data.
104
43.6k
    std::string to_string() const { return {_data, _size}; }
105
106
16.2M
    bool operator==(const CacheKey& other) const {
107
16.2M
        return ((size() == other.size()) && (memcmp(data(), other.data(), size()) == 0));
108
16.2M
    }
109
110
16.3M
    bool operator!=(const CacheKey& other) const { return !(*this == other); }
111
112
0
    int compare(const CacheKey& b) const {
113
0
        const size_t min_len = (_size < b._size) ? _size : b._size;
114
0
        int r = memcmp(_data, b._data, min_len);
115
0
        if (r == 0) {
116
0
            if (_size < b._size) {
117
0
                r = -1;
118
0
            } else if (_size > b._size) {
119
0
                r = +1;
120
0
            }
121
0
        }
122
0
        return r;
123
0
    }
124
125
    uint32_t hash(const char* data, size_t n, uint32_t seed) const;
126
127
    // Return true if "x" is a prefix of "*this"
128
0
    bool starts_with(const CacheKey& x) const {
129
0
        return ((_size >= x._size) && (memcmp(_data, x._data, x._size) == 0));
130
0
    }
131
132
private:
133
525M
    uint32_t _decode_fixed32(const char* ptr) const {
134
        // Load the raw bytes
135
525M
        uint32_t result;
136
525M
        memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
137
525M
        return result;
138
525M
    }
139
140
    const char* _data = nullptr;
141
    size_t _size;
142
};
143
144
// The entry with smaller CachePriority will evict firstly
145
enum class CachePriority { NORMAL = 0, DURABLE = 1 };
146
147
using CachePrunePredicate = std::function<bool(const LRUHandle*)>;
148
// CacheValueTimeExtractor can extract timestamp
149
// in cache value through the specified function,
150
// such as last_visit_time in InvertedIndexSearcherCache::CacheValue
151
using CacheValueTimeExtractor = std::function<int64_t(const void*)>;
152
struct PrunedInfo {
153
    int64_t pruned_count = 0;
154
    int64_t pruned_size = 0;
155
};
156
157
class Cache {
158
public:
159
1.29k
    Cache() = default;
160
161
    // Destroys all existing entries by calling the "deleter"
162
    // function that was passed to the constructor.
163
1.21k
    virtual ~Cache() = default;
164
165
    // Opaque handle to an entry stored in the cache.
166
    struct Handle {};
167
168
    // Insert a mapping from key->value into the cache and assign it
169
    // the specified charge against the total cache capacity.
170
    //
171
    // Returns a handle that corresponds to the mapping.  The caller
172
    // must call this->release(handle) when the returned mapping is no
173
    // longer needed.
174
    //
175
    // When the inserted entry is no longer needed, the key and
176
    // value will be passed to "deleter".
177
    //
178
    // if cache is lru k and cache is full, first insert of key will not succeed.
179
    //
180
    // Note: if is ShardedLRUCache, cache capacity = ShardedLRUCache_capacity / num_shards.
181
    virtual Handle* insert(const CacheKey& key, void* value, size_t charge,
182
                           CachePriority priority = CachePriority::NORMAL) = 0;
183
184
    // If the cache has no mapping for "key", returns nullptr.
185
    //
186
    // Else return a handle that corresponds to the mapping.  The caller
187
    // must call this->release(handle) when the returned mapping is no
188
    // longer needed.
189
    virtual Handle* lookup(const CacheKey& key) = 0;
190
191
    // Release a mapping returned by a previous Lookup().
192
    // REQUIRES: handle must not have been released yet.
193
    // REQUIRES: handle must have been returned by a method on *this.
194
    virtual void release(Handle* handle) = 0;
195
196
    // Return the value encapsulated in a handle returned by a
197
    // successful lookup().
198
    // REQUIRES: handle must not have been released yet.
199
    // REQUIRES: handle must have been returned by a method on *this.
200
    virtual void* value(Handle* handle) = 0;
201
202
    // If the cache contains entry for key, erase it.  Note that the
203
    // underlying entry will be kept around until all existing handles
204
    // to it have been released.
205
    virtual void erase(const CacheKey& key) = 0;
206
207
    // Return a new numeric id.  May be used by multiple clients who are
208
    // sharing the same cache to partition the key space.  Typically the
209
    // client will allocate a new id at startup and prepend the id to
210
    // its cache keys.
211
    virtual uint64_t new_id() = 0;
212
213
    // Remove all cache entries that are not actively in use.  Memory-constrained
214
    // applications may wish to call this method to reduce memory usage.
215
    // Default implementation of Prune() does nothing.  Subclasses are strongly
216
    // encouraged to override the default implementation.  A future release of
217
    // leveldb may change prune() to a pure abstract method.
218
    // return num of entries being pruned.
219
0
    virtual PrunedInfo prune() { return {0, 0}; }
220
221
    // Same as prune(), but the entry will only be pruned if the predicate matched.
222
    // NOTICE: the predicate should be simple enough, or the prune_if() function
223
    // may hold lock for a long time to execute predicate.
224
0
    virtual PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) { return {0, 0}; }
225
226
    virtual void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) = 0;
227
228
    virtual int64_t get_usage() = 0;
229
230
    virtual PrunedInfo set_capacity(size_t capacity) = 0;
231
    virtual size_t get_capacity() = 0;
232
233
    virtual size_t get_element_count() = 0;
234
235
private:
236
    DISALLOW_COPY_AND_ASSIGN(Cache);
237
};
238
239
// An entry is a variable length heap-allocated structure.  Entries
240
// are kept in a circular doubly linked list ordered by access time.
241
// Note: member variables can only be POD types and raw pointer,
242
// cannot be class objects or smart pointers, because LRUHandle will be created using malloc.
243
struct LRUHandle {
244
    void* value = nullptr;
245
    struct LRUHandle* next_hash = nullptr; // next entry in hash table
246
    struct LRUHandle* next = nullptr;      // next entry in lru list
247
    struct LRUHandle* prev = nullptr;      // previous entry in lru list
248
    size_t charge;
249
    size_t key_length;
250
    size_t total_size; // Entry charge, used to limit cache capacity, LRUCacheType::SIZE including key length.
251
    bool in_cache; // Whether entry is in the cache.
252
    uint32_t refs;
253
    uint32_t hash; // Hash of key(); used for fast sharding and comparisons
254
    CachePriority priority = CachePriority::NORMAL;
255
    LRUCacheType type;
256
    int64_t last_visit_time; // Save the last visit time of this cache entry.
257
    char key_data[1];        // Beginning of key
258
    // Note! key_data must be at the end.
259
260
18.8M
    CacheKey key() const {
261
        // For cheaper lookups, we allow a temporary Handle object
262
        // to store a pointer to a key in "value".
263
18.8M
        if (next == this) {
264
0
            return *(reinterpret_cast<CacheKey*>(value));
265
18.8M
        } else {
266
18.8M
            return {key_data, key_length};
267
18.8M
        }
268
18.8M
    }
269
270
1.89M
    void free() {
271
1.89M
        if (value != nullptr) { // value allows null pointer.
272
1.87M
            delete (LRUCacheValueBase*)value;
273
1.87M
        }
274
1.89M
        ::free(this);
275
1.89M
    }
276
};
277
278
// We provide our own simple hash tablet since it removes a whole bunch
279
// of porting hacks and is also faster than some of the built-in hash
280
// tablet implementations in some of the compiler/runtime combinations
281
// we have tested.  E.g., readrandom speeds up by ~5% over the g++
282
// 4.4.3's builtin hashtable.
283
284
class HandleTable {
285
public:
286
30.3k
    HandleTable() { _resize(); }
287
288
    ~HandleTable();
289
290
    LRUHandle* lookup(const CacheKey& key, uint32_t hash);
291
292
    LRUHandle* insert(LRUHandle* h);
293
294
    // Remove element from hash table by "key" and "hash".
295
    LRUHandle* remove(const CacheKey& key, uint32_t hash);
296
297
    // Remove element from hash table by "h", it would be faster
298
    // than the function above.
299
    // Return whether h is found and removed.
300
    bool remove(const LRUHandle* h);
301
302
    uint32_t element_count() const;
303
304
private:
305
    FRIEND_TEST(CacheTest, HandleTableTest);
306
307
    // The tablet consists of an array of buckets where each bucket is
308
    // a linked list of cache entries that hash into the bucket.
309
    uint32_t _length {};
310
    uint32_t _elems {};
311
    LRUHandle** _list = nullptr;
312
313
    // Return a pointer to slot that points to a cache entry that
314
    // matches key/hash.  If there is no such cache entry, return a
315
    // pointer to the trailing slot in the corresponding linked list.
316
    LRUHandle** _find_pointer(const CacheKey& key, uint32_t hash);
317
318
    void _resize();
319
};
320
321
// pair first is timestatmp, put <timestatmp, LRUHandle*> into asc set,
322
// when need to free space, can first evict the begin of the set,
323
// because the begin element's timestamp is the oldest.
324
using LRUHandleSortedSet = std::set<std::pair<int64_t, LRUHandle*>>;
325
326
// A single shard of sharded cache.
327
class LRUCache {
328
public:
329
    LRUCache(LRUCacheType type, bool is_lru_k = DEFAULT_LRU_CACHE_IS_LRU_K);
330
    ~LRUCache();
331
332
    // visits_lru_cache_key is the hash value of CacheKey.
333
    // If there is a hash conflict, a cache entry may be inserted early
334
    // and another cache entry with the same key hash may be inserted later.
335
    // Otherwise, this does not affect the correctness of the cache.
336
    using visits_lru_cache_key = uint32_t;
337
    using visits_lru_cache_pair = std::pair<visits_lru_cache_key, size_t>;
338
339
    // Separate from constructor so caller can easily make an array of LRUCache
340
    PrunedInfo set_capacity(size_t capacity);
341
30.3k
    void set_element_count_capacity(uint32_t element_count_capacity) {
342
30.3k
        _element_count_capacity = element_count_capacity;
343
30.3k
    }
344
345
    // Like Cache methods, but with an extra "hash" parameter.
346
    // Must call release on the returned handle pointer.
347
    Cache::Handle* insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
348
                          CachePriority priority = CachePriority::NORMAL);
349
    Cache::Handle* lookup(const CacheKey& key, uint32_t hash);
350
    void release(Cache::Handle* handle);
351
    void erase(const CacheKey& key, uint32_t hash);
352
    PrunedInfo prune();
353
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false);
354
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor);
355
356
    void set_cache_value_time_extractor(CacheValueTimeExtractor cache_value_time_extractor);
357
    void set_cache_value_check_timestamp(bool cache_value_check_timestamp);
358
359
    uint64_t get_lookup_count();
360
    uint64_t get_hit_count();
361
    uint64_t get_miss_count();
362
    uint64_t get_stampede_count();
363
364
    size_t get_usage();
365
    size_t get_capacity();
366
    size_t get_element_count();
367
368
private:
369
    void _lru_remove(LRUHandle* e);
370
    void _lru_append(LRUHandle* list, LRUHandle* e);
371
    bool _unref(LRUHandle* e);
372
    void _evict_from_lru(size_t total_size, LRUHandle** to_remove_head);
373
    void _evict_from_lru_with_time(size_t total_size, LRUHandle** to_remove_head);
374
    void _evict_one_entry(LRUHandle* e);
375
    bool _check_element_count_limit();
376
    bool _lru_k_insert_visits_list(size_t total_size, visits_lru_cache_key visits_key);
377
378
private:
379
    LRUCacheType _type;
380
381
    // Initialized before use.
382
    size_t _capacity = 0;
383
384
    // _mutex protects the following state.
385
    std::mutex _mutex;
386
    size_t _usage = 0;
387
388
    // Dummy head of LRU list.
389
    // Entries have refs==1 and in_cache==true.
390
    // _lru_normal.prev is newest entry, _lru_normal.next is oldest entry.
391
    LRUHandle _lru_normal;
392
    // _lru_durable.prev is newest entry, _lru_durable.next is oldest entry.
393
    LRUHandle _lru_durable;
394
395
    HandleTable _table;
396
397
    uint64_t _lookup_count = 0; // number of cache lookups
398
    uint64_t _hit_count = 0;    // number of cache hits
399
    uint64_t _miss_count = 0;   // number of cache misses
400
    uint64_t _stampede_count = 0;
401
402
    CacheValueTimeExtractor _cache_value_time_extractor;
403
    bool _cache_value_check_timestamp = false;
404
    LRUHandleSortedSet _sorted_normal_entries_with_timestamp;
405
    LRUHandleSortedSet _sorted_durable_entries_with_timestamp;
406
407
    uint32_t _element_count_capacity = 0;
408
409
    bool _is_lru_k = false; // LRU-K algorithm, K=2
410
    std::list<visits_lru_cache_pair> _visits_lru_cache_list;
411
    std::unordered_map<visits_lru_cache_key, std::list<visits_lru_cache_pair>::iterator>
412
            _visits_lru_cache_map;
413
    size_t _visits_lru_cache_usage = 0;
414
};
415
416
class ShardedLRUCache : public Cache {
417
public:
418
    ~ShardedLRUCache() override;
419
    Handle* insert(const CacheKey& key, void* value, size_t charge,
420
                   CachePriority priority = CachePriority::NORMAL) override;
421
    Handle* lookup(const CacheKey& key) override;
422
    void release(Handle* handle) override;
423
    void erase(const CacheKey& key) override;
424
    void* value(Handle* handle) override;
425
    uint64_t new_id() override;
426
    PrunedInfo prune() override;
427
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) override;
428
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) override;
429
    int64_t get_usage() override;
430
    size_t get_element_count() override;
431
    PrunedInfo set_capacity(size_t capacity) override;
432
    size_t get_capacity() override;
433
434
private:
435
    // LRUCache can only be created and managed with LRUCachePolicy.
436
    friend class LRUCachePolicy;
437
438
    explicit ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
439
                             uint32_t num_shards, uint32_t element_count_capacity, bool is_lru_k);
440
    explicit ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
441
                             uint32_t num_shards,
442
                             CacheValueTimeExtractor cache_value_time_extractor,
443
                             bool cache_value_check_timestamp, uint32_t element_count_capacity,
444
                             bool is_lru_k);
445
446
    void update_cache_metrics() const;
447
448
private:
449
    static uint32_t _hash_slice(const CacheKey& s);
450
42.4M
    uint32_t _shard(uint32_t hash) const {
451
42.4M
        return _num_shard_bits > 0 ? (hash >> (32 - _num_shard_bits)) : 0;
452
42.4M
    }
453
454
    std::string _name;
455
    const int _num_shard_bits;
456
    const uint32_t _num_shards;
457
    LRUCache** _shards = nullptr;
458
    std::atomic<uint64_t> _last_id;
459
    std::mutex _mutex;
460
    size_t _capacity {0};
461
462
    std::shared_ptr<MetricEntity> _entity;
463
    IntGauge* cache_capacity = nullptr;
464
    IntGauge* cache_usage = nullptr;
465
    IntGauge* cache_element_count = nullptr;
466
    DoubleGauge* cache_usage_ratio = nullptr;
467
    IntCounter* cache_lookup_count = nullptr;
468
    IntCounter* cache_hit_count = nullptr;
469
    IntCounter* cache_miss_count = nullptr;
470
    IntCounter* cache_stampede_count = nullptr;
471
    DoubleGauge* cache_hit_ratio = nullptr;
472
    // bvars
473
    std::unique_ptr<bvar::Adder<uint64_t>> _hit_count_bvar;
474
    std::unique_ptr<bvar::PerSecond<bvar::Adder<uint64_t>>> _hit_count_per_second;
475
    std::unique_ptr<bvar::Adder<uint64_t>> _lookup_count_bvar;
476
    std::unique_ptr<bvar::PerSecond<bvar::Adder<uint64_t>>> _lookup_count_per_second;
477
};
478
479
// Compatible with ShardedLRUCache usage, but will not actually cache.
480
class DummyLRUCache : public Cache {
481
public:
482
    // Must call release on the returned handle pointer.
483
    Handle* insert(const CacheKey& key, void* value, size_t charge,
484
                   CachePriority priority = CachePriority::NORMAL) override;
485
187
    Handle* lookup(const CacheKey& key) override { return nullptr; };
486
    void release(Handle* handle) override;
487
146
    void erase(const CacheKey& key) override {};
488
    void* value(Handle* handle) override;
489
0
    uint64_t new_id() override { return 0; };
490
0
    PrunedInfo prune() override { return {0, 0}; };
491
0
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) override {
492
0
        return {0, 0};
493
0
    };
494
0
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) override {}
495
0
    int64_t get_usage() override { return 0; };
496
0
    PrunedInfo set_capacity(size_t capacity) override { return {0, 0}; };
497
0
    size_t get_capacity() override { return 0; };
498
0
    size_t get_element_count() override { return 0; };
499
};
500
501
} // namespace doris