Coverage Report

Created: 2026-05-09 01:43

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
6.45M
uint32_t CacheKey::hash(const char* data, size_t n, uint32_t seed) const {
48
    // Similar to murmur hash
49
6.45M
    const uint32_t m = 0xc6a4a793;
50
6.45M
    const uint32_t r = 24;
51
6.45M
    const char* limit = data + n;
52
6.45M
    uint32_t h = seed ^ (static_cast<uint32_t>(n) * m);
53
54
    // Pick up four bytes at a time
55
151M
    while (data + 4 <= limit) {
56
144M
        uint32_t w = _decode_fixed32(data);
57
144M
        data += 4;
58
144M
        h += w;
59
144M
        h *= m;
60
144M
        h ^= (h >> 16);
61
144M
    }
62
63
    // Pick up remaining bytes
64
6.45M
    switch (limit - data) {
65
1.12M
    case 3:
66
1.12M
        h += static_cast<unsigned char>(data[2]) << 16;
67
68
        // fall through
69
2.09M
    case 2:
70
2.09M
        h += static_cast<unsigned char>(data[1]) << 8;
71
72
        // fall through
73
2.88M
    case 1:
74
2.88M
        h += static_cast<unsigned char>(data[0]);
75
2.88M
        h *= m;
76
2.88M
        h ^= (h >> r);
77
2.88M
        break;
78
79
3.57M
    default:
80
3.57M
        break;
81
6.45M
    }
82
83
6.45M
    return h;
84
6.45M
}
85
86
23.1k
HandleTable::~HandleTable() {
87
23.1k
    delete[] _list;
88
23.1k
}
89
90
// LRU cache implementation
91
5.39M
LRUHandle* HandleTable::lookup(const CacheKey& key, uint32_t hash) {
92
5.39M
    return *_find_pointer(key, hash);
93
5.39M
}
94
95
1.03M
LRUHandle* HandleTable::insert(LRUHandle* h) {
96
1.03M
    LRUHandle** ptr = _find_pointer(h->key(), h->hash);
97
1.03M
    LRUHandle* old = *ptr;
98
1.03M
    h->next_hash = old ? old->next_hash : nullptr;
99
1.03M
    *ptr = h;
100
101
1.03M
    if (old == nullptr) {
102
1.01M
        ++_elems;
103
1.01M
        if (_elems > _length) {
104
            // Since each cache entry is fairly large, we aim for a small
105
            // average linked list length (<= 1).
106
4.34k
            _resize();
107
4.34k
        }
108
1.01M
    }
109
110
1.03M
    return old;
111
1.03M
}
112
113
12.7k
LRUHandle* HandleTable::remove(const CacheKey& key, uint32_t hash) {
114
12.7k
    LRUHandle** ptr = _find_pointer(key, hash);
115
12.7k
    LRUHandle* result = *ptr;
116
117
12.7k
    if (result != nullptr) {
118
8
        *ptr = result->next_hash;
119
8
        _elems--;
120
8
    }
121
122
12.7k
    return result;
123
12.7k
}
124
125
717k
bool HandleTable::remove(const LRUHandle* h) {
126
717k
    LRUHandle** ptr = &(_list[h->hash & (_length - 1)]);
127
784k
    while (*ptr != nullptr && *ptr != h) {
128
66.7k
        ptr = &(*ptr)->next_hash;
129
66.7k
    }
130
131
717k
    LRUHandle* result = *ptr;
132
717k
    if (result != nullptr) {
133
717k
        *ptr = result->next_hash;
134
717k
        _elems--;
135
717k
        return true;
136
717k
    }
137
18.4E
    return false;
138
717k
}
139
140
6.45M
LRUHandle** HandleTable::_find_pointer(const CacheKey& key, uint32_t hash) {
141
6.45M
    LRUHandle** ptr = &(_list[hash & (_length - 1)]);
142
9.92M
    while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) {
143
3.47M
        ptr = &(*ptr)->next_hash;
144
3.47M
    }
