Coverage Report

Created: 2026-10-17 20:15

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
17.0M
    CacheKey(const char* d, size_t n) : _data(d), _size(n) {}
65
66
    // Create a slice that refers to the contents of "s"
67
20.6M
    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
52.5M
    const char* data() const { return _data; }
76
77
    // Return the length (in bytes) of the referenced data
78
72.2M
    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
48.0k
    std::string to_string() const { return {_data, _size}; }
105
106
14.5M
    bool operator==(const CacheKey& other) const {
107
14.5M
        return ((size() == other.size()) && (memcmp(data(), other.data(), size()) == 0));
108
14.5M
    }
109
110
14.5M
    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
419M
    uint32_t _decode_fixed32(const char* ptr) const {
134
        // Load the raw bytes
135
419M
        uint32_t result;
136
419M
        memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load
137
419M
        return result;
138
419M
    }
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
2.87k
    Cache() = default;
160
161
    // Destroys all existing entries by calling the "deleter"
162
    // function that was passed to the constructor.
163
2.79k
    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
    // Grow an entry's eviction charge after lazy initialization, without changing its
197
    // memory tracker. The caller must hold a live handle. Stale smaller charges are ignored.
198
    virtual void update_charge(Handle* handle, size_t charge) = 0;
199
200
    // Return the value encapsulated in a handle returned by a
201
    // successful lookup().
202
    // REQUIRES: handle must not have been released yet.
203
    // REQUIRES: handle must have been returned by a method on *this.
204
    virtual void* value(Handle* handle) = 0;
205
206
    // If the cache contains entry for key, erase it.  Note that the
207
    // underlying entry will be kept around until all existing handles
208
    // to it have been released.
209
    virtual void erase(const CacheKey& key) = 0;
210
211
    // Return a new numeric id.  May be used by multiple clients who are
212
    // sharing the same cache to partition the key space.  Typically the
213
    // client will allocate a new id at startup and prepend the id to
214
    // its cache keys.
215
    virtual uint64_t new_id() = 0;
216
217
    // Remove all cache entries that are not actively in use.  Memory-constrained
218
    // applications may wish to call this method to reduce memory usage.
219
    // Default implementation of Prune() does nothing.  Subclasses are strongly
220
    // encouraged to override the default implementation.  A future release of
221
    // leveldb may change prune() to a pure abstract method.
222
    // return num of entries being pruned.
223
0
    virtual PrunedInfo prune() { return {0, 0}; }
224
225
    // Same as prune(), but the entry will only be pruned if the predicate matched.
226
    // NOTICE: the predicate should be simple enough, or the prune_if() function
227
    // may hold lock for a long time to execute predicate.
228
0
    virtual PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) { return {0, 0}; }
229
230
    virtual void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) = 0;
231
232
    virtual int64_t get_usage() = 0;
233
234
    virtual PrunedInfo set_capacity(size_t capacity) = 0;
235
    virtual size_t get_capacity() = 0;
236
237
    virtual size_t get_element_count() = 0;
238
239
private:
240
    DISALLOW_COPY_AND_ASSIGN(Cache);
