Coverage Report

Created: 2025-07-27 03:09

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