145
146
6.45M
    return ptr;
147
6.45M
}
148
149
33.8k
void HandleTable::_resize() {
150
33.8k
    uint32_t new_length = 16;
151
44.4k
    while (new_length < _elems * 1.5) {
152
10.6k
        new_length *= 2;
153
10.6k
    }
154
155
33.8k
    auto** new_list = new (std::nothrow) LRUHandle*[new_length];
156
33.8k
    memset(new_list, 0, sizeof(new_list[0]) * new_length);
157
158
33.8k
    uint32_t count = 0;
159
829k
    for (uint32_t i = 0; i < _length; i++) {
160
795k
        LRUHandle* h = _list[i];
161
1.59M
        while (h != nullptr) {
162
798k
            LRUHandle* next = h->next_hash;
163
798k
            uint32_t hash = h->hash;
164
798k
            LRUHandle** ptr = &new_list[hash & (new_length - 1)];
165
798k
            h->next_hash = *ptr;
166
798k
            *ptr = h;
167
798k
            h = next;
168
798k
            count++;
169
798k
        }
170
795k
    }
171
172
33.8k
    DCHECK_EQ(_elems, count);
173
33.8k
    delete[] _list;
174
33.8k
    _list = new_list;
175
33.8k
    _length = new_length;
176
33.8k
}
177
178
1.06M
uint32_t HandleTable::element_count() const {
179
1.06M
    return _elems;
180
1.06M
}
181
182
29.4k
LRUCache::LRUCache(LRUCacheType type, bool is_lru_k) : _type(type), _is_lru_k(is_lru_k) {
183
    // Make empty circular linked list
184
29.4k
    _lru_normal.next = &_lru_normal;
185
29.4k
    _lru_normal.prev = &_lru_normal;
186
29.4k
    _lru_durable.next = &_lru_durable;
187
29.4k
    _lru_durable.prev = &_lru_durable;
188
29.4k
}
189
190
23.1k
LRUCache::~LRUCache() {
191
23.1k
    prune();
192
23.1k
}
193
194
29.4k
PrunedInfo LRUCache::set_capacity(size_t capacity) {
195
29.4k
    LRUHandle* last_ref_list = nullptr;
196
29.4k
    {
197
29.4k
        std::lock_guard l(_mutex);
198
29.4k
        if (capacity > _capacity) {
199
29.4k
            _capacity = capacity;
200
29.4k
            return {0, 0};
201
29.4k
        }
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
29.4k
}
217
218
1.06M
uint64_t LRUCache::get_lookup_count() {
219
1.06M
    std::lock_guard l(_mutex);
220
1.06M
    return _lookup_count;
221
1.06M
}
222
223
1.06M
uint64_t LRUCache::get_hit_count() {
224
1.06M
    std::lock_guard l(_mutex);
225
1.06M
    return _hit_count;
226
1.06M
}
227
228
1.06M
uint64_t LRUCache::get_stampede_count() {
229
1.06M
    std::lock_guard l(_mutex);
230
1.06M
    return _stampede_count;
231
1.06M
}
232
233
1.06M
uint64_t LRUCache::get_miss_count() {
234
1.06M
    std::lock_guard l(_mutex);
235
1.06M
    return _miss_count;
236
1.06M
}
237
238
1.11M
size_t LRUCache::get_usage() {
239
1.11M
    std::lock_guard l(_mutex);
240
1.11M
    return _usage;
241
1.11M
}
242
243
1.06M
size_t LRUCache::get_capacity() {
244
1.06M
    std::lock_guard l(_mutex);
245
1.06M
    return _capacity;
246
1.06M
}
247
248
1.06M
size_t LRUCache::get_element_count() {
249
1.06M
    std::lock_guard l(_mutex);
250
1.06M
    return _table.element_count();
251
1.06M
}
252
253
5.32M
bool LRUCache::_unref(LRUHandle* e) {
254
5.32M
    DCHECK(e->refs > 0);
255
5.32M
    e->refs--;
256
5.32M
    return e->refs == 0;
257
5.32M
}
258
259
3.61M
void LRUCache::_lru_remove(LRUHandle* e) {
260
3.61M
    e->next->prev = e->prev;
261
3.61M
    e->prev->next = e->next;
262
3.61M
    e->prev = e->next = nullptr;
263
264
3.61M
    if (_cache_value_check_timestamp) {
265
147
        if (e->priority == CachePriority::NORMAL) {
266
147
            auto pair = std::make_pair(_cache_value_time_extractor(e->value), e);
267
147
            auto found_it = _sorted_normal_entries_with_timestamp.find(pair);
268
147
            if (found_it != _sorted_normal_entries_with_timestamp.end()) {
269
147
                _sorted_normal_entries_with_timestamp.erase(found_it);
270
147
            }
271
147
        } 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
147
    }
279
3.61M
}
280
281
3.90M
void LRUCache::_lru_append(LRUHandle* list, LRUHandle* e) {
282
    // Make "e" newest entry by inserting just before *list
283
3.90M
    e->next = list;
284
3.90M
    e->prev = list->prev;
285
3.90M
    e->prev->next = e;
286
3.90M
    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
3.90M
    if (_cache_value_check_timestamp) {
297
147
        if (e->priority == CachePriority::NORMAL) {
298
147
            _sorted_normal_entries_with_timestamp.insert(
299
147
                    std::make_pair(_cache_value_time_extractor(e->value), e));
300
147
        } 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
147
    }
305
3.90M
}
306
307
5.39M
Cache::Handle* LRUCache::lookup(const CacheKey& key, uint32_t hash) {
308
5.39M
    std::lock_guard l(_mutex);
309
5.39M
    ++_lookup_count;
310
5.39M
    LRUHandle* e = _table.lookup(key, hash);
311
5.39M
    if (e != nullptr) {
312
        // we get it from _table, so in_cache must be true
313
3.91M
        DCHECK(e->in_cache);
314
3.91M
        if (e->refs == 1) {
315
            // only in LRU free list, remove it from list
316
2.91M
            _lru_remove(e);
317
2.91M
        }
318
3.91M
        e->refs++;
319
3.91M
        ++_hit_count;
320
3.91M
        e->last_visit_time = UnixMillis();
321
3.91M
    } else {
322
1.48M
        ++_miss_count;
323
1.48M
    }
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
5.39M
    if (e == nullptr && _is_lru_k) {
329
1.37M
        auto it = _visits_lru_cache_map.find(hash);
330
1.37M
        if (it != _visits_lru_cache_map.end()) {
331
4.21k
            _visits_lru_cache_list.splice(_visits_lru_cache_list.begin(), _visits_lru_cache_list,
332
4.21k
                                          it->second);
333
4.21k
        }
334
1.37M
    }
335
5.39M
    return reinterpret_cast<Cache::Handle*>(e);
336
5.39M
}
337
338
4.58M
void LRUCache::release(Cache::Handle* handle) {
339
4.58M
    if (handle == nullptr) {
340
0
        return;
341
0
    }
342
4.58M
    auto* e = reinterpret_cast<LRUHandle*>(handle);
343
4.58M
    bool last_ref = false;
344
4.58M
    {
345
4.58M
        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
4.58M
        last_ref = _unref(e);
349
4.58M
        if (e->in_cache && e->refs == 1) {
350
            // only exists in cache
351
3.92M
            if (_usage > _capacity) {
352
                // take this opportunity and remove the item
353
24.1k
                bool removed = _table.remove(e);
354
24.1k
                DCHECK(removed);
355
24.1k
                e->in_cache = false;
356
24.1k
                _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
24.1k
                _usage -= e->total_size;
360
24.1k
                last_ref = true;
361
3.90M
            } else {
362
                // put it to LRU free list
363
3.90M
                if (e->priority == CachePriority::NORMAL) {
364
3.90M
                    _lru_append(&_lru_normal, e);
365
3.90M
                } else if (e->priority == CachePriority::DURABLE) {
366
18
                    _lru_append(&_lru_durable, e);
367
18
                }
368
3.90M
            }
369
3.92M
        }
370
4.58M
    }
371
372
    // free handle out of mutex
373
4.58M
    if (last_ref) {
374
48.6k
        e->free();
375
48.6k
    }
376
4.58M
}
377
378
119
void LRUCache::_evict_from_lru_with_time(size_t total_size, LRUHandle** to_remove_head) {
379
    // 1. evict normal cache entries
380
140
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
381
140
           !_sorted_normal_entries_with_timestamp.empty()) {
382
21
        auto entry_pair = _sorted_normal_entries_with_timestamp.begin();
383
21
        LRUHandle* remove_handle = entry_pair->second;
384
21
        DCHECK(remove_handle != nullptr);
385
21
        DCHECK(remove_handle->priority == CachePriority::NORMAL);
386
21
        _evict_one_entry(remove_handle);
387
21
        remove_handle->next = *to_remove_head;
388
21
        *to_remove_head = remove_handle;
389
21
    }
390
391
    // 2. evict durable cache entries if need
392
119
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
393
119
           !_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
119
}
403
404
1.03M
void LRUCache::_evict_from_lru(size_t total_size, LRUHandle** to_remove_head) {
405
    // 1. evict normal cache entries
406
1.30M
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
407
1.30M
           _lru_normal.next != &_lru_normal) {
408
265k
        LRUHandle* old = _lru_normal.next;
409
265k
        DCHECK(old->priority == CachePriority::NORMAL);
410
265k
        _evict_one_entry(old);
411
265k
        old->next = *to_remove_head;
412
265k
        *to_remove_head = old;
413
265k
    }