241
};
242
243
// An entry is a variable length heap-allocated structure.  Entries
244
// are kept in a circular doubly linked list ordered by access time.
245
// Note: member variables can only be POD types and raw pointer,
246
// cannot be class objects or smart pointers, because LRUHandle will be created using malloc.
247
struct LRUHandle {
248
    void* value = nullptr;
249
    struct LRUHandle* next_hash = nullptr; // next entry in hash table
250
    struct LRUHandle* next = nullptr;      // next entry in lru list
251
    struct LRUHandle* prev = nullptr;      // previous entry in lru list
252
    size_t charge;
253
    size_t key_length;
254
    size_t total_size; // Entry charge, used to limit cache capacity, LRUCacheType::SIZE including key length.
255
    bool in_cache; // Whether entry is in the cache.
256
    uint32_t refs;
257
    uint32_t hash; // Hash of key(); used for fast sharding and comparisons
258
    CachePriority priority = CachePriority::NORMAL;
259
    LRUCacheType type;
260
    int64_t last_visit_time; // Save the last visit time of this cache entry.
261
    char key_data[1];        // Beginning of key
262
    // Note! key_data must be at the end.
263
264
16.4M
    CacheKey key() const {
265
        // For cheaper lookups, we allow a temporary Handle object
266
        // to store a pointer to a key in "value".
267
16.4M
        if (next == this) {
268
0
            return *(reinterpret_cast<CacheKey*>(value));
269
16.4M
        } else {
270
16.4M
            return {key_data, key_length};
271
16.4M
        }
272
16.4M
    }
273
274
1.24M
    void free() {
275
1.24M
        if (value != nullptr) { // value allows null pointer.
276
1.21M
            delete (LRUCacheValueBase*)value;
277
1.21M
        }
278
1.24M
        ::free(this);
279
1.24M
    }
280
};
281
282
// We provide our own simple hash tablet since it removes a whole bunch
283
// of porting hacks and is also faster than some of the built-in hash
284
// tablet implementations in some of the compiler/runtime combinations
285
// we have tested.  E.g., readrandom speeds up by ~5% over the g++
286
// 4.4.3's builtin hashtable.
287
288
class HandleTable {
289
public:
290
50.4k
    HandleTable() { _resize(); }
291
292
    ~HandleTable();
293
294
    LRUHandle* lookup(const CacheKey& key, uint32_t hash);
295
296
    LRUHandle* insert(LRUHandle* h);
297
298
    // Remove element from hash table by "key" and "hash".
299
    LRUHandle* remove(const CacheKey& key, uint32_t hash);
300
301
    // Remove element from hash table by "h", it would be faster
302
    // than the function above.
303
    // Return whether h is found and removed.
304
    bool remove(const LRUHandle* h);
305
306
    uint32_t element_count() const;
307
308
private:
309
    FRIEND_TEST(CacheTest, HandleTableTest);
310
311
    // The tablet consists of an array of buckets where each bucket is
312
    // a linked list of cache entries that hash into the bucket.
313
    uint32_t _length {};
314
    uint32_t _elems {};
315
    LRUHandle** _list = nullptr;
316
317
    // Return a pointer to slot that points to a cache entry that
318
    // matches key/hash.  If there is no such cache entry, return a
319
    // pointer to the trailing slot in the corresponding linked list.
320
    LRUHandle** _find_pointer(const CacheKey& key, uint32_t hash);
321
322
    void _resize();
323
};
324
325
// pair first is timestatmp, put <timestatmp, LRUHandle*> into asc set,
326
// when need to free space, can first evict the begin of the set,
327
// because the begin element's timestamp is the oldest.
328
using LRUHandleSortedSet = std::set<std::pair<int64_t, LRUHandle*>>;
329
330
// A single shard of sharded cache.
331
class LRUCache {
332
public:
333
    LRUCache(LRUCacheType type, bool is_lru_k = DEFAULT_LRU_CACHE_IS_LRU_K);
334
    ~LRUCache();
335
336
    // visits_lru_cache_key is the hash value of CacheKey.
337
    // If there is a hash conflict, a cache entry may be inserted early
338
    // and another cache entry with the same key hash may be inserted later.
339
    // Otherwise, this does not affect the correctness of the cache.
340
    using visits_lru_cache_key = uint32_t;
341
    using visits_lru_cache_pair = std::pair<visits_lru_cache_key, size_t>;
342
343
    // Separate from constructor so caller can easily make an array of LRUCache
344
    PrunedInfo set_capacity(size_t capacity);
345
50.4k
    void set_element_count_capacity(uint32_t element_count_capacity) {
346
50.4k
        _element_count_capacity = element_count_capacity;
347
50.4k
    }
348
349
    // Like Cache methods, but with an extra "hash" parameter.
350
    // Must call release on the returned handle pointer.
351
    Cache::Handle* insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
352
                          CachePriority priority = CachePriority::NORMAL);
353
    Cache::Handle* lookup(const CacheKey& key, uint32_t hash);
354
    void release(Cache::Handle* handle);
355
    void update_charge(Cache::Handle* handle, size_t charge);
356
    void erase(const CacheKey& key, uint32_t hash);
357
    PrunedInfo prune();
358
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false);
359
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor);
360
361
    void set_cache_value_time_extractor(CacheValueTimeExtractor cache_value_time_extractor);
362
    void set_cache_value_check_timestamp(bool cache_value_check_timestamp);
363
364
    uint64_t get_lookup_count();
365
    uint64_t get_hit_count();
366
    uint64_t get_miss_count();
367
    uint64_t get_stampede_count();
368
369
    size_t get_usage();
370
    size_t get_capacity();
371
    size_t get_element_count();
372
373
private:
374
    void _lru_remove(LRUHandle* e);
375
    void _lru_append(LRUHandle* list, LRUHandle* e);
376
    bool _unref(LRUHandle* e);
377
    void _evict_from_lru(size_t total_size, LRUHandle** to_remove_head);
378
    void _evict_from_lru_with_time(size_t total_size, LRUHandle** to_remove_head);
379
    void _evict_one_entry(LRUHandle* e);
380
    bool _check_element_count_limit();
381
    bool _lru_k_insert_visits_list(size_t total_size, visits_lru_cache_key visits_key);
382
383
private:
384
    LRUCacheType _type;
385
386
    // Initialized before use.
387
    size_t _capacity = 0;
388
389
    // _mutex protects the following state.
390
    std::mutex _mutex;
391
    size_t _usage = 0;
392
393
    // Dummy head of LRU list.
394
    // Entries have refs==1 and in_cache==true.
395
    // _lru_normal.prev is newest entry, _lru_normal.next is oldest entry.
396
    LRUHandle _lru_normal;
397
    // _lru_durable.prev is newest entry, _lru_durable.next is oldest entry.
398
    LRUHandle _lru_durable;
399
400
    HandleTable _table;
401
402
    uint64_t _lookup_count = 0; // number of cache lookups
403
    uint64_t _hit_count = 0;    // number of cache hits
404
    uint64_t _miss_count = 0;   // number of cache misses
