Coverage Report

Created: 2026-04-15 17:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/lru_cache.cpp
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
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
18
// Use of this source code is governed by a BSD-style license that can be
19
// found in the LICENSE file. See the AUTHORS file for names of contributors.
20
21
#include "util/lru_cache.h"
22
23
#include <cstdlib>
24
#include <mutex>
25
#include <new>
26
#include <sstream>
27
#include <string>
28
29
#include "common/metrics/metrics.h"
30
#include "util/time.h"
31
32
using std::string;
33
using std::stringstream;
34
35
namespace doris {
36
37
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(cache_capacity, MetricUnit::BYTES);
38
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(cache_usage, MetricUnit::BYTES);
39
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(cache_element_count, MetricUnit::NOUNIT);
40
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(cache_usage_ratio, MetricUnit::NOUNIT);
41
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(cache_lookup_count, MetricUnit::OPERATIONS);
42
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(cache_hit_count, MetricUnit::OPERATIONS);
43
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(cache_miss_count, MetricUnit::OPERATIONS);
44
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(cache_stampede_count, MetricUnit::OPERATIONS);
45
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(cache_hit_ratio, MetricUnit::NOUNIT);
46
47
23.5M
uint32_t CacheKey::hash(const char* data, size_t n, uint32_t seed) const {
48
    // Similar to murmur hash
49
23.5M
    const uint32_t m = 0xc6a4a793;
50
23.5M
    const uint32_t r = 24;
51
23.5M
    const char* limit = data + n;
52
23.5M
    uint32_t h = seed ^ (static_cast<uint32_t>(n) * m);
53
54
    // Pick up four bytes at a time
55
479M
    while (data + 4 <= limit) {
56
456M
        uint32_t w = _decode_fixed32(data);
57
456M
        data += 4;
58
456M
        h += w;
59
456M
        h *= m;
60
456M
        h ^= (h >> 16);
61
456M
    }
62
63
    // Pick up remaining bytes
64
23.5M
    switch (limit - data) {
65
738k
    case 3:
66
738k
        h += static_cast<unsigned char>(data[2]) << 16;
67
68
        // fall through
69
1.40M
    case 2:
70
1.40M
        h += static_cast<unsigned char>(data[1]) << 8;
71
72
        // fall through
73
9.26M
    case 1:
74
9.26M
        h += static_cast<unsigned char>(data[0]);
75
9.26M
        h *= m;
76
9.26M
        h ^= (h >> r);
77
9.26M
        break;
78
79
14.3M
    default:
80
14.3M
        break;
81
23.5M
    }
82
83
23.5M
    return h;
84
23.5M
}
85
86
22.0k
HandleTable::~HandleTable() {
87
22.0k
    delete[] _list;
88
22.0k
}
89
90
// LRU cache implementation
91
21.1M
LRUHandle* HandleTable::lookup(const CacheKey& key, uint32_t hash) {
92
21.1M
    return *_find_pointer(key, hash);
93
21.1M
}
94
95
2.44M
LRUHandle* HandleTable::insert(LRUHandle* h) {
96
2.44M
    LRUHandle** ptr = _find_pointer(h->key(), h->hash);
97
2.44M
    LRUHandle* old = *ptr;
98
2.44M
    h->next_hash = old ? old->next_hash : nullptr;
99
2.44M
    *ptr = h;
100
101
2.44M
    if (old == nullptr) {
102
2.28M
        ++_elems;
103
2.28M
        if (_elems > _length) {
104
            // Since each cache entry is fairly large, we aim for a small
105
            // average linked list length (<= 1).
106
6.86k
            _resize();
107
6.86k
        }
108
2.28M
    }
109
110
2.44M
    return old;
111
2.44M
}
112
113
112k
LRUHandle* HandleTable::remove(const CacheKey& key, uint32_t hash) {
114
112k
    LRUHandle** ptr = _find_pointer(key, hash);
115
112k
    LRUHandle* result = *ptr;
116
117
112k
    if (result != nullptr) {
118
53.3k
        *ptr = result->next_hash;
119
53.3k
        _elems--;
120
53.3k
    }
121
122
112k
    return result;
123
112k
}
124
125
1.60M
bool HandleTable::remove(const LRUHandle* h) {
126
1.60M
    LRUHandle** ptr = &(_list[h->hash & (_length - 1)]);
127
1.72M
    while (*ptr != nullptr && *ptr != h) {
128
120k
        ptr = &(*ptr)->next_hash;
129
120k
    }
130
131
1.60M
    LRUHandle* result = *ptr;
132
1.60M
    if (result != nullptr) {
133
1.60M
        *ptr = result->next_hash;
134
1.60M
        _elems--;
135
1.60M
        return true;
136
1.60M
    }
137
18.4E
    return false;
138
1.60M
}
139
140
23.6M
LRUHandle** HandleTable::_find_pointer(const CacheKey& key, uint32_t hash) {
141
23.6M
    LRUHandle** ptr = &(_list[hash & (_length - 1)]);
142
35.7M
    while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) {
143
12.0M
        ptr = &(*ptr)->next_hash;
144
12.0M
    }
145
146
23.6M
    return ptr;
147
23.6M
}
148
149
37.2k
void HandleTable::_resize() {
150
37.2k
    uint32_t new_length = 16;
151
55.1k
    while (new_length < _elems * 1.5) {
152
17.8k
        new_length *= 2;
153
17.8k
    }
154
155
37.2k
    auto** new_list = new (std::nothrow) LRUHandle*[new_length];
156
37.2k
    memset(new_list, 0, sizeof(new_list[0]) * new_length);
157
158
37.2k
    uint32_t count = 0;
159
1.23M
    for (uint32_t i = 0; i < _length; i++) {
160
1.19M
        LRUHandle* h = _list[i];
161
2.39M
        while (h != nullptr) {
162
1.20M
            LRUHandle* next = h->next_hash;
163
1.20M
            uint32_t hash = h->hash;
164
1.20M
            LRUHandle** ptr = &new_list[hash & (new_length - 1)];
165
1.20M
            h->next_hash = *ptr;
166
1.20M
            *ptr = h;
167
1.20M
            h = next;
168
1.20M
            count++;
169
1.20M
        }
170
1.19M
    }
171
172
37.2k
    DCHECK_EQ(_elems, count);
173
37.2k
    delete[] _list;
174
37.2k
    _list = new_list;
175
37.2k
    _length = new_length;
176
37.2k
}
177
178
764k
uint32_t HandleTable::element_count() const {
179
764k
    return _elems;
180
764k
}
181
182
30.3k
LRUCache::LRUCache(LRUCacheType type, bool is_lru_k) : _type(type), _is_lru_k(is_lru_k) {
183
    // Make empty circular linked list
184
30.3k
    _lru_normal.next = &_lru_normal;
185
30.3k
    _lru_normal.prev = &_lru_normal;
186
30.3k
    _lru_durable.next = &_lru_durable;
187
30.3k
    _lru_durable.prev = &_lru_durable;
188
30.3k
}
189
190
22.0k
LRUCache::~LRUCache() {
191
22.0k
    prune();
192
22.0k
}
193
194
30.3k
PrunedInfo LRUCache::set_capacity(size_t capacity) {
195
30.3k
    LRUHandle* last_ref_list = nullptr;
196
30.3k
    {
197
30.3k
        std::lock_guard l(_mutex);
198
30.3k
        if (capacity > _capacity) {
199
30.3k
            _capacity = capacity;
200
30.3k
            return {0, 0};
201
30.3k
        }
202
8
        _capacity = capacity;
203
8
        _evict_from_lru(0, &last_ref_list);
204
8
    }
205
206
0
    int64_t pruned_count = 0;
207
8
    int64_t pruned_size = 0;
208
56.0k
    while (last_ref_list != nullptr) {
209
55.9k
        ++pruned_count;
210
55.9k
        pruned_size += last_ref_list->total_size;
211
55.9k
        LRUHandle* next = last_ref_list->next;
212
55.9k
        last_ref_list->free();
213
55.9k
        last_ref_list = next;
214
55.9k
    }
215
8
    return {pruned_count, pruned_size};
216
30.3k
}
217
218
738k
uint64_t LRUCache::get_lookup_count() {
219
738k
    std::lock_guard l(_mutex);
220
738k
    return _lookup_count;
221
738k
}
222
223
738k
uint64_t LRUCache::get_hit_count() {
224
738k
    std::lock_guard l(_mutex);
225
738k
    return _hit_count;
226
738k
}
227
228
738k
uint64_t LRUCache::get_stampede_count() {
229
738k
    std::lock_guard l(_mutex);
230
738k
    return _stampede_count;
231
738k
}
232
233
738k
uint64_t LRUCache::get_miss_count() {
234
738k
    std::lock_guard l(_mutex);
235
738k
    return _miss_count;
236
738k
}
237
238
788k
size_t LRUCache::get_usage() {
239
788k
    std::lock_guard l(_mutex);
240
788k
    return _usage;
241
788k
}
242
243
738k
size_t LRUCache::get_capacity() {
244
738k
    std::lock_guard l(_mutex);
245
738k
    return _capacity;
246
738k
}
247
248
739k
size_t LRUCache::get_element_count() {
249
739k
    std::lock_guard l(_mutex);
250
739k
    return _table.element_count();
251
739k
}
252
253
19.0M
bool LRUCache::_unref(LRUHandle* e) {
254
19.0M
    DCHECK(e->refs > 0);
255
19.0M
    e->refs--;
256
19.0M
    return e->refs == 0;
257
19.0M
}
258
259
13.1M
void LRUCache::_lru_remove(LRUHandle* e) {
260
13.1M
    e->next->prev = e->prev;
261
13.1M
    e->prev->next = e->next;
262
13.1M
    e->prev = e->next = nullptr;
263
264
13.1M
    if (_cache_value_check_timestamp) {
265
8.14k
        if (e->priority == CachePriority::NORMAL) {
266
8.14k
            auto pair = std::make_pair(_cache_value_time_extractor(e->value), e);
267
8.14k
            auto found_it = _sorted_normal_entries_with_timestamp.find(pair);
268
8.15k
            if (found_it != _sorted_normal_entries_with_timestamp.end()) {
269
8.15k
                _sorted_normal_entries_with_timestamp.erase(found_it);
270
8.15k
            }
271
18.4E
        } else if (e->priority == CachePriority::DURABLE) {
272
0
            auto pair = std::make_pair(_cache_value_time_extractor(e->value), e);
273
0
            auto found_it = _sorted_durable_entries_with_timestamp.find(pair);
274
0
            if (found_it != _sorted_durable_entries_with_timestamp.end()) {
275
0
                _sorted_durable_entries_with_timestamp.erase(found_it);
276
0
            }
277
0
        }
278
8.14k
    }
279
13.1M
}
280
281
13.7M
void LRUCache::_lru_append(LRUHandle* list, LRUHandle* e) {
282
    // Make "e" newest entry by inserting just before *list
283
13.7M
    e->next = list;
284
13.7M
    e->prev = list->prev;
285
13.7M
    e->prev->next = e;
286
13.7M
    e->next->prev = e;
287
288
    // _cache_value_check_timestamp is true,
289
    // means evict entry will depends on the timestamp asc set,
290
    // the timestamp is updated by higher level caller,
291
    // and the timestamp of hit entry is different with the insert entry,
292
    // that is why need check timestamp to evict entry,
293
    // in order to keep the survival time of hit entries
294
    // longer than the entries just inserted,
295
    // so use asc set to sorted these entries's timestamp and LRUHandle*
296
13.7M
    if (_cache_value_check_timestamp) {
297
18.6k
        if (e->priority == CachePriority::NORMAL) {
298
18.6k
            _sorted_normal_entries_with_timestamp.insert(
299
18.6k
                    std::make_pair(_cache_value_time_extractor(e->value), e));
300
18.6k
        } else if (e->priority == CachePriority::DURABLE) {
301
0
            _sorted_durable_entries_with_timestamp.insert(
302
0
                    std::make_pair(_cache_value_time_extractor(e->value), e));
303
0
        }
304
18.6k
    }
305
13.7M
}
306
307
21.0M
Cache::Handle* LRUCache::lookup(const CacheKey& key, uint32_t hash) {
308
21.0M
    std::lock_guard l(_mutex);
309
21.0M
    ++_lookup_count;
310
21.0M
    LRUHandle* e = _table.lookup(key, hash);
311
21.0M
    if (e != nullptr) {
312
        // we get it from _table, so in_cache must be true
313
15.4M
        DCHECK(e->in_cache);
314
15.4M
        if (e->refs == 1) {
315
            // only in LRU free list, remove it from list
316
11.4M
            _lru_remove(e);
317
11.4M
        }
318
15.4M
        e->refs++;
319
15.4M
        ++_hit_count;
320
15.4M
        e->last_visit_time = UnixMillis();
321
15.4M
    } else {
322
5.51M
        ++_miss_count;
323
5.51M
    }
324
325
    // If key not exist in cache, and is lru k cache, and key in visits list,
326
    // then move the key to beginning of the visits list.
327
    // key in visits list indicates that the key has been inserted once after the cache is full.
328
21.0M
    if (e == nullptr && _is_lru_k) {
329
3.07M
        auto it = _visits_lru_cache_map.find(hash);
330
3.07M
        if (it != _visits_lru_cache_map.end()) {
331
163
            _visits_lru_cache_list.splice(_visits_lru_cache_list.begin(), _visits_lru_cache_list,
332
163
                                          it->second);
333
163
        }
334
3.07M
    }
335
21.0M
    return reinterpret_cast<Cache::Handle*>(e);
336
21.0M
}
337
338
17.2M
void LRUCache::release(Cache::Handle* handle) {
339
17.2M
    if (handle == nullptr) {
340
0
        return;
341
0
    }
342
17.2M
    auto* e = reinterpret_cast<LRUHandle*>(handle);
343
17.2M
    bool last_ref = false;
344
17.2M
    {
345
17.2M
        std::lock_guard l(_mutex);
346
        // if last_ref is true, key may have been evict from the cache,
347
        // or if it is lru k, first insert of key may have failed.
348
17.2M
        last_ref = _unref(e);
349
17.2M
        if (e->in_cache && e->refs == 1) {
350
            // only exists in cache
351
13.8M
            if (_usage > _capacity) {
352
                // take this opportunity and remove the item
353
27.3k
                bool removed = _table.remove(e);
354
27.3k
                DCHECK(removed);
355
27.3k
                e->in_cache = false;
356
27.3k
                _unref(e);
357
                // `entry->in_cache = false` and `_usage -= entry->total_size;` and `_unref(entry)` should appear together.
358
                // see the comment for old entry in `LRUCache::insert`.
359
27.3k
                _usage -= e->total_size;
360
27.3k
                last_ref = true;
361
13.7M
            } else {
362
                // put it to LRU free list
363
13.8M
                if (e->priority == CachePriority::NORMAL) {
364
13.8M
                    _lru_append(&_lru_normal, e);
365
18.4E
                } else if (e->priority == CachePriority::DURABLE) {
366
18
                    _lru_append(&_lru_durable, e);
367
18
                }
368
13.7M
            }
369
13.8M
        }
370
17.2M
    }
371
372
    // free handle out of mutex
373
17.2M
    if (last_ref) {
374
64.5k
        e->free();
375
64.5k
    }
376
17.2M
}
377
378
11.8k
void LRUCache::_evict_from_lru_with_time(size_t total_size, LRUHandle** to_remove_head) {
379
    // 1. evict normal cache entries
380
11.8k
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
381
11.8k
           !_sorted_normal_entries_with_timestamp.empty()) {
382
23
        auto entry_pair = _sorted_normal_entries_with_timestamp.begin();
383
23
        LRUHandle* remove_handle = entry_pair->second;
384
23
        DCHECK(remove_handle != nullptr);
385
23
        DCHECK(remove_handle->priority == CachePriority::NORMAL);
386
23
        _evict_one_entry(remove_handle);
387
23
        remove_handle->next = *to_remove_head;
388
23
        *to_remove_head = remove_handle;
389
23
    }
