Coverage Report

Created: 2026-08-20 20:03

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
32.3M
inline size_t file_cache_type_index(FileCacheType type) {
48
32.3M
    return static_cast<size_t>(type);
49
32.3M
}
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
505k
    explicit UInt128Wrapper(const uint128_t& value) : value_(value) {}
63
64
365M
    bool operator==(const UInt128Wrapper& other) const { return value_ == other.value_; }
65
66
435k
    uint64_t high() const { return static_cast<uint64_t>(value_ >> 64); }
67
434k
    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 remote_physical_read_bytes = 0;
84
    int64_t bytes_write_into_file_cache = 0;
85
    int64_t remote_read_timer = 0;
86
    int64_t peer_read_timer = 0;
87
    int64_t remote_wait_timer = 0; // wait for other downloader
88
    int64_t local_read_timer = 0;
89
    int64_t local_write_timer = 0;
90
    int64_t read_cache_file_directly_timer = 0;
91
    int64_t cache_get_or_set_timer = 0;
92
    int64_t lock_wait_timer = 0;
93
    int64_t get_timer = 0;
94
    int64_t set_timer = 0;
95
    int64_t async_cache_write_submitted = 0;
96
    int64_t async_cache_write_rejected = 0;
97
    int64_t async_cache_write_buffer_alloc_fail = 0;
98
    int64_t async_cache_write_drop_stale_epoch = 0;
99
    int64_t inflight_write_buffer_index_hit = 0;
100
    int64_t inflight_write_buffer_index_miss = 0;
101
    int64_t probe_downloaded_hit = 0;
102
    int64_t probe_downloading_hit = 0;
103
    int64_t probe_miss = 0;
104
    int64_t block_wait_success = 0;
105
    int64_t block_wait_timeout = 0;
106
};
107
108
class BlockFileCache;
109
struct FileBlocksHolder;
110
using FileBlocksHolderPtr = std::unique_ptr<FileBlocksHolder>;
111
112
struct FileCacheAllocatorBuilder {
113
    bool _is_cold_data;
114
    uint64_t _expiration_time;
115
    UInt128Wrapper _cache_hash;
116
    BlockFileCache* _cache; // Only one ref, the lifetime is owned by FileCache
117
    FileBlocksHolderPtr allocate_cache_holder(size_t offset, size_t size, int64_t tablet_id) const;
118
};
119
120
struct KeyHash {
121
366M
    std::size_t operator()(const UInt128Wrapper& w) const {
122
366M
        return util_hash::HashLen16(w.value_.low(), w.value_.high());
123
366M
    }
124
};
125
126
using AccessKeyAndOffset = std::pair<UInt128Wrapper, size_t>;
127
struct KeyAndOffsetHash {
128
2.03M
    std::size_t operator()(const AccessKeyAndOffset& key) const {
129
2.03M
        return KeyHash()(key.first) ^ std::hash<uint64_t>()(key.second);
130
2.03M
    }
131
};
132
133
struct KeyMeta {
134
    uint64_t expiration_time; // absolute time
135
    FileCacheType type;
136
    int64_t tablet_id {0};
137
};
138
139
struct FileCacheKey {
140
    UInt128Wrapper hash;
141
    size_t offset;
142
    KeyMeta meta;
143
};
144
145
struct FileCacheSettings {
146
    size_t capacity {0};
147
    size_t disposable_queue_size {0};
148
    size_t disposable_queue_elements {0};
149
    size_t index_queue_size {0};
150
    size_t index_queue_elements {0};
151
    size_t query_queue_size {0};
152
    size_t query_queue_elements {0};
153
    size_t ttl_queue_size {0};
154
    size_t ttl_queue_elements {0};
155
    size_t max_file_block_size {0};
156
    size_t max_query_cache_size {0};
157
    std::string storage;
158
159
    // to string
160
    std::string to_string() const;
161
};
162
163
FileCacheSettings get_file_cache_settings(size_t capacity, size_t max_query_cache_size,
164
                                          size_t normal_percent = DEFAULT_NORMAL_PERCENT,
165
                                          size_t disposable_percent = DEFAULT_DISPOSABLE_PERCENT,
166
                                          size_t index_percent = DEFAULT_INDEX_PERCENT,
167
                                          size_t ttl_percent = DEFAULT_TTL_PERCENT,
168
                                          const std::string& storage = "disk");