405
    uint64_t _stampede_count = 0;
406
407
    CacheValueTimeExtractor _cache_value_time_extractor;
408
    bool _cache_value_check_timestamp = false;
409
    LRUHandleSortedSet _sorted_normal_entries_with_timestamp;
410
    LRUHandleSortedSet _sorted_durable_entries_with_timestamp;
411
412
    uint32_t _element_count_capacity = 0;
413
414
    bool _is_lru_k = false; // LRU-K algorithm, K=2
415
    std::list<visits_lru_cache_pair> _visits_lru_cache_list;
416
    std::unordered_map<visits_lru_cache_key, std::list<visits_lru_cache_pair>::iterator>
417
            _visits_lru_cache_map;
418
    size_t _visits_lru_cache_usage = 0;
419
};
420
421
class ShardedLRUCache : public Cache {
422
public:
423
    ~ShardedLRUCache() override;
424
    Handle* insert(const CacheKey& key, void* value, size_t charge,
425
                   CachePriority priority = CachePriority::NORMAL) override;
426
    Handle* lookup(const CacheKey& key) override;
427
    void release(Handle* handle) override;
428
    void update_charge(Handle* handle, size_t charge) override;
429
    void erase(const CacheKey& key) override;
430
    void* value(Handle* handle) override;
431
    uint64_t new_id() override;
432
    PrunedInfo prune() override;
433
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) override;
434
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) override;
435
    int64_t get_usage() override;
436
    size_t get_element_count() override;
437
    PrunedInfo set_capacity(size_t capacity) override;
438
    size_t get_capacity() override;
439
440
private:
441
    // LRUCache can only be created and managed with LRUCachePolicy.
442
    friend class LRUCachePolicy;
443
444
    explicit ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
445
                             uint32_t num_shards, uint32_t element_count_capacity, bool is_lru_k);
446
    explicit ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
447
                             uint32_t num_shards,
448
                             CacheValueTimeExtractor cache_value_time_extractor,
449
                             bool cache_value_check_timestamp, uint32_t element_count_capacity,
450
                             bool is_lru_k);
451
452
    void update_cache_metrics() const;
453
454
private:
455
    static uint32_t _hash_slice(const CacheKey& s);
456
36.8M
    uint32_t _shard(uint32_t hash) const {
457
36.8M
        return _num_shard_bits > 0 ? (hash >> (32 - _num_shard_bits)) : 0;
458
36.8M
    }
459
460
    std::string _name;
461
    const int _num_shard_bits;
462
    const uint32_t _num_shards;
463
    LRUCache** _shards = nullptr;
464
    std::atomic<uint64_t> _last_id;
465
    std::mutex _mutex;
466
    size_t _capacity {0};
467
468
    std::shared_ptr<MetricEntity> _entity;
469
    IntGauge* cache_capacity = nullptr;
470
    IntGauge* cache_usage = nullptr;
471
    IntGauge* cache_element_count = nullptr;
472
    DoubleGauge* cache_usage_ratio = nullptr;
473
    IntCounter* cache_lookup_count = nullptr;
474
    IntCounter* cache_hit_count = nullptr;
475
    IntCounter* cache_miss_count = nullptr;
476
    IntCounter* cache_stampede_count = nullptr;
477
    DoubleGauge* cache_hit_ratio = nullptr;
478
    // bvars
479
    std::unique_ptr<bvar::Adder<uint64_t>> _hit_count_bvar;
480
    std::unique_ptr<bvar::PerSecond<bvar::Adder<uint64_t>>> _hit_count_per_second;
481
    std::unique_ptr<bvar::Adder<uint64_t>> _lookup_count_bvar;
482
    std::unique_ptr<bvar::PerSecond<bvar::Adder<uint64_t>>> _lookup_count_per_second;
483
};
484
485
// Compatible with ShardedLRUCache usage, but will not actually cache.
486
class DummyLRUCache : public Cache {
487
public:
488
    // Must call release on the returned handle pointer.
489
    Handle* insert(const CacheKey& key, void* value, size_t charge,
490
                   CachePriority priority = CachePriority::NORMAL) override;
491
558
    Handle* lookup(const CacheKey& key) override { return nullptr; };
492
    void release(Handle* handle) override;
493
0
    void update_charge(Handle* handle, size_t charge) override {}
494
146
    void erase(const CacheKey& key) override {};
495
    void* value(Handle* handle) override;
496
0
    uint64_t new_id() override { return 0; };
497
0
    PrunedInfo prune() override { return {0, 0}; };
498
0
    PrunedInfo prune_if(CachePrunePredicate pred, bool lazy_mode = false) override {
499
0
        return {0, 0};
500
0
    };
501
0
    void for_each_entry(const std::function<void(const LRUHandle*)>& visitor) override {}
502
0
    int64_t get_usage() override { return 0; };
503
0
    PrunedInfo set_capacity(size_t capacity) override { return {0, 0}; };
504
0
    size_t get_capacity() override { return 0; };
505
0
    size_t get_element_count() override { return 0; };
506
};
507
508
} // namespace doris