Coverage Report

Created: 2026-07-09 13:33

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