169
170
struct CacheContext {
171
982k
    CacheContext(const IOContext* io_context) {
172
982k
        if (io_context->expiration_time != 0) {
173
2
            cache_type = FileCacheType::TTL;
174
2
            expiration_time = io_context->expiration_time;
175
982k
        } else if (io_context->is_index_data) {
176
138k
            cache_type = FileCacheType::INDEX;
177
844k
        } else if (io_context->is_disposable) {
178
67.0k
            cache_type = FileCacheType::DISPOSABLE;
179
777k
        } else {
180
777k
            cache_type = FileCacheType::NORMAL;
181
777k
        }
182
982k
        query_id = io_context->query_id ? *io_context->query_id : TUniqueId();
183
982k
        is_warmup = io_context->is_warmup;
184
982k
        remote_scan_cache_write_limiter = io_context->remote_scan_cache_write_limiter;
185
982k
        admit_cache_write_by_remote_scan_limiter =
186
982k
                remote_scan_cache_write_limiter != nullptr &&
187
982k
                io_context->reader_type == ReaderType::READER_QUERY &&
188
982k
                (!io_context->is_index_data || io_context->is_inverted_index ||
189
9
                 config::enable_file_cache_query_limit_segment_meta) &&
190
982k
                !io_context->is_warmup;
191
982k
    }
192
72.0k
    CacheContext() = default;
193
    bool operator==(const CacheContext& rhs) const {
194
        return query_id == rhs.query_id && cache_type == rhs.cache_type &&
195
               expiration_time == rhs.expiration_time && is_cold_data == rhs.is_cold_data;
196
    }
197
    TUniqueId query_id {};
198
    FileCacheType cache_type {FileCacheType::NORMAL};
199
    int64_t expiration_time {0};
200
    bool is_cold_data {false};
201
    ReadStatistics* stats {nullptr};
202
    bool is_warmup {false};
203
    int64_t tablet_id {0};
204
    RemoteScanCacheWriteLimiter* remote_scan_cache_write_limiter = nullptr;
205
    bool admit_cache_write_by_remote_scan_limiter {false};
206
};
207
208
template <class Lock>
209
concept IsXLock = std::same_as<Lock, std::lock_guard<std::mutex>> ||
210
                  std::same_as<Lock, std::unique_lock<std::mutex>>;