414
    // 2. evict durable cache entries if need
415
1.03M
    while ((_usage + total_size > _capacity || _check_element_count_limit()) &&
416
1.03M
           _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
1.03M
}
424
425
693k
void LRUCache::_evict_one_entry(LRUHandle* e) {
426
693k
    DCHECK(e->in_cache);
427
693k
    DCHECK(e->refs == 1); // LRU list contains elements which may be evicted
428
693k
    _lru_remove(e);
429
693k
    bool removed = _table.remove(e);
430
693k
    DCHECK(removed);
431
693k
    e->in_cache = false;
432
693k
    _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
693k
    _usage -= e->total_size;
436
693k
}
437
438
2.65M
bool LRUCache::_check_element_count_limit() {
439
2.65M
    return _element_count_capacity != 0 && _table.element_count() >= _element_count_capacity;
440
2.65M
}
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
654k
bool LRUCache::_lru_k_insert_visits_list(size_t total_size, visits_lru_cache_key visits_key) {
448
654k
    if (_usage + total_size > _capacity ||
449
654k
        _check_element_count_limit()) { // this line no lock required
450
12.4k
        auto it = _visits_lru_cache_map.find(visits_key);
451
12.4k
        if (it != _visits_lru_cache_map.end()) {
452
4.23k
            _visits_lru_cache_usage -= it->second->second;
453
4.23k
            _visits_lru_cache_list.erase(it->second);
454
4.23k
            _visits_lru_cache_map.erase(it);
455
8.20k
        } 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
8.89k
            while (_visits_lru_cache_usage + total_size > _capacity &&
459
8.89k
                   _visits_lru_cache_usage != 0) {
460
681
                DCHECK(!_visits_lru_cache_map.empty());
461
681
                _visits_lru_cache_usage -= _visits_lru_cache_list.back().second;
462
681
                _visits_lru_cache_map.erase(_visits_lru_cache_list.back().first);
463
681
                _visits_lru_cache_list.pop_back();
464
681
            }
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
8.20k
            if (_visits_lru_cache_usage + total_size <= _capacity) {
468
6.85k
                _visits_lru_cache_list.emplace_front(visits_key, total_size);
469
6.85k
                _visits_lru_cache_map[visits_key] = _visits_lru_cache_list.begin();
470
6.85k
                _visits_lru_cache_usage += total_size;
471
6.85k
            }
472
8.20k
            return true;
473
8.20k
        }
474
12.4k
    }
475
646k
    return false;
476
654k
}
477
478
Cache::Handle* LRUCache::insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
479
1.04M
                                CachePriority priority) {
480
1.04M
    size_t handle_size = sizeof(LRUHandle) - 1 + key.size();
481
1.04M
    auto* e = reinterpret_cast<LRUHandle*>(malloc(handle_size));
482
1.04M
    e->value = value;
483
1.04M
    e->charge = charge;
484
1.04M
    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
1.04M
    e->total_size = (_type == LRUCacheType::SIZE ? handle_size + charge : charge);
488
1.04M
    e->hash = hash;
489
1.04M
    e->refs = 1; // only one for the returned handle.
490
1.04M
    e->next = e->prev = nullptr;
491
1.04M
    e->in_cache = false;
492
1.04M
    e->priority = priority;
493
1.04M
    e->type = _type;
494
1.04M
    memcpy(e->key_data, key.data(), key.size());
495
1.04M
    e->last_visit_time = UnixMillis();
496
497
1.04M
    LRUHandle* to_remove_head = nullptr;
498
1.04M
    {
499
1.04M
        std::lock_guard l(_mutex);
500
501
1.04M
        if (_is_lru_k && _lru_k_insert_visits_list(e->total_size, hash)) {
502
8.22k
            return reinterpret_cast<Cache::Handle*>(e);
503
8.22k
        }
504
505
        // Free the space following strict LRU policy until enough space
506
        // is freed or the lru list is empty
507
1.03M
        if (_cache_value_check_timestamp) {
508
119
            _evict_from_lru_with_time(e->total_size, &to_remove_head);
509
1.03M
        } else {
510
1.03M
            _evict_from_lru(e->total_size, &to_remove_head);
511
1.03M
        }
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
1.03M
        auto* old = _table.insert(e);
517
1.03M
        e->in_cache = true;
518
1.03M
        _usage += e->total_size;
519
1.03M
        e->refs++; // one for the returned handle, one for LRUCache.
520
1.03M
        if (old != nullptr) {
521
21.9k
            _stampede_count++;
522
21.9k
            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
21.9k
            _usage -= old->total_size;
530
            // if false, old entry is being used externally, just ref-- and sub _usage,
531
21.9k
            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
5.62k
                _lru_remove(old);
535
5.62k
                old->next = to_remove_head;
536
5.62k
                to_remove_head = old;
537
5.62k
            }
538
21.9k
        }
539
1.03M
    }
540
541
    // we free the entries here outside of mutex for
542
    // performance reasons
543
1.25M
    while (to_remove_head != nullptr) {
544
215k
        LRUHandle* next = to_remove_head->next;
545
215k
        to_remove_head->free();
546
215k
        to_remove_head = next;
547
215k
    }
548
549
1.03M
    return reinterpret_cast<Cache::Handle*>(e);
550
1.04M
}
551
552
12.7k
void LRUCache::erase(const CacheKey& key, uint32_t hash) {
553
12.7k
    LRUHandle* e = nullptr;
554
12.7k
    bool last_ref = false;
555
12.7k
    {
556
12.7k
        std::lock_guard l(_mutex);
557
12.7k
        e = _table.remove(key, hash);
558
12.7k
        if (e != nullptr) {
559
5
            last_ref = _unref(e);
560
            // if last_ref is false or in_cache is false, e must not be in lru
561
5
            if (last_ref && e->in_cache) {
562
                // locate in free list
563
2
                _lru_remove(e);
564
2
            }
565
5
            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
5
            _usage -= e->total_size;
569
5
        }
570
12.7k
    }
571
    // free handle out of mutex, when last_ref is true, e must not be nullptr
572
12.7k
    if (last_ref) {
573
2
        e->free();
574
2
    }
575
12.7k
}
576
577
23.1k
PrunedInfo LRUCache::prune() {
578
23.1k
    LRUHandle* to_remove_head = nullptr;
579
23.1k
    {
580
23.1k
        std::lock_guard l(_mutex);
581
329k
        while (_lru_normal.next != &_lru_normal) {
582
306k
            LRUHandle* old = _lru_normal.next;
583
306k
            _evict_one_entry(old);
584
306k
            old->next = to_remove_head;
585
306k
            to_remove_head = old;
586
306k
        }
587
23.1k
        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
23.1k
    }
594
23.1k
    int64_t pruned_count = 0;
595
23.1k
    int64_t pruned_size = 0;
596
329k
    while (to_remove_head != nullptr) {
597
306k
        ++pruned_count;
598
306k
        pruned_size += to_remove_head->total_size;
599
306k
        LRUHandle* next = to_remove_head->next;
600
306k
        to_remove_head->free();
601
306k
        to_remove_head = next;
602
306k
    }
603
23.1k
    return {pruned_count, pruned_size};
604
23.1k
}
605
606
17.9k
PrunedInfo LRUCache::prune_if(CachePrunePredicate pred, bool lazy_mode) {
607
17.9k
    LRUHandle* to_remove_head = nullptr;
608
17.9k
    {
609
17.9k
        std::lock_guard l(_mutex);
610
17.9k
        LRUHandle* p = _lru_normal.next;
611
138k
        while (p != &_lru_normal) {
612
136k
            LRUHandle* next = p->next;
613
136k
            if (pred(p)) {
614
120k
                _evict_one_entry(p);
615
120k
                p->next = to_remove_head;
616
120k
                to_remove_head = p;
617
120k
            } else if (lazy_mode) {
618
15.2k
                break;
619
15.2k
            }
620
120k
            p = next;
621
120k
        }
622
623
17.9k
        p = _lru_durable.next;
624
17.9k
        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
17.9k
    }
636
17.9k
    int64_t pruned_count = 0;
637
17.9k
    int64_t pruned_size = 0;
638
138k
    while (to_remove_head != nullptr) {
639
120k
        ++pruned_count;
640
120k
        pruned_size += to_remove_head->total_size;
641
120k
        LRUHandle* next = to_remove_head->next;
642
120k
        to_remove_head->free();
643
120k
        to_remove_head = next;
644
120k
    }
645
17.9k
    return {pruned_count, pruned_size};
646
17.9k
}
647
648
0
void LRUCache::for_each_entry(const std::function<void(const LRUHandle*)>& visitor) {
649
0
    std::lock_guard l(_mutex);
650
0
    for (LRUHandle* p = _lru_normal.next; p != &_lru_normal; p = p->next) {
651
0
        visitor(p);
652
0
    }
653
0
    for (LRUHandle* p = _lru_durable.next; p != &_lru_durable; p = p->next) {
654
0
        visitor(p);
655
0
    }
656
0
}
657
658
1.65k
void LRUCache::set_cache_value_time_extractor(CacheValueTimeExtractor cache_value_time_extractor) {
659
1.65k
    _cache_value_time_extractor = cache_value_time_extractor;
660
1.65k
}
661
662
1.65k
void LRUCache::set_cache_value_check_timestamp(bool cache_value_check_timestamp) {
663
1.65k
    _cache_value_check_timestamp = cache_value_check_timestamp;
664
1.65k
}
665
666
6.45M
inline uint32_t ShardedLRUCache::_hash_slice(const CacheKey& s) {
667
6.45M
    return s.hash(s.data(), s.size(), 0);
668
6.45M
}
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.29k
        : _name(name),
674
1.29k
          _num_shard_bits(__builtin_ctz(num_shards)),
675
1.29k
          _num_shards(num_shards),
676
1.29k
          _last_id(1),
677
1.29k
          _capacity(capacity) {
678
1.29k
    CHECK(num_shards > 0) << "num_shards cannot be 0";
679
1.29k
    CHECK_EQ((num_shards & (num_shards - 1)), 0)
680
0
            << "num_shards should be power of two, but got " << num_shards;
681
682
1.29k
    const size_t per_shard = (capacity + (_num_shards - 1)) / _num_shards;
683
1.29k
    const uint32_t per_shard_element_count_capacity =
684
1.29k
            (total_element_count_capacity + (_num_shards - 1)) / _num_shards;
685
1.29k
    auto** shards = new (std::nothrow) LRUCache*[_num_shards];
686
30.7k
    for (int s = 0; s < _num_shards; s++) {
687
29.4k
        shards[s] = new LRUCache(type, is_lru_k);
688
29.4k
        shards[s]->set_capacity(per_shard);
689
29.4k
        shards[s]->set_element_count_capacity(per_shard_element_count_capacity);
690
29.4k
    }
691
1.29k
    _shards = shards;
692
693
1.29k
    _entity = DorisMetrics::instance()->metric_registry()->register_entity(
694
1.29k
            std::string("lru_cache:") + name, {{"name", name}});
695
1.29k
    _entity->register_hook(name, std::bind(&ShardedLRUCache::update_cache_metrics, this));
696
1.29k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_capacity);
697
1.29k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_usage);
698
1.29k
    INT_GAUGE_METRIC_REGISTER(_entity, cache_element_count);
699
1.29k
    DOUBLE_GAUGE_METRIC_REGISTER(_entity, cache_usage_ratio);
700
1.29k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_lookup_count);
701
1.29k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_hit_count);
702
1.29k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_stampede_count);
703
1.29k
    INT_COUNTER_METRIC_REGISTER(_entity, cache_miss_count);
704
1.29k
    DOUBLE_GAUGE_METRIC_REGISTER(_entity, cache_hit_ratio);
705
706
1.29k
    _hit_count_bvar.reset(new bvar::Adder<uint64_t>("doris_cache", _name));
707
1.29k
    _hit_count_per_second.reset(new bvar::PerSecond<bvar::Adder<uint64_t>>(
708
1.29k
            "doris_cache", _name + "_persecond", _hit_count_bvar.get(), 60));
709
1.29k
    _lookup_count_bvar.reset(new bvar::Adder<uint64_t>("doris_cache", _name));
710
1.29k
    _lookup_count_per_second.reset(new bvar::PerSecond<bvar::Adder<uint64_t>>(
711
1.29k
            "doris_cache", _name + "_persecond", _lookup_count_bvar.get(), 60));
712
1.29k
}
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
123
        : ShardedLRUCache(name, capacity, type, num_shards, total_element_count_capacity,
720
123
                          is_lru_k) {
721
1.77k
    for (int s = 0; s < _num_shards; s++) {
722
1.65k
        _shards[s]->set_cache_value_time_extractor(cache_value_time_extractor);
723
1.65k
        _shards[s]->set_cache_value_check_timestamp(cache_value_check_timestamp);
724
1.65k
    }
725
123
}
726
727
1.23k
ShardedLRUCache::~ShardedLRUCache() {
728
1.23k
    _entity->deregister_hook(_name);
729
1.23k
    DorisMetrics::instance()->metric_registry()->deregister_entity(_entity);
730
1.23k
    if (_shards) {
731
24.3k
        for (int s = 0; s < _num_shards; s++) {
732
23.1k
            delete _shards[s];
733
23.1k
        }
734
1.23k
        delete[] _shards;
735
1.23k
    }
736
1.23k
}
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
1.04M
                                       CachePriority priority) {
758
1.04M
    const uint32_t hash = _hash_slice(key);
759
1.04M
    return _shards[_shard(hash)]->insert(key, hash, value, charge, priority);
760
1.04M
}
761
762
5.39M
Cache::Handle* ShardedLRUCache::lookup(const CacheKey& key) {
763
5.39M
    const uint32_t hash = _hash_slice(key);
764
5.39M
    return _shards[_shard(hash)]->lookup(key, hash);
765
5.39M
}
766
767
4.58M
void ShardedLRUCache::release(Handle* handle) {
768
4.58M
    auto* h = reinterpret_cast<LRUHandle*>(handle);
769
4.58M
    _shards[_shard(h->hash)]->release(handle);
770
4.58M
}
771
772
12.7k
void ShardedLRUCache::erase(const CacheKey& key) {
773
12.7k
    const uint32_t hash = _hash_slice(key);
774
12.7k
    _shards[_shard(hash)]->erase(key, hash);
775
12.7k
}
776
777
4.45M
void* ShardedLRUCache::value(Handle* handle) {
778
4.45M
    return reinterpret_cast<LRUHandle*>(handle)->value;
779
4.45M
}
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
268
PrunedInfo ShardedLRUCache::prune_if(CachePrunePredicate pred, bool lazy_mode) {
796
268
    PrunedInfo pruned_info;
797
18.2k
    for (int s = 0; s < _num_shards; s++) {
798
17.9k
        PrunedInfo info = _shards[s]->prune_if(pred, lazy_mode);
799
17.9k
        pruned_info.pruned_count += info.pruned_count;
800
17.9k
        pruned_info.pruned_size += info.pruned_size;
801
17.9k
    }
802
268
    return pruned_info;
803
268
}
804
805
0
void ShardedLRUCache::for_each_entry(const std::function<void(const LRUHandle*)>& visitor) {
806
0
    for (int s = 0; s < _num_shards; s++) {
807
0
        _shards[s]->for_each_entry(visitor);
808
0
    }
809
0
}
810
811
17.2k
int64_t ShardedLRUCache::get_usage() {
812
17.2k
    size_t total_usage = 0;
813
73.9k
    for (int i = 0; i < _num_shards; i++) {
814
56.6k
        total_usage += _shards[i]->get_usage();
815
56.6k
    }
816
17.2k
    return total_usage;
817
17.2k
}
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
9.72k
void ShardedLRUCache::update_cache_metrics() const {
828
9.72k
    size_t capacity = 0;
829
9.72k
    size_t total_usage = 0;
830
9.72k
    size_t total_lookup_count = 0;
831
9.72k
    size_t total_hit_count = 0;
832
9.72k
    size_t total_element_count = 0;
833
9.72k
    size_t total_miss_count = 0;
834
9.72k
    size_t total_stampede_count = 0;
835
836
1.07M
    for (int i = 0; i < _num_shards; i++) {
837
1.06M
        capacity += _shards[i]->get_capacity();
838
1.06M
        total_usage += _shards[i]->get_usage();
839
1.06M
        total_lookup_count += _shards[i]->get_lookup_count();
840
1.06M
        total_hit_count += _shards[i]->get_hit_count();
841
1.06M
        total_element_count += _shards[i]->get_element_count();
842
1.06M
        total_miss_count += _shards[i]->get_miss_count();
843
1.06M
        total_stampede_count += _shards[i]->get_stampede_count();
844
1.06M
    }
845
846
9.72k
    cache_capacity->set_value(capacity);
847
9.72k
    cache_usage->set_value(total_usage);
848
9.72k
    cache_element_count->set_value(total_element_count);
849
9.72k
    cache_lookup_count->set_value(total_lookup_count);
850
9.72k
    cache_hit_count->set_value(total_hit_count);
851
9.72k
    cache_miss_count->set_value(total_miss_count);
852
9.72k
    cache_stampede_count->set_value(total_stampede_count);
853
9.72k
    cache_usage_ratio->set_value(
854
9.72k
            capacity == 0 ? 0 : (static_cast<double>(total_usage) / static_cast<double>(capacity)));
855
9.72k
    cache_hit_ratio->set_value(total_lookup_count == 0 ? 0
856
9.72k
                                                       : (static_cast<double>(total_hit_count) /
857
4.48k
                                                          static_cast<double>(total_lookup_count)));
858
9.72k
}
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