Coverage Report

Created: 2026-11-02 15:43

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