390
391
    // 2. evict durable cache entries if need
392
11.8k
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
393
11.8k
           !_sorted_durable_entries_with_timestamp.empty()) {
394
0
        auto entry_pair = _sorted_durable_entries_with_timestamp.begin();
395
0
        LRUHandle* remove_handle = entry_pair->second;
396
0
        DCHECK(remove_handle != nullptr);
397
0
        DCHECK(remove_handle->priority == CachePriority::DURABLE);
398
0
        _evict_one_entry(remove_handle);
399
0
        remove_handle->next = *to_remove_head;
400
0
        *to_remove_head = remove_handle;
401
0
    }
402
11.8k
}
403
404
2.43M
void LRUCache::_evict_from_lru(size_t total_size, LRUHandle** to_remove_head) {
405
    // 1. evict normal cache entries
406
2.74M
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
407
2.74M
           _lru_normal.next != &_lru_normal) {
408
311k
        LRUHandle* old = _lru_normal.next;
409
311k
        DCHECK(old->priority == CachePriority::NORMAL);
410
311k
        _evict_one_entry(old);
411
311k
        old->next = *to_remove_head;
412
311k
        *to_remove_head = old;
413
311k
    }
414
    // 2. evict durable cache entries if need
415
2.43M
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
416
2.43M
           _lru_durable.next != &_lru_durable) {
417
4
        LRUHandle* old = _lru_durable.next;
418
4
        DCHECK(old->priority == CachePriority::DURABLE);
419
4
        _evict_one_entry(old);
420
4
        old->next = *to_remove_head;
421
4
        *to_remove_head = old;
422
4
    }