211
212
class LRUQueue {
213
public:
214
2.65k
    LRUQueue() = default;
215
    LRUQueue(size_t max_size, size_t max_element_size, int64_t hot_data_interval)
216
1.30k
            : max_size(max_size),
217
1.30k
              max_element_size(max_element_size),
218
1.30k
              hot_data_interval(hot_data_interval) {}
219
220
    struct HashFileKeyAndOffset {
221
1.93M
        std::size_t operator()(const std::pair<UInt128Wrapper, size_t>& pair) const {
222
1.93M
            return KeyHash()(pair.first) + pair.second;
223
1.93M
        }
224
    };
225
226
    struct FileKeyAndOffset {
227
        UInt128Wrapper hash;
228
        size_t offset;
229
        size_t size;
230
231
        FileKeyAndOffset(const UInt128Wrapper& hash, size_t offset, size_t size)
232
530k
                : hash(hash), offset(offset), size(size) {}
233
    };
234
235
    using Iterator = typename std::list<FileKeyAndOffset>::iterator;
236
237
286k
    size_t get_max_size() const { return max_size; }
238
708
    size_t get_max_element_size() const { return max_element_size; }
239
240
    template <class T>
241
        requires IsXLock<T>
242
291k
    size_t get_capacity(T& /* cache_lock */) const {
243
291k
        return cache_size;
244
291k
    }
245
246
705
    size_t get_capacity_unsafe() const { return cache_size; }
247
248
738
    size_t get_elements_num_unsafe() const { return queue.size(); }
249
250
690k
    size_t get_elements_num(std::lock_guard<std::mutex>& /* cache_lock */) const {
251
690k
        return queue.size();
252
690k
    }
253
254
    Iterator add(const UInt128Wrapper& hash, size_t offset, size_t size,
255
                 std::lock_guard<std::mutex>& cache_lock);
256
    template <class T>
257
        requires IsXLock<T>
258
500k
    void remove(Iterator queue_it, T& /* cache_lock */) {
259
500k
        cache_size -= queue_it->size;
260
500k
        map.erase(std::make_pair(queue_it->hash, queue_it->offset));
261
500k
        queue.erase(queue_it);
262
500k
    }
263
264
    void move_to_end(Iterator queue_it, std::lock_guard<std::mutex>& cache_lock);
265
266
    void resize(Iterator queue_it, size_t new_size, std::lock_guard<std::mutex>& cache_lock);
267
268
    std::string to_string(std::lock_guard<std::mutex>& cache_lock) const;
269
270
    bool contains(const UInt128Wrapper& hash, size_t offset,
271
                  std::lock_guard<std::mutex>& cache_lock) const;
272
273
973k
    Iterator begin() { return queue.begin(); }
274
275
973k
    Iterator end() { return queue.end(); }
276
277
    void remove_all(std::lock_guard<std::mutex>& cache_lock);
278
279
    bool pop_front(std::lock_guard<std::mutex>& cache_lock);
280
281
    Iterator get(const UInt128Wrapper& hash, size_t offset,
282
                 std::lock_guard<std::mutex>& /* cache_lock */) const;
283
284
407k
    int64_t get_hot_data_interval() const { return hot_data_interval; }
285
286
0
    void clear(std::lock_guard<std::mutex>& cache_lock) {
287
0
        queue.clear();
288
0
        map.clear();
289
0
        cache_size = 0;
290
0
    }
291
292
    size_t levenshtein_distance_from(LRUQueue& base, std::lock_guard<std::mutex>& cache_lock);
293
294
    size_t max_size;
295
    size_t max_element_size;
296
    std::list<FileKeyAndOffset> queue;
297
    std::unordered_map<std::pair<UInt128Wrapper, size_t>, Iterator, HashFileKeyAndOffset> map;
298
    size_t cache_size = 0;
299
    int64_t hot_data_interval {0};
300
};
301
struct FileCacheInfo {
302
    UInt128Wrapper hash {0};
303
    uint64_t expiration_time {0};
304
    uint64_t size {0};
305
    size_t offset {0};
306
    bool is_tmp {false};
307
    FileCacheType cache_type {NORMAL};
308
309
    std::string to_string() const;
310
};
311
312
class InconsistencyType {
313
    uint32_t type;
314
315
public:
316
    enum : uint32_t {
317
        // No anomaly
318
        NONE = 0,
319
        // Missing a block cache metadata in _files
320
        NOT_LOADED = 1 << 0,
321
        // A block cache is missing in storage
322
        MISSING_IN_STORAGE = 1 << 1,
323
        // Size of a block cache recorded in _files is inconsistent with the storage
324
        SIZE_INCONSISTENT = 1 << 2,
325
        // Cache type of a block cache recorded in _files is inconsistent with the storage
326
        CACHE_TYPE_INCONSISTENT = 1 << 3,
327
        // Expiration time of a block cache recorded in _files is inconsistent with the storage
328
        EXPIRATION_TIME_INCONSISTENT = 1 << 4,
329
        // File in storage has a _tmp suffix, but the state of block cache in _files is not set to downloading
330
        TMP_FILE_EXPECT_DOWNLOADING_STATE = 1 << 5
331
    };
332
0
    InconsistencyType(uint32_t t = 0) : type(t) {}
333
0
    operator uint32_t&() { return type; }
334
335
    std::string to_string() const;
336
};
337
338
struct InconsistencyContext {
339
    // The infos in _files of BlockFileCache.
340
    std::vector<FileCacheInfo> infos_in_manager;
341
    std::vector<FileCacheInfo> infos_in_storage;
342
    std::vector<InconsistencyType> types;
343
};
344
345
std::optional<int64_t> get_tablet_id(std::string file_path);
346
347
} // namespace doris::io