Coverage Report

Created: 2026-08-16 12:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/file_cache_common.h
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
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Interpreters/Cache/FileCache_fwd.h
19
// and modified by Doris
20
21
#pragma once
22
#include <cstdint>
23
#include <vector>
24
25
#include "common/config.h"
26
#include "core/uint128.h"
27
#include "io/io_common.h"
28
29
namespace doris::io {
30
31
inline static constexpr size_t REMOTE_FS_OBJECTS_CACHE_DEFAULT_ELEMENTS = 100 * 1024;
32
inline static constexpr size_t FILE_CACHE_MAX_FILE_BLOCK_SIZE = 1 * 1024 * 1024;
33
inline static constexpr size_t DEFAULT_NORMAL_PERCENT = 40;
34
inline static constexpr size_t DEFAULT_DISPOSABLE_PERCENT = 5;
35
inline static constexpr size_t DEFAULT_INDEX_PERCENT = 5;
36
inline static constexpr size_t DEFAULT_TTL_PERCENT = 50;
37
38
using uint128_t = UInt128;
39
40
enum FileCacheType {
41
    INDEX = 2,
42
    NORMAL = 1,
43
    DISPOSABLE = 0,
44
    TTL = 3,
45
};
46
47
31.9M
inline size_t file_cache_type_index(FileCacheType type) {
48
31.9M
    return static_cast<size_t>(type);
49
31.9M
}
50
51
std::string cache_type_to_surfix(FileCacheType type);
52
FileCacheType surfix_to_cache_type(const std::string& str);
53
54
FileCacheType string_to_cache_type(const std::string& str);
55
std::string cache_type_to_string(FileCacheType type);
56
57
struct UInt128Wrapper {
58
    uint128_t value_;
59
    [[nodiscard]] std::string to_string() const;
60
61
    UInt128Wrapper() = default;
62
503k
    explicit UInt128Wrapper(const uint128_t& value) : value_(value) {}
63
64
272M
    bool operator==(const UInt128Wrapper& other) const { return value_ == other.value_; }
65
66
407k
    uint64_t high() const { return static_cast<uint64_t>(value_ >> 64); }
67
406k
    uint64_t low() const { return static_cast<uint64_t>(value_); }
68
69
    friend std::ostream& operator<<(std::ostream& os, const UInt128Wrapper& wrapper) {
70
        os << "UInt128Wrapper(" << wrapper.high() << ", " << wrapper.low() << ")";
71
        return os;
72
    }
73
};
74
75
struct ReadStatistics {
76
    bool hit_cache = true;
77
    bool from_peer_cache = false;
78
    bool skip_cache = false;
79
    int64_t bytes_read = 0;
80
    int64_t bytes_read_from_local = 0;
81
    int64_t bytes_read_from_remote = 0;
82
    int64_t bytes_read_from_peer = 0;
83
    int64_t bytes_write_into_file_cache = 0;
84
    int64_t remote_read_timer = 0;
85
    int64_t peer_read_timer = 0;
86
    int64_t remote_wait_timer = 0; // wait for other downloader
87
    int64_t local_read_timer = 0;
88
    int64_t local_write_timer = 0;
89
    int64_t read_cache_file_directly_timer = 0;
90
    int64_t cache_get_or_set_timer = 0;
91
    int64_t lock_wait_timer = 0;
92
    int64_t get_timer = 0;
93
    int64_t set_timer = 0;
94
};
95
96
class BlockFileCache;
97
struct FileBlocksHolder;
98
using FileBlocksHolderPtr = std::unique_ptr<FileBlocksHolder>;
99
100
struct FileCacheAllocatorBuilder {
101
    bool _is_cold_data;
102
    uint64_t _expiration_time;
103
    UInt128Wrapper _cache_hash;
104
    BlockFileCache* _cache; // Only one ref, the lifetime is owned by FileCache
105
    FileBlocksHolderPtr allocate_cache_holder(size_t offset, size_t size, int64_t tablet_id) const;
106
};
107
108
struct KeyHash {
109
273M
    std::size_t operator()(const UInt128Wrapper& w) const {
110
273M
        return util_hash::HashLen16(w.value_.low(), w.value_.high());
111
273M
    }
112
};
113
114
using AccessKeyAndOffset = std::pair<UInt128Wrapper, size_t>;
115
struct KeyAndOffsetHash {
116
4.66M
    std::size_t operator()(const AccessKeyAndOffset& key) const {
117
4.66M
        return KeyHash()(key.first) ^ std::hash<uint64_t>()(key.second);
118
4.66M
    }
119
};
120
121
struct KeyMeta {
122
    uint64_t expiration_time; // absolute time
123
    FileCacheType type;
124
    int64_t tablet_id {0};
125
};
126
127
struct FileCacheKey {
128
    UInt128Wrapper hash;
129
    size_t offset;
130
    KeyMeta meta;
131
};
132
133
struct FileCacheSettings {
134
    size_t capacity {0};
135
    size_t disposable_queue_size {0};
136
    size_t disposable_queue_elements {0};
137
    size_t index_queue_size {0};
138
    size_t index_queue_elements {0};
139
    size_t query_queue_size {0};
140
    size_t query_queue_elements {0};
141
    size_t ttl_queue_size {0};
142
    size_t ttl_queue_elements {0};
143
    size_t max_file_block_size {0};
144
    size_t max_query_cache_size {0};
145
    std::string storage;
146
147
    // to string
148
    std::string to_string() const;
149
};
150
151
FileCacheSettings get_file_cache_settings(size_t capacity, size_t max_query_cache_size,
152
                                          size_t normal_percent = DEFAULT_NORMAL_PERCENT,
153
                                          size_t disposable_percent = DEFAULT_DISPOSABLE_PERCENT,
154
                                          size_t index_percent = DEFAULT_INDEX_PERCENT,
155
                                          size_t ttl_percent = DEFAULT_TTL_PERCENT,
156
                                          const std::string& storage = "disk");
157
158
struct CacheContext {
159
1.09M
    CacheContext(const IOContext* io_context) {
160
1.09M
        if (io_context->expiration_time != 0) {
161
2
            cache_type = FileCacheType::TTL;
162
2
            expiration_time = io_context->expiration_time;
163
1.09M
        } else if (io_context->is_index_data) {
164
231k
            cache_type = FileCacheType::INDEX;
165
865k
        } else if (io_context->is_disposable) {
166
86.7k
            cache_type = FileCacheType::DISPOSABLE;
167
778k
        } else {
168
778k
            cache_type = FileCacheType::NORMAL;
169
778k
        }
170
1.09M
        query_id = io_context->query_id ? *io_context->query_id : TUniqueId();
171
1.09M
        is_warmup = io_context->is_warmup;
172
1.09M
        remote_scan_cache_write_limiter = io_context->remote_scan_cache_write_limiter;
173
1.09M
        admit_cache_write_by_remote_scan_limiter =
174
1.09M
                remote_scan_cache_write_limiter != nullptr &&
175
1.09M
                io_context->reader_type == ReaderType::READER_QUERY &&
176
1.09M
                (!io_context->is_index_data || io_context->is_inverted_index ||
177
9
                 config::enable_file_cache_query_limit_segment_meta) &&
178
1.09M
                !io_context->is_warmup;
179
1.09M
    }
180
71.8k
    CacheContext() = default;
181
    bool operator==(const CacheContext& rhs) const {
182
        return query_id == rhs.query_id && cache_type == rhs.cache_type &&
183
               expiration_time == rhs.expiration_time && is_cold_data == rhs.is_cold_data;
184
    }
185
    TUniqueId query_id {};
186
    FileCacheType cache_type {FileCacheType::NORMAL};
187
    int64_t expiration_time {0};
188
    bool is_cold_data {false};
189
    ReadStatistics* stats {nullptr};
190
    bool is_warmup {false};
191
    int64_t tablet_id {0};
192
    RemoteScanCacheWriteLimiter* remote_scan_cache_write_limiter = nullptr;
193
    bool admit_cache_write_by_remote_scan_limiter {false};
194
};
195
196
template <class Lock>
197
concept IsXLock = std::same_as<Lock, std::lock_guard<std::mutex>> ||
198
                  std::same_as<Lock, std::unique_lock<std::mutex>>;
199
200
class LRUQueue {
201
public:
202
2.24k
    LRUQueue() = default;
203
    LRUQueue(size_t max_size, size_t max_element_size, int64_t hot_data_interval)
204
1.09k
            : max_size(max_size),
205
1.09k
              max_element_size(max_element_size),
206
1.09k
              hot_data_interval(hot_data_interval) {}
207
208
    struct HashFileKeyAndOffset {
209
1.98M
        std::size_t operator()(const std::pair<UInt128Wrapper, size_t>& pair) const {
210
1.98M
            return KeyHash()(pair.first) + pair.second;
211
1.98M
        }
212
    };
213
214
    struct FileKeyAndOffset {
215
        UInt128Wrapper hash;
216
        size_t offset;
217
        size_t size;
218
219
        FileKeyAndOffset(const UInt128Wrapper& hash, size_t offset, size_t size)
220
516k
                : hash(hash), offset(offset), size(size) {}
221
    };
222
223
    using Iterator = typename std::list<FileKeyAndOffset>::iterator;
224
225
245k
    size_t get_max_size() const { return max_size; }
226
708
    size_t get_max_element_size() const { return max_element_size; }
227
228
    template <class T>
229
        requires IsXLock<T>
230
250k
    size_t get_capacity(T& /* cache_lock */) const {
231
250k
        return cache_size;
232
250k
    }
233
234
705
    size_t get_capacity_unsafe() const { return cache_size; }
235
236
738
    size_t get_elements_num_unsafe() const { return queue.size(); }
237
238
692k
    size_t get_elements_num(std::lock_guard<std::mutex>& /* cache_lock */) const {
239
692k
        return queue.size();
240
692k
    }
241
242
    Iterator add(const UInt128Wrapper& hash, size_t offset, size_t size,
243
                 std::lock_guard<std::mutex>& cache_lock);
244
    template <class T>
245
        requires IsXLock<T>
246
486k
    void remove(Iterator queue_it, T& /* cache_lock */) {
247
486k
        cache_size -= queue_it->size;
248
486k
        map.erase(std::make_pair(queue_it->hash, queue_it->offset));
249
486k
        queue.erase(queue_it);
250
486k
    }
251
252
    void move_to_end(Iterator queue_it, std::lock_guard<std::mutex>& cache_lock);
253
254
    void resize(Iterator queue_it, size_t new_size, std::lock_guard<std::mutex>& cache_lock);
255
256
    std::string to_string(std::lock_guard<std::mutex>& cache_lock) const;
257
258
    bool contains(const UInt128Wrapper& hash, size_t offset,
259
                  std::lock_guard<std::mutex>& cache_lock) const;
260
261
1.01M
    Iterator begin() { return queue.begin(); }
262
263
1.01M
    Iterator end() { return queue.end(); }
264
265
    void remove_all(std::lock_guard<std::mutex>& cache_lock);
266
267
    bool pop_front(std::lock_guard<std::mutex>& cache_lock);
268
269
    Iterator get(const UInt128Wrapper& hash, size_t offset,
270
                 std::lock_guard<std::mutex>& /* cache_lock */) const;
271
272
474k
    int64_t get_hot_data_interval() const { return hot_data_interval; }
273
274
0
    void clear(std::lock_guard<std::mutex>& cache_lock) {
275
0
        queue.clear();
276
0
        map.clear();
277
0
        cache_size = 0;
278
0
    }
279
280
    size_t levenshtein_distance_from(LRUQueue& base, std::lock_guard<std::mutex>& cache_lock);
281
282
    size_t max_size;
283
    size_t max_element_size;
284
    std::list<FileKeyAndOffset> queue;
285
    std::unordered_map<std::pair<UInt128Wrapper, size_t>, Iterator, HashFileKeyAndOffset> map;
286
    size_t cache_size = 0;
287
    int64_t hot_data_interval {0};
288
};
289
struct FileCacheInfo {
290
    UInt128Wrapper hash {0};
291
    uint64_t expiration_time {0};
292
    uint64_t size {0};
293
    size_t offset {0};
294
    bool is_tmp {false};
295
    FileCacheType cache_type {NORMAL};
296
297
    std::string to_string() const;
298
};
299
300
class InconsistencyType {
301
    uint32_t type;
302
303
public:
304
    enum : uint32_t {
305
        // No anomaly
306
        NONE = 0,
307
        // Missing a block cache metadata in _files
308
        NOT_LOADED = 1 << 0,
309
        // A block cache is missing in storage
310
        MISSING_IN_STORAGE = 1 << 1,
311
        // Size of a block cache recorded in _files is inconsistent with the storage
312
        SIZE_INCONSISTENT = 1 << 2,
313
        // Cache type of a block cache recorded in _files is inconsistent with the storage
314
        CACHE_TYPE_INCONSISTENT = 1 << 3,
315
        // Expiration time of a block cache recorded in _files is inconsistent with the storage
316
        EXPIRATION_TIME_INCONSISTENT = 1 << 4,
317
        // File in storage has a _tmp suffix, but the state of block cache in _files is not set to downloading
318
        TMP_FILE_EXPECT_DOWNLOADING_STATE = 1 << 5
319
    };
320
0
    InconsistencyType(uint32_t t = 0) : type(t) {}
321
0
    operator uint32_t&() { return type; }
322
323
    std::string to_string() const;
324
};
325
326
struct InconsistencyContext {
327
    // The infos in _files of BlockFileCache.
328
    std::vector<FileCacheInfo> infos_in_manager;
329
    std::vector<FileCacheInfo> infos_in_storage;
330
    std::vector<InconsistencyType> types;
331
};
332
333
std::optional<int64_t> get_tablet_id(std::string file_path);
334
335
} // namespace doris::io