423
2.43M
}
424
425
1.57M
void LRUCache::_evict_one_entry(LRUHandle* e) {
426
1.57M
    DCHECK(e->in_cache);
427
1.57M
    DCHECK(e->refs == 1); // LRU list contains elements which may be evicted
428
1.57M
    _lru_remove(e);
429
1.57M
    bool removed = _table.remove(e);
430
1.57M
    DCHECK(removed);
431
1.57M
    e->in_cache = false;
432
1.57M
    _unref(e);
433
    // `entry->in_cache = false` and `_usage -= entry->total_size;` and `_unref(entry)` should appear together.
434
    // see the comment for old entry in `LRUCache::insert`.
435
1.57M
    _usage -= e->total_size;
436
1.57M
}
437
438
6.22M
bool LRUCache::_check_element_count_limit() {
439
6.22M
    return _element_count_capacity != 0 && _table.element_count() >= _element_count_capacity;
440
6.22M
}
441
442
// After cache is full,
443
// 1.Return false. If key has been inserted into the visits list before,
444
// key is allowed to be inserted into cache this time (this will trigger cache evict),
445
// and key is removed from the visits list.
446
// 2. Return true. If key not in visits list, insert it into visits list.
447
1.42M
bool LRUCache::_lru_k_insert_visits_list(size_t total_size, visits_lru_cache_key visits_key) {
448
1.42M
    if (_usage + total_size > _capacity ||
449
1.42M
        _check_element_count_limit()) { // this line no lock required
450
4.82k
        auto it = _visits_lru_cache_map.find(visits_key);
451
4.82k
        if (it != _visits_lru_cache_map.end()) {
452
162
            _visits_lru_cache_usage -= it->second->second;
453
162
            _visits_lru_cache_list.erase(it->second);
454
162
            _visits_lru_cache_map.erase(it);
455
4.66k
        } else {
456
            // _visits_lru_cache_list capacity is same as the cache itself.
457
            // If _visits_lru_cache_list is full, some keys will also be evict.
458
4.94k
            while (_visits_lru_cache_usage + total_size > _capacity &&
459
4.94k
                   _visits_lru_cache_usage != 0) {
460
279
                DCHECK(!_visits_lru_cache_map.empty());
461
279
                _visits_lru_cache_usage -= _visits_lru_cache_list.back().second;
462
279
                _visits_lru_cache_map.erase(_visits_lru_cache_list.back().first);
463
279
                _visits_lru_cache_list.pop_back();
464
279
            }
465
            // 1. If true, insert key at the beginning of _visits_lru_cache_list.
466
            // 2. If false, it means total_size > cache _capacity, preventing this insert.
467
4.66k
            if (_visits_lru_cache_usage + total_size <= _capacity) {
468
465
                _visits_lru_cache_list.emplace_front(visits_key, total_size);
469
465
                _visits_lru_cache_map[visits_key] = _visits_lru_cache_list.begin();
470
465
                _visits_lru_cache_usage += total_size;
471
465
            }
472
4.66k
            return true;
473
4.66k
        }
474
4.82k
    }
475
1.41M
    return false;
476
1.42M
}
477
478
Cache::Handle* LRUCache::insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
479
2.44M
                                CachePriority priority) {
480
2.44M
    size_t handle_size = sizeof(LRUHandle) - 1 + key.size();
481
2.44M
    auto* e = reinterpret_cast<LRUHandle*>(malloc(handle_size));
482
2.44M
    e->value = value;
483
2.44M
    e->charge = charge;
484
2.44M
    e->key_length = key.size();
485
    // if LRUCacheType::NUMBER, charge not add handle_size,
486
    // because charge at this time is no longer the memory size, but an weight.
487
2.44M
    e->total_size = (_type == LRUCacheType::SIZE ? handle_size + charge : charge);
488
2.44M
    e->hash = hash;
489
2.44M
    e->refs = 1; // only one for the returned handle.
490
2.44M
    e->next = e->prev = nullptr;
491
2.44M
    e->in_cache = false;
492
2.44M
    e->priority = priority;
493
2.44M
    e->type = _type;
494
2.44M
    memcpy(e->key_data, key.data(), key.size());
495
2.44M
    e->last_visit_time = UnixMillis();
496
497
2.44M
    LRUHandle* to_remove_head = nullptr;
498
2.44M
    {
499
2.44M
        std::lock_guard l(_mutex);
500
501
2.44M
        if (_is_lru_k && _lru_k_insert_visits_list(e->total_size, hash)) {
502
4.66k
            return reinterpret_cast<Cache::Handle*>(e);
503
4.66k
        }
504
505
        // Free the space following strict LRU policy until enough space
506
        // is freed or the lru list is empty
507
2.44M
        if (_cache_value_check_timestamp) {
508
11.8k
            _evict_from_lru_with_time(e->total_size, &to_remove_head);
509
2.42M
        } else {
510
2.42M
            _evict_from_lru(e->total_size, &to_remove_head);
511
2.42M
        }
512
513
        // insert into the cache
514
        // note that the cache might get larger than its capacity if not enough
515
        // space was freed
516
2.44M
        auto* old = _table.insert(e);
517
2.44M
        e->in_cache = true;
518
2.44M
        _usage += e->total_size;
519
2.44M
        e->refs++; // one for the returned handle, one for LRUCache.
520
2.44M
        if (old != nullptr) {
521
158k
            _stampede_count++;
522
158k
            old->in_cache = false;
523
            // `entry->in_cache = false` and `_usage -= entry->total_size;` and `_unref(entry)` should appear together.
524
            // Whether the reference of the old entry is 0, the cache usage is subtracted here,
525
            // because the old entry has been removed from the cache and should not be counted in the cache capacity,
526
            // but the memory of the old entry is still tracked by the cache memory_tracker.
527
            // After all the old handles are released, the old entry will be freed and the memory of the old entry
528
            // will be released from the cache memory_tracker.
529
158k
            _usage -= old->total_size;
530
            // if false, old entry is being used externally, just ref-- and sub _usage,
531
158k
            if (_unref(old)) {
532
                // old is on LRU because it's in cache and its reference count
533
                // was just 1 (Unref returned 0)
534
120k
                _lru_remove(old);
535
120k
                old->next = to_remove_head;
536
120k
                to_remove_head = old;
537
120k
            }
538
158k
        }
539
2.44M
    }
540
541
    // we free the entries here outside of mutex for
542
    // performance reasons
543
2.81M
    while (to_remove_head != nullptr) {
544
375k
        LRUHandle* next = to_remove_head->next;
545
375k
        to_remove_head->free();
546
375k
        to_remove_head = next;
547
375k
    }
548
549
2.44M
    return reinterpret_cast<Cache::Handle*>(e);
550
2.44M
}
551
552
112k
void LRUCache::erase(const CacheKey& key, uint32_t hash) {
553
112k
    LRUHandle* e = nullptr;
554
112k
    bool last_ref = false;
555
112k
    {
556
112k
        std::lock_guard l(_mutex);
557
112k
        e = _table.remove(key, hash);
558
112k
        if (e != nullptr) {
559
53.3k
            last_ref = _unref(e);
560
            // if last_ref is false or in_cache is false, e must not be in lru
561
53.3k
            if (last_ref && e->in_cache) {
562
                // locate in free list
563
53.3k
                _lru_remove(e);
564
53.3k
            }
565
53.3k
            e->in_cache = false;
566
            // `entry->in_cache = false` and `_usage -= entry->total_size;` and `_unref(entry)` should appear together.
567
            // see the comment for old entry in `LRUCache::insert`.
568
53.3k
            _usage -= e->total_size;
569
53.3k
        }
570
112k
    }
571
    // free handle out of mutex, when last_ref is true, e must not be nullptr
572
112k
    if (last_ref) {
573
53.3k
        e->free();
574
53.3k
    }
575
112k
}
576
577
22.0k
PrunedInfo LRUCache::prune() {
578
22.0k
    LRUHandle* to_remove_head = nullptr;
579
22.0k
    {
580
22.0k
        std::lock_guard l(_mutex);
581
59.2k
        while (_lru_normal.next != &_lru_normal) {
582
37.1k
            LRUHandle* old = _lru_normal.next;
583
37.1k
            _evict_one_entry(old);
584
37.1k
            old->next = to_remove_head;
585
37.1k
            to_remove_head = old;
586
37.1k
        }
587
22.0k
        while (_lru_durable.next != &_lru_durable) {
588
6
            LRUHandle* old = _lru_durable.next;
589
6
            _evict_one_entry(old);
590
6
            old->next = to_remove_head;
591
6
            to_remove_head = old;
592
6
        }
593
22.0k
    }
594
22.0k
    int64_t pruned_count = 0;
595
22.0k
    int64_t pruned_size = 0;
596
59.2k
    while (to_remove_head != nullptr) {
597
37.1k
        ++pruned_count;
598
37.1k
        pruned_size += to_remove_head->total_size;
599
37.1k
        LRUHandle* next = to_remove_head->next;
600
37.1k
        to_remove_head->free();
601
37.1k
        to_remove_head = next;
602
37.1k
    }
603
22.0k
    return {pruned_count, pruned_size};
604
22.0k
}
605
606
21.2k
PrunedInfo LRUCache::prune_if(CachePrunePredicate pred, bool lazy_mode) {
607
21.2k
    LRUHandle* to_remove_head = nullptr;
608
21.2k
    {
609
21.2k
        std::lock_guard l(_mutex);
610
21.2k
        LRUHandle* p = _lru_normal.next;
611
1.25M
        while (p != &_lru_normal) {
612
1.24M
            LRUHandle* next = p->next;
613
1.24M
            if (pred(p)) {
614
1.23M
                _evict_one_entry(p);
615
1.23M
                p->next = to_remove_head;
616
1.23M
                to_remove_head = p;
617
1.23M
            } else if (lazy_mode) {
618
18.1k
                break;
619
18.1k
            }
620
1.23M
            p = next;
621
1.23M
        }
622
623
21.2k
        p = _lru_durable.next;
624
21.2k
        while (p != &_lru_durable) {
625
10
            LRUHandle* next = p->next;
626
10
            if (pred(p)) {
627
2
                _evict_one_entry(p);
628
2
                p->next = to_remove_head;
629
2
                to_remove_head = p;
630
8
            } else if (lazy_mode) {
631
3
                break;
632
3
            }
633
7
            p = next;
634
7
        }
635
21.2k
    }
636
21.2k
    int64_t pruned_count = 0;
637
21.2k
    int64_t pruned_size = 0;
638
1.25M
    while (to_remove_head != nullptr) {
639
1.23M
        ++pruned_count;
640
1.23M
        pruned_size += to_remove_head->total_size;
641
1.23M
        LRUHandle* next = to_remove_head->next;
642
1.23M
        to_remove_head->free();
643
1.23M
        to_remove_head = next;
644
1.23M
    }
645
21.2k
    return {pruned_count, pruned_size};
646
21.2k
}
647
648
512
void LRUCache::for_each_entry(const std::function<void(const LRUHandle*)>& visitor) {
649
512
    std::lock_guard l(_mutex);
650
45.4k
    for (LRUHandle* p = _lru_normal.next; p != &_lru_normal; p = p->next) {
651
44.9k
        visitor(p);
652
44.9k
    }
653
512
    for (LRUHandle* p = _lru_durable.next; p != &_lru_durable; p = p->next) {
654
0
        visitor(p);
655
0
    }
656
512
}
657
658
1.90k
void LRUCache::set_cache_value_time_extractor(CacheValueTimeExtractor cache_value_time_extractor) {
659
1.90k
    _cache_value_time_extractor = cache_value_time_extractor;
660
1.90k
}
661
662
1.90k
void LRUCache::set_cache_value_check_timestamp(bool cache_value_check_timestamp) {
663
1.90k
    _cache_value_check_timestamp = cache_value_check_timestamp;
664
1.90k
}
665
666
23.6M
inline uint32_t ShardedLRUCache::_hash_slice(const CacheKey& s) {
667
23.6M
    return s.hash(s.data(), s.size(), 0);
668
23.6M
}
669
670
ShardedLRUCache::ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
671
                                 uint32_t num_shards, uint32_t total_element_count_capacity,
