Coverage Report

Created: 2026-03-13 08:21

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