Coverage Report

Created: 2026-04-16 21:18

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