672
                                 bool is_lru_k)
673
1.24k
        : _name(name),
674
1.24k
          _num_shard_bits(__builtin_ctz(num_shards)),
675
1.24k
          _num_shards(num_shards),
676
1.24k
          _last_id(1),
677
1.24k
          _capacity(capacity) {
678
1.24k
    CHECK(num_shards > 0) << "num_shards cannot be 0";
679
1.24k
    CHECK_EQ((num_shards & (num_shards - 1)), 0)
680
0
            << "num_shards should be power of two, but got " << num_shards;
681
682
1.24k
    const size_t per_shard = (capacity + (_num_shards - 1)) / _num_shards;
683
1.24k
    const uint32_t per_shard_element_count_capacity =
684
1.24k
            (total_element_count_capacity + (_num_shards - 1)) / _num_shards;
685
1.24k
    auto** shards = new (std::nothrow) LRUCache*[_num_shards];
686
31.5k
    for (int s = 0; s < _num_shards; s++) {
687
30.3k
        shards[s] = new LRUCache(type, is_lru_k);
688
30.3k
        shards[s]->set_capacity(per_shard);
689
30.3k
        shards[s]->set_element_count_capacity(per_shard_element_count_capacity);
690
30.3k
    }
691
1.24k
    _shards = shards;
692
693
1.24k
    _entity = DorisMetrics::instance()->metric_registry()->register_entity(
694
1.24k
            std::string("lru_cache:") + name, {{"name", name}});
695
1.24k
    _entity->register_hook(name, std::bind(&ShardedLRUCache::update_cache_metrics, this));
696
1.24k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_capacity);
697
1.24k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_usage);
698
1.24k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_element_count);
699
1.24k
    DOUBLE_GAUGE_METRIC_REGISTER(_entity, cache_usage_ratio);
700
1.24k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_lookup_count);
701
1.24k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_hit_count);
702
1.24k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_stampede_count);
703
1.24k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_miss_count);
704
1.24k
    DOUBLE_GAUGE_METRIC_REGISTER(_entity, cache_hit_ratio);
705
706
1.24k
    _hit_count_bvar.reset(new bvar::Adder<uint64_t>("doris_cache", _name));
707
1.24k
    _hit_count_per_second.reset(new bvar::PerSecond<bvar::Adder<uint64_t>>(
708
1.24k
            "doris_cache", _name + "_persecond", _hit_count_bvar.get(), 60));
709
1.24k
    _lookup_count_bvar.reset(new bvar::Adder<uint64_t>("doris_cache", _name));
710
1.24k
    _lookup_count_per_second.reset(new bvar::PerSecond<bvar::Adder<uint64_t>>(
711
1.24k
            "doris_cache", _name + "_persecond", _lookup_count_bvar.get(), 60));
712
1.24k
}
713
714
ShardedLRUCache::ShardedLRUCache(const std::string& name, size_t capacity, LRUCacheType type,
715
                                 uint32_t num_shards,
716
                                 CacheValueTimeExtractor cache_value_time_extractor,
717
                                 bool cache_value_check_timestamp,
718
                                 uint32_t total_element_count_capacity, bool is_lru_k)
