Coverage Report

Created: 2026-03-11 17:55

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