719
124
        : ShardedLRUCache(name, capacity, type, num_shards, total_element_count_capacity,
720
124
                          is_lru_k) {
721
2.03k
    for (int s = 0; s < _num_shards; s++) {
722
1.90k
        _shards[s]->set_cache_value_time_extractor(cache_value_time_extractor);
723
1.90k
        _shards[s]->set_cache_value_check_timestamp(cache_value_check_timestamp);
724
1.90k
    }
725
124
}
726
727
1.16k
ShardedLRUCache::~ShardedLRUCache() {
728
1.16k
    _entity->deregister_hook(_name);
729
1.16k
    DorisMetrics::instance()->metric_registry()->deregister_entity(_entity);
730
1.16k
    if (_shards) {
731
23.2k
        for (int s = 0; s < _num_shards; s++) {
732
22.0k
            delete _shards[s];
733
22.0k
        }
734
1.16k
        delete[] _shards;
735
1.16k
    }
736
1.16k
}
737
738
14
PrunedInfo ShardedLRUCache::set_capacity(size_t capacity) {
739
14
    std::lock_guard l(_mutex);
740
14
    PrunedInfo pruned_info;
741
14
    const size_t per_shard = (capacity + (_num_shards - 1)) / _num_shards;
742
28
    for (int s = 0; s < _num_shards; s++) {
743
14
        PrunedInfo info = _shards[s]->set_capacity(per_shard);
744
14
        pruned_info.pruned_count += info.pruned_count;
745
14
        pruned_info.pruned_size += info.pruned_size;
746
14
    }
747
14
    _capacity = capacity;
748
14
    return pruned_info;
749
14
}
750
751
16.0k
size_t ShardedLRUCache::get_capacity() {
752
16.0k
    std::lock_guard l(_mutex);
753
16.0k
    return _capacity;
754
16.0k
}
755
756
Cache::Handle* ShardedLRUCache::insert(const CacheKey& key, void* value, size_t charge,
757
2.44M
                                       CachePriority priority) {
758
2.44M
    const uint32_t hash = _hash_slice(key);
759
2.44M
    return _shards[_shard(hash)]->insert(key, hash, value, charge, priority);
760
2.44M
}
761
762
21.0M
Cache::Handle* ShardedLRUCache::lookup(const CacheKey& key) {
763
21.0M
    const uint32_t hash = _hash_slice(key);
764
21.0M
    return _shards[_shard(hash)]->lookup(key, hash);
765
21.0M
}
766
767
17.2M
void ShardedLRUCache::release(Handle* handle) {
768
17.2M
    auto* h = reinterpret_cast<LRUHandle*>(handle);
769
17.2M
    _shards[_shard(h->hash)]->release(handle);
770
17.2M
}
771
772
112k
void ShardedLRUCache::erase(const CacheKey& key) {
773
112k
    const uint32_t hash = _hash_slice(key);
774
112k
    _shards[_shard(hash)]->erase(key, hash);
775
112k
}
776
777
15.5M
void* ShardedLRUCache::value(Handle* handle) {
778
15.5M
    return reinterpret_cast<LRUHandle*>(handle)->value;
779
15.5M
}
780
781
2
uint64_t ShardedLRUCache::new_id() {
782
2
    return _last_id.fetch_add(1, std::memory_order_relaxed);
783
2
}
784
785
0
PrunedInfo ShardedLRUCache::prune() {
786
0
    PrunedInfo pruned_info;
787
0
    for (int s = 0; s < _num_shards; s++) {
788
0
        PrunedInfo info = _shards[s]->prune();
789
0
        pruned_info.pruned_count += info.pruned_count;
790
0
        pruned_info.pruned_size += info.pruned_size;
791
0
    }
792
0
    return pruned_info;
793
0
}
794
795
314
PrunedInfo ShardedLRUCache::prune_if(CachePrunePredicate pred, bool lazy_mode) {
796
314
    PrunedInfo pruned_info;
797
21.5k
    for (int s = 0; s < _num_shards; s++) {
798
21.2k
        PrunedInfo info = _shards[s]->prune_if(pred, lazy_mode);
799
21.2k
        pruned_info.pruned_count += info.pruned_count;
800
21.2k
        pruned_info.pruned_size += info.pruned_size;
801
21.2k
    }
802
314
    return pruned_info;
803
314
}
804
805
2
void ShardedLRUCache::for_each_entry(const std::function<void(const LRUHandle*)>& visitor) {
806
514
    for (int s = 0; s < _num_shards; s++) {
807
512
        _shards[s]->for_each_entry(visitor);
808
512
    }
809
2
}
810
811
16.7k
int64_t ShardedLRUCache::get_usage() {
812
16.7k
    size_t total_usage = 0;
813
66.3k
    for (int i = 0; i < _num_shards; i++) {
814
49.5k
        total_usage += _shards[i]->get_usage();
815
49.5k
    }
816
16.7k
    return total_usage;
817
16.7k
}
818
819
10
size_t ShardedLRUCache::get_element_count() {
820
10
    size_t total_element_count = 0;
821
202
    for (int i = 0; i < _num_shards; i++) {
822
192
        total_element_count += _shards[i]->get_element_count();
823
192
    }
824
10
    return total_element_count;
825
10
}
826
827
6.78k
void ShardedLRUCache::update_cache_metrics() const {
828
6.78k
    size_t capacity = 0;
829
6.78k
    size_t total_usage = 0;
830
6.78k
    size_t total_lookup_count = 0;
831
6.78k
    size_t total_hit_count = 0;
832
6.78k
    size_t total_element_count = 0;
833
6.78k
    size_t total_miss_count = 0;
834
6.78k
    size_t total_stampede_count = 0;
835
836
745k
    for (int i = 0; i < _num_shards; i++) {
837
738k
        capacity += _shards[i]->get_capacity();
838
738k
        total_usage += _shards[i]->get_usage();
839
738k
        total_lookup_count += _shards[i]->get_lookup_count();
840
738k
        total_hit_count += _shards[i]->get_hit_count();
841
738k
        total_element_count += _shards[i]->get_element_count();
842
738k
        total_miss_count += _shards[i]->get_miss_count();
843
738k
        total_stampede_count += _shards[i]->get_stampede_count();
844
738k
    }
845
846
6.78k
    cache_capacity->set_value(capacity);
847
6.78k
    cache_usage->set_value(total_usage);
848
6.78k
    cache_element_count->set_value(total_element_count);
849
6.78k
    cache_lookup_count->set_value(total_lookup_count);
850
6.78k
    cache_hit_count->set_value(total_hit_count);
851
6.78k
    cache_miss_count->set_value(total_miss_count);
852
6.78k
    cache_stampede_count->set_value(total_stampede_count);
853
6.78k
    cache_usage_ratio->set_value(
854
6.78k
            capacity == 0 ? 0 : (static_cast<double>(total_usage) / static_cast<double>(capacity)));
855
6.78k
    cache_hit_ratio->set_value(total_lookup_count == 0 ? 0
856
6.78k
                                                       : (static_cast<double>(total_hit_count) /
857
4.82k
                                                          static_cast<double>(total_lookup_count)));
858
6.78k
}
859
860
Cache::Handle* DummyLRUCache::insert(const CacheKey& key, void* value, size_t charge,
861
187
                                     CachePriority priority) {
862
187
    size_t handle_size = sizeof(LRUHandle);
863
187
    auto* e = reinterpret_cast<LRUHandle*>(malloc(handle_size));
864
187
    e->value = value;
865
187
    e->charge = charge;
866
187
    e->key_length = 0;
867
187
    e->total_size = 0;
868
187
    e->hash = 0;
869
187
    e->refs = 1; // only one for the returned handle
870
187
    e->next = e->prev = nullptr;
871
187
    e->in_cache = false;
872
187
    return reinterpret_cast<Cache::Handle*>(e);
873
187
}
874
875
187
void DummyLRUCache::release(Cache::Handle* handle) {
876
187
    if (handle == nullptr) {
877
0
        return;
878
0
    }
879
187
    auto* e = reinterpret_cast<LRUHandle*>(handle);
880
187
    e->free();
881
187
}
882
883
0
void* DummyLRUCache::value(Handle* handle) {
884
0
    return reinterpret_cast<LRUHandle*>(handle)->value;
885
0
}
886
887
} // namespace doris