Coverage Report

Created: 2026-05-13 01:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/cached_remote_file_reader.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
18
#include "io/cache/cached_remote_file_reader.h"
19
20
#include <brpc/controller.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/Types_types.h>
23
#include <gen_cpp/internal_service.pb.h>
24
#include <glog/logging.h>
25
26
#include <algorithm>
27
#include <atomic>
28
#include <condition_variable>
29
#include <cstring>
30
#include <functional>
31
#include <list>
32
#include <memory>
33
#include <mutex>
34
#include <thread>
35
#include <vector>
36
37
#include "cloud/cloud_warm_up_manager.h"
38
#include "cloud/config.h"
39
#include "common/compiler_util.h" // IWYU pragma: keep
40
#include "common/config.h"
41
#include "cpp/sync_point.h"
42
#include "cpp/token_bucket_rate_limiter.h"
43
#include "io/cache/block_file_cache.h"
44
#include "io/cache/block_file_cache_factory.h"
45
#include "io/cache/block_file_cache_profile.h"
46
#include "io/cache/file_block.h"
47
#include "io/cache/file_cache_common.h"
48
#include "io/cache/peer_file_cache_reader.h"
49
#include "io/fs/file_reader.h"
50
#include "io/fs/local_file_system.h"
51
#include "io/io_common.h"
52
#include "runtime/exec_env.h"
53
#include "runtime/runtime_profile.h"
54
#include "runtime/thread_context.h"
55
#include "runtime/workload_management/io_throttle.h"
56
#include "service/backend_options.h"
57
#include "util/bit_util.h"
58
#include "util/brpc_client_cache.h" // BrpcClientCache
59
#include "util/client_cache.h"
60
#include "util/concurrency_stats.h"
61
#include "util/debug_points.h"
62
63
namespace doris::io {
64
65
bvar::Adder<uint64_t> s3_read_counter("cached_remote_reader_s3_read");
66
bvar::Adder<uint64_t> peer_read_counter("cached_remote_reader_peer_read");
67
bvar::LatencyRecorder g_skip_cache_num("cached_remote_reader_skip_cache_num");
68
bvar::Adder<uint64_t> g_skip_cache_sum("cached_remote_reader_skip_cache_sum");
69
bvar::Adder<uint64_t> g_skip_local_cache_io_sum_bytes(
70
        "cached_remote_reader_skip_local_cache_io_sum_bytes");
71
bvar::Adder<uint64_t> g_read_cache_direct_whole_num("cached_remote_reader_cache_direct_whole_num");
72
bvar::Adder<uint64_t> g_read_cache_direct_partial_num(
73
        "cached_remote_reader_cache_direct_partial_num");
74
bvar::Adder<uint64_t> g_read_cache_indirect_num("cached_remote_reader_cache_indirect_num");
75
bvar::Adder<uint64_t> g_read_cache_direct_whole_bytes(
76
        "cached_remote_reader_cache_direct_whole_bytes");
77
bvar::Adder<uint64_t> g_read_cache_direct_partial_bytes(
78
        "cached_remote_reader_cache_direct_partial_bytes");
79
bvar::Adder<uint64_t> g_read_cache_indirect_bytes("cached_remote_reader_cache_indirect_bytes");
80
bvar::Adder<uint64_t> g_read_cache_indirect_total_bytes(
81
        "cached_remote_reader_cache_indirect_total_bytes");
82
bvar::Adder<uint64_t> g_read_cache_self_heal_on_not_found(
83
        "cached_remote_reader_self_heal_on_not_found");
84
bvar::Window<bvar::Adder<uint64_t>> g_read_cache_indirect_bytes_1min_window(
85
        "cached_remote_reader_indirect_bytes_1min_window", &g_read_cache_indirect_bytes, 60);
86
bvar::Window<bvar::Adder<uint64_t>> g_read_cache_indirect_total_bytes_1min_window(
87
        "cached_remote_reader_indirect_total_bytes_1min_window", &g_read_cache_indirect_total_bytes,
88
        60);
89
bvar::Adder<uint64_t> g_failed_get_peer_addr_counter(
90
        "cached_remote_reader_failed_get_peer_addr_counter");
91
92
CachedRemoteFileReader::CachedRemoteFileReader(FileReaderSPtr remote_file_reader,
93
                                               const FileReaderOptions& opts)
94
2.01k
        : _tablet_id(opts.tablet_id), _remote_file_reader(std::move(remote_file_reader)) {
95
2.01k
    DCHECK(!opts.is_doris_table || _tablet_id > 0);
96
2.01k
    _is_doris_table = opts.is_doris_table;
97
2.01k
    if (_is_doris_table) {
98
2.01k
        _cache_hash = BlockFileCache::hash(path().filename().native());
99
2.01k
        _cache = FileCacheFactory::instance()->get_by_path(_cache_hash);
100
2.01k
        if (config::enable_read_cache_file_directly) {
101
            // this is designed for and test in doris table, external table need extra tests
102
2.00k
            _cache_file_readers = _cache->get_blocks_by_key(_cache_hash);
103
2.00k
        }
104
2.01k
    } else {
105
        // Use path and modification time to build cache key
106
2
        std::string unique_path = fmt::format("{}:{}", path().native(), opts.mtime);
107
2
        _cache_hash = BlockFileCache::hash(unique_path);
108
2
        if (opts.cache_base_path.empty()) {
109
            // if cache path is not specified by session variable, chose randomly.
110
1
            _cache = FileCacheFactory::instance()->get_by_path(_cache_hash);
111
1
        } else {
112
            // from query session variable: file_cache_base_path
113
1
            _cache = FileCacheFactory::instance()->get_by_path(opts.cache_base_path);
114
1
            if (_cache == nullptr) {
115
1
                LOG(WARNING) << "Can't get cache from base path: " << opts.cache_base_path
116
1
                             << ", using random instead.";
117
1
                _cache = FileCacheFactory::instance()->get_by_path(_cache_hash);
118
1
            }
119
1
        }
120
2
    }
121
2.01k
}
122
123
62
void CachedRemoteFileReader::_insert_file_reader(FileBlockSPtr file_block) {
124
62
    if (_is_doris_table && config::enable_read_cache_file_directly) {
125
40
        std::lock_guard lock(_mtx);
126
40
        DCHECK(file_block->state() == FileBlock::State::DOWNLOADED);
127
40
        file_block->_owned_by_cached_reader = true;
128
40
        _cache_file_readers.emplace(file_block->offset(), std::move(file_block));
129
40
    }
130
62
}
131
132
2.01k
CachedRemoteFileReader::~CachedRemoteFileReader() {
133
2.01k
    for (auto& it : _cache_file_readers) {
134
925
        it.second->_owned_by_cached_reader = false;
135
925
    }
136
2.01k
    static_cast<void>(close());
137
2.01k
}
138
139
3.03k
Status CachedRemoteFileReader::close() {
140
3.03k
    return _remote_file_reader->close();
141
3.03k
}
142
143
std::pair<size_t, size_t> CachedRemoteFileReader::s_align_size(size_t offset, size_t read_size,
144
2.85k
                                                               size_t length) {
145
2.85k
    size_t left = offset;
146
2.85k
    size_t right = offset + read_size - 1;
147
2.85k
    size_t align_left =
148
2.85k
            (left / config::file_cache_each_block_size) * config::file_cache_each_block_size;
149
2.85k
    size_t align_right =
150
2.85k
            (right / config::file_cache_each_block_size + 1) * config::file_cache_each_block_size;
151
2.85k
    align_right = align_right < length ? align_right : length;
152
2.85k
    size_t align_size = align_right - align_left;
153
2.85k
    if (align_size < config::file_cache_each_block_size && align_left != 0) {
154
5
        align_size += config::file_cache_each_block_size;
155
5
        align_left -= config::file_cache_each_block_size;
156
5
    }
157
2.85k
    return std::make_pair(align_left, align_size);
158
2.85k
}
159
160
namespace {
161
// Execute S3 read
162
Status execute_s3_read(size_t empty_start, size_t& size, std::unique_ptr<char[]>& buffer,
163
                       ReadStatistics& stats, const IOContext* io_ctx,
164
1.83k
                       FileReaderSPtr remote_file_reader) {
165
1.83k
    s3_read_counter << 1;
166
1.83k
    SCOPED_RAW_TIMER(&stats.remote_read_timer);
167
1.83k
    stats.from_peer_cache = false;
168
1.83k
    return remote_file_reader->read_at(empty_start, Slice(buffer.get(), size), &size, io_ctx);
169
1.83k
}
170
171
// Get peer connection info from tablet_id
172
std::pair<std::string, int> get_peer_connection_info(int64_t tablet_id,
173
0
                                                     const std::string& file_path) {
174
0
    std::string host = "";
175
0
    int port = 0;
176
177
0
    DCHECK(tablet_id > 0);
178
0
    auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
179
0
    if (auto tablet_info = manager.get_balanced_tablet_info(tablet_id)) {
180
0
        host = tablet_info->first;
181
0
        port = tablet_info->second;
182
0
    } else {
183
0
        LOG_EVERY_N(WARNING, 100) << "get peer connection info not found"
184
0
                                  << ", tablet_id=" << tablet_id << ", file_path=" << file_path;
185
0
    }
186
187
0
    DBUG_EXECUTE_IF("PeerFileCacheReader::_fetch_from_peer_cache_blocks", {
188
0
        host = dp->param<std::string>("host", "127.0.0.1");
189
0
        port = dp->param("port", 9060);
190
0
        LOG_WARNING("debug point PeerFileCacheReader::_fetch_from_peer_cache_blocks")
191
0
                .tag("host", host)
192
0
                .tag("port", port);
193
0
    });
194
195
0
    return {host, port};
196
0
}
197
198
// Execute peer read with fallback to S3
199
// file_size is the size of the file
200
// used to calculate the rightmost boundary value of the block, due to inaccurate current block meta information.
201
Status execute_peer_read(const std::vector<FileBlockSPtr>& empty_blocks, size_t empty_start,
202
                         size_t& size, std::unique_ptr<char[]>& buffer,
203
                         const std::string& file_path, size_t file_size, bool is_doris_table,
204
0
                         int64_t tablet_id, ReadStatistics& stats, const IOContext* io_ctx) {
205
0
    auto [host, port] = get_peer_connection_info(tablet_id, file_path);
206
0
    VLOG_DEBUG << "PeerFileCacheReader read from peer, host=" << host << ", port=" << port
207
0
               << ", file_path=" << file_path;
208
209
0
    if (host.empty() || port == 0) {
210
0
        g_failed_get_peer_addr_counter << 1;
211
0
        VLOG_DEBUG << "PeerFileCacheReader host or port is empty"
212
0
                   << ", host=" << host << ", port=" << port << ", file_path=" << file_path;
213
0
        return Status::InternalError<false>("host or port is empty");
214
0
    }
215
0
    SCOPED_RAW_TIMER(&stats.peer_read_timer);
216
0
    peer_read_counter << 1;
217
0
    PeerFileCacheReader peer_reader(file_path, is_doris_table, host, port);
218
0
    auto st = peer_reader.fetch_blocks(empty_blocks, empty_start, Slice(buffer.get(), size), &size,
219
0
                                       file_size, io_ctx);
220
0
    if (!st.ok()) {
221
0
        VLOG_DEBUG << "PeerFileCacheReader read from peer failed"
222
0
                   << ", host=" << host << ", port=" << port << ", error=" << st.msg();
223
0
    }
224
0
    stats.from_peer_cache = true;
225
0
    return st;
226
0
}
227
228
} // anonymous namespace
229
230
Status CachedRemoteFileReader::_execute_remote_read(const std::vector<FileBlockSPtr>& empty_blocks,
231
                                                    size_t empty_start, size_t& size,
232
                                                    std::unique_ptr<char[]>& buffer,
233
                                                    ReadStatistics& stats,
234
1.83k
                                                    const IOContext* io_ctx) {
235
1.83k
    DBUG_EXECUTE_IF("CachedRemoteFileReader.read_at_impl.change_type", {
236
        // Determine read type from debug point or default to S3
237
1.83k
        std::string read_type = "s3";
238
1.83k
        read_type = dp->param<std::string>("type", "s3");
239
1.83k
        LOG_WARNING("CachedRemoteFileReader.read_at_impl.change_type")
240
1.83k
                .tag("path", path().native())
241
1.83k
                .tag("off", empty_start)
242
1.83k
                .tag("size", size)
243
1.83k
                .tag("type", read_type);
244
        // Execute appropriate read strategy
245
1.83k
        if (read_type == "s3") {
246
1.83k
            return execute_s3_read(empty_start, size, buffer, stats, io_ctx, _remote_file_reader);
247
1.83k
        } else {
248
1.83k
            return execute_peer_read(empty_blocks, empty_start, size, buffer, path().native(),
249
1.83k
                                     this->size(), _is_doris_table, _tablet_id, stats, io_ctx);
250
1.83k
        }
251
1.83k
    });
252
253
1.83k
    if (!doris::config::is_cloud_mode() || !_is_doris_table || io_ctx->is_warmup ||
254
1.83k
        !doris::config::enable_cache_read_from_peer) {
255
1.83k
        return execute_s3_read(empty_start, size, buffer, stats, io_ctx, _remote_file_reader);
256
1.83k
    } else {
257
        // first try peer read, if peer failed, fallback to S3
258
        // peer timeout is 5 seconds
259
        // TODO(dx): here peer and s3 reader need to get data in parallel, and take the one that is correct and returns first
260
        // ATTN: Save original size before peer read, as it may be modified by fetch_blocks, read peer ref size
261
0
        size_t original_size = size;
262
0
        auto st = execute_peer_read(empty_blocks, empty_start, size, buffer, path().native(),
263
0
                                    this->size(), _is_doris_table, _tablet_id, stats, io_ctx);
264
0
        if (!st.ok()) {
265
            // Restore original size for S3 fallback, as peer read may have modified it
266
0
            size = original_size;
267
            // Fallback to S3
268
0
            return execute_s3_read(empty_start, size, buffer, stats, io_ctx, _remote_file_reader);
269
0
        }
270
0
        return st;
271
0
    }
272
1.83k
}
273
274
Status CachedRemoteFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
275
10.0k
                                            const IOContext* io_ctx) {
276
10.0k
    size_t already_read = 0;
277
10.0k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().cached_remote_reader_read_at);
278
279
10.0k
    const bool is_dryrun = io_ctx->is_dryrun;
280
10.0k
    DCHECK(!closed());
281
10.0k
    DCHECK(io_ctx);
282
10.0k
    if (offset > size()) {
283
1
        return Status::InvalidArgument(
284
1
                fmt::format("offset exceeds file size(offset: {}, file size: {}, path: {})", offset,
285
1
                            size(), path().native()));
286
1
    }
287
10.0k
    size_t bytes_req = result.size;
288
10.0k
    bytes_req = std::min(bytes_req, size() - offset);
289
10.0k
    if (UNLIKELY(bytes_req == 0)) {
290
1
        *bytes_read = 0;
291
1
        return Status::OK();
292
1
    }
293
294
10.0k
    ReadStatistics stats;
295
10.0k
    stats.bytes_read += bytes_req;
296
10.0k
    MonotonicStopWatch read_at_sw;
297
10.0k
    read_at_sw.start();
298
10.0k
    auto defer_func = [&](int*) {
299
10.0k
        if (config::print_stack_when_cache_miss) {
300
0
            if (io_ctx->file_cache_stats == nullptr && !stats.hit_cache && !io_ctx->is_warmup) {
301
0
                LOG_INFO("[verbose] {}", Status::InternalError<true>("not hit cache"));
302
0
            }
303
0
        }
304
10.0k
        if (!stats.hit_cache && config::read_cluster_cache_opt_verbose_log) {
305
0
            LOG_INFO(
306
0
                    "[verbose] not hit cache, path: {}, offset: {}, size: {}, cost: {} ms, warmup: "
307
0
                    "{}",
308
0
                    path().native(), offset, bytes_req, read_at_sw.elapsed_time_milliseconds(),
309
0
                    io_ctx->is_warmup);
310
0
        }
311
10.0k
        if (is_dryrun) {
312
2
            return;
313
2
        }
314
        // update stats increment in this reading procedure for file cache metrics
315
10.0k
        FileCacheStatistics fcache_stats_increment;
316
10.0k
        _update_stats(stats, &fcache_stats_increment, io_ctx->is_inverted_index);
317
10.0k
        io::FileCacheMetrics::instance().update(&fcache_stats_increment);
318
10.0k
        if (io_ctx->file_cache_stats) {
319
            // update stats in io_ctx, for query profile
320
25
            _update_stats(stats, io_ctx->file_cache_stats, io_ctx->is_inverted_index);
321
25
        }
322
10.0k
    };
323
10.0k
    std::unique_ptr<int, decltype(defer_func)> defer((int*)0x01, std::move(defer_func));
324
10.0k
    if (_is_doris_table && config::enable_read_cache_file_directly) {
325
        // read directly
326
10.0k
        SCOPED_RAW_TIMER(&stats.read_cache_file_directly_timer);
327
10.0k
        size_t need_read_size = bytes_req;
328
10.0k
        std::shared_lock lock(_mtx);
329
10.0k
        if (!_cache_file_readers.empty()) {
330
            // find the last offset > offset.
331
8.22k
            auto iter = _cache_file_readers.upper_bound(offset);
332
8.22k
            if (iter != _cache_file_readers.begin()) {
333
8.22k
                iter--;
334
8.22k
            }
335
8.22k
            size_t cur_offset = offset;
336
16.8k
            while (need_read_size != 0 && iter != _cache_file_readers.end()) {
337
8.60k
                if (iter->second->offset() > cur_offset ||
338
8.60k
                    iter->second->range().right < cur_offset) {
339
4
                    break;
340
4
                }
341
8.60k
                size_t file_offset = cur_offset - iter->second->offset();
342
8.60k
                size_t reserve_bytes =
343
8.60k
                        std::min(need_read_size, iter->second->range().size() - file_offset);
344
8.60k
                if (is_dryrun) [[unlikely]] {
345
0
                    g_skip_local_cache_io_sum_bytes << reserve_bytes;
346
8.60k
                } else {
347
8.60k
                    SCOPED_RAW_TIMER(&stats.local_read_timer);
348
8.60k
                    if (!iter->second
349
8.60k
                                 ->read(Slice(result.data + (cur_offset - offset), reserve_bytes),
350
8.60k
                                        file_offset)
351
8.60k
                                 .ok()) { //TODO: maybe read failed because block evict, should handle error
352
6
                        break;
353
6
                    }
354
8.60k
                }
355
8.59k
                _cache->add_need_update_lru_block(iter->second);
356
8.59k
                need_read_size -= reserve_bytes;
357
8.59k
                cur_offset += reserve_bytes;
358
8.59k
                already_read += reserve_bytes;
359
8.59k
                iter++;
360
8.59k
            }
361
8.22k
            if (need_read_size == 0) {
362
8.21k
                *bytes_read = bytes_req;
363
8.21k
                stats.hit_cache = true;
364
8.21k
                g_read_cache_direct_whole_num << 1;
365
8.21k
                g_read_cache_direct_whole_bytes << bytes_req;
366
8.21k
                return Status::OK();
367
8.21k
            } else {
368
6
                g_read_cache_direct_partial_num << 1;
369
6
                g_read_cache_direct_partial_bytes << already_read;
370
6
            }
371
8.22k
        }
372
10.0k
    }
373
    // read from cache or remote
374
1.83k
    g_read_cache_indirect_num << 1;
375
1.83k
    size_t indirect_read_bytes = 0;
376
1.83k
    auto [align_left, align_size] =
377
1.83k
            s_align_size(offset + already_read, bytes_req - already_read, size());
378
1.83k
    CacheContext cache_context(io_ctx);
379
1.83k
    cache_context.stats = &stats;
380
1.83k
    cache_context.tablet_id = _tablet_id;
381
1.83k
    MonotonicStopWatch sw;
382
1.83k
    sw.start();
383
384
1.83k
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set->increment();
385
1.83k
    FileBlocksHolder holder =
386
1.83k
            _cache->get_or_set(_cache_hash, align_left, align_size, cache_context);
387
1.83k
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set->decrement();
388
389
1.83k
    stats.cache_get_or_set_timer += sw.elapsed_time();
390
1.83k
    std::vector<FileBlockSPtr> empty_blocks;
391
1.86k
    for (auto& block : holder.file_blocks) {
392
1.86k
        switch (block->state()) {
393
59
        case FileBlock::State::EMPTY:
394
59
            VLOG_DEBUG << fmt::format("Block EMPTY path={} hash={}:{}:{} offset={} cache_path={}",
395
0
                                      path().native(), _cache_hash.to_string(), _cache_hash.high(),
396
0
                                      _cache_hash.low(), block->offset(), block->get_cache_file());
397
59
            block->get_or_set_downloader();
398
59
            if (block->is_downloader()) {
399
59
                empty_blocks.push_back(block);
400
59
                TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::EMPTY");
401
59
            }
402
59
            stats.hit_cache = false;
403
59
            break;
404
1.79k
        case FileBlock::State::SKIP_CACHE:
405
1.79k
            VLOG_DEBUG << fmt::format(
406
0
                    "Block SKIP_CACHE path={} hash={}:{}:{} offset={} cache_path={}",
407
0
                    path().native(), _cache_hash.to_string(), _cache_hash.high(), _cache_hash.low(),
408
0
                    block->offset(), block->get_cache_file());
409
1.79k
            empty_blocks.push_back(block);
410
1.79k
            stats.hit_cache = false;
411
1.79k
            stats.skip_cache = true;
412
1.79k
            break;
413
2
        case FileBlock::State::DOWNLOADING:
414
2
            stats.hit_cache = false;
415
2
            break;
416
5
        case FileBlock::State::DOWNLOADED:
417
5
            _insert_file_reader(block);
418
5
            break;
419
1.86k
        }
420
1.86k
    }
421
1.83k
    size_t empty_start = 0;
422
1.83k
    size_t empty_end = 0;
423
1.83k
    if (!empty_blocks.empty()) {
424
1.83k
        empty_start = empty_blocks.front()->range().left;
425
1.83k
        empty_end = empty_blocks.back()->range().right;
426
1.83k
        size_t size = empty_end - empty_start + 1;
427
1.83k
        std::unique_ptr<char[]> buffer(new char[size]);
428
429
        // Apply rate limiting for warmup download tasks (node level)
430
        // Rate limiting is applied before remote read to limit both S3 read and local cache write
431
1.83k
        if (io_ctx->is_warmup) {
432
0
            auto* rate_limiter = ExecEnv::GetInstance()->warmup_download_rate_limiter();
433
0
            if (rate_limiter != nullptr) {
434
0
                rate_limiter->add(size);
435
0
            }
436
0
        }
437
438
        // Determine read type and execute remote read
439
1.83k
        RETURN_IF_ERROR(
440
1.83k
                _execute_remote_read(empty_blocks, empty_start, size, buffer, stats, io_ctx));
441
442
1.83k
        {
443
1.83k
            SCOPED_CONCURRENCY_COUNT(
444
1.83k
                    ConcurrencyStatsManager::instance().cached_remote_reader_write_back);
445
1.85k
            for (auto& block : empty_blocks) {
446
1.85k
                if (block->state() == FileBlock::State::SKIP_CACHE) {
447
1.79k
                    continue;
448
1.79k
                }
449
59
                SCOPED_RAW_TIMER(&stats.local_write_timer);
450
59
                char* cur_ptr = buffer.get() + block->range().left - empty_start;
451
59
                size_t block_size = block->range().size();
452
59
                Status st = block->append(Slice(cur_ptr, block_size));
453
59
                if (st.ok()) {
454
58
                    st = block->finalize();
455
58
                }
456
59
                if (!st.ok()) {
457
2
                    LOG_EVERY_N(WARNING, 100)
458
1
                            << "Write data to file cache failed. err=" << st.msg();
459
57
                } else {
460
57
                    _insert_file_reader(block);
461
57
                }
462
59
                stats.bytes_write_into_file_cache += block_size;
463
59
            }
464
1.83k
        }
465
        // copy from memory directly
466
1.83k
        size_t right_offset = offset + bytes_req - 1;
467
1.83k
        if (empty_start <= right_offset && empty_end >= offset + already_read && !is_dryrun) {
468
1.83k
            size_t copy_left_offset = std::max(offset + already_read, empty_start);
469
1.83k
            size_t copy_right_offset = std::min(right_offset, empty_end);
470
1.83k
            char* dst = result.data + (copy_left_offset - offset);
471
1.83k
            char* src = buffer.get() + (copy_left_offset - empty_start);
472
1.83k
            size_t copy_size = copy_right_offset - copy_left_offset + 1;
473
1.83k
            memcpy(dst, src, copy_size);
474
1.83k
            indirect_read_bytes += copy_size;
475
1.83k
        }
476
1.83k
    }
477
478
1.83k
    size_t current_offset = offset;
479
1.83k
    size_t end_offset = offset + bytes_req - 1;
480
1.83k
    bool need_self_heal = false;
481
1.83k
    *bytes_read = 0;
482
1.86k
    for (auto& block : holder.file_blocks) {
483
1.86k
        if (current_offset > end_offset) {
484
0
            break;
485
0
        }
486
1.86k
        size_t left = block->range().left;
487
1.86k
        size_t right = block->range().right;
488
1.86k
        if (right < offset) {
489
1
            continue;
490
1
        }
491
1.86k
        size_t read_size =
492
1.86k
                end_offset > right ? right - current_offset + 1 : end_offset - current_offset + 1;
493
1.86k
        if (empty_start <= left && right <= empty_end) {
494
1.85k
            *bytes_read += read_size;
495
1.85k
            current_offset = right + 1;
496
1.85k
            continue;
497
1.85k
        }
498
7
        FileBlock::State block_state = block->state();
499
7
        int64_t wait_time = 0;
500
7
        static int64_t max_wait_time = 10;
501
7
        TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::max_wait_time", &max_wait_time);
502
7
        if (block_state != FileBlock::State::DOWNLOADED) {
503
2
            SCOPED_CONCURRENCY_COUNT(
504
2
                    ConcurrencyStatsManager::instance().cached_remote_reader_blocking);
505
3
            do {
506
3
                SCOPED_RAW_TIMER(&stats.remote_wait_timer);
507
3
                SCOPED_RAW_TIMER(&stats.remote_read_timer);
508
3
                TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::DOWNLOADING");
509
3
                block_state = block->wait();
510
3
                if (block_state != FileBlock::State::DOWNLOADING) {
511
1
                    break;
512
1
                }
513
3
            } while (++wait_time < max_wait_time);
514
2
        }
515
7
        if (wait_time == max_wait_time) [[unlikely]] {
516
1
            LOG_WARNING("Waiting too long for the download to complete");
517
1
        }
518
7
        {
519
7
            Status st;
520
            /*
521
             * If block_state == EMPTY, the thread reads the data from remote.
522
             * If block_state == DOWNLOADED, when the cache file is deleted by the other process,
523
             * the thread reads the data from remote too.
524
             */
525
7
            if (block_state == FileBlock::State::DOWNLOADED) {
526
6
                if (is_dryrun) [[unlikely]] {
527
1
                    g_skip_local_cache_io_sum_bytes << read_size;
528
5
                } else {
529
5
                    size_t file_offset = current_offset - left;
530
5
                    SCOPED_RAW_TIMER(&stats.local_read_timer);
531
5
                    SCOPED_CONCURRENCY_COUNT(
532
5
                            ConcurrencyStatsManager::instance().cached_remote_reader_local_read);
533
5
                    st = block->read(Slice(result.data + (current_offset - offset), read_size),
534
5
                                     file_offset);
535
5
                    indirect_read_bytes += read_size;
536
5
                }
537
6
            }
538
7
            if (!st || block_state != FileBlock::State::DOWNLOADED) {
539
3
                if (is_dryrun) [[unlikely]] {
540
                    // dryrun mode uses a null buffer, skip actual remote IO
541
3
                } else {
542
3
                    if (block_state == FileBlock::State::DOWNLOADED &&
543
3
                        st.is<ErrorCode::NOT_FOUND>()) {
544
1
                        need_self_heal = true;
545
1
                        g_read_cache_self_heal_on_not_found << 1;
546
1
                        LOG_EVERY_N(WARNING, 100)
547
1
                                << "Cache block file is missing, will self-heal by clearing cache "
548
1
                                   "hash. "
549
1
                                << "path=" << path().native()
550
1
                                << ", hash=" << _cache_hash.to_string() << ", offset=" << left
551
1
                                << ", err=" << st.msg();
552
1
                    }
553
3
                    LOG(WARNING) << "Read data failed from file cache downloaded by others. err="
554
3
                                 << st.msg() << ", block state=" << block_state;
555
3
                    size_t nest_bytes_read {0};
556
3
                    stats.hit_cache = false;
557
3
                    stats.from_peer_cache = false;
558
3
                    s3_read_counter << 1;
559
3
                    SCOPED_RAW_TIMER(&stats.remote_read_timer);
560
3
                    RETURN_IF_ERROR(_remote_file_reader->read_at(
561
3
                            current_offset,
562
3
                            Slice(result.data + (current_offset - offset), read_size),
563
3
                            &nest_bytes_read));
564
2
                    indirect_read_bytes += read_size;
565
2
                    DCHECK(nest_bytes_read == read_size);
566
2
                }
567
3
            }
568
7
        }
569
6
        *bytes_read += read_size;
570
6
        current_offset = right + 1;
571
6
    }
572
1.83k
    if (need_self_heal && _cache != nullptr) {
573
1
        _cache->remove_if_cached_async(_cache_hash);
574
1
    }
575
1.83k
    g_read_cache_indirect_bytes << indirect_read_bytes;
576
1.83k
    g_read_cache_indirect_total_bytes << *bytes_read;
577
578
1.83k
    DCHECK(*bytes_read == bytes_req);
579
1.83k
    return Status::OK();
580
1.83k
}
581
582
void CachedRemoteFileReader::_update_stats(const ReadStatistics& read_stats,
583
                                           FileCacheStatistics* statis,
584
10.0k
                                           bool is_inverted_index) const {
585
10.0k
    if (statis == nullptr) {
586
0
        return;
587
0
    }
588
10.0k
    if (read_stats.hit_cache) {
589
8.22k
        statis->num_local_io_total++;
590
8.22k
        statis->bytes_read_from_local += read_stats.bytes_read;
591
8.22k
    } else {
592
1.86k
        if (read_stats.from_peer_cache) {
593
0
            statis->num_peer_io_total++;
594
0
            statis->bytes_read_from_peer += read_stats.bytes_read;
595
0
            statis->peer_io_timer += read_stats.peer_read_timer;
596
1.86k
        } else {
597
1.86k
            statis->num_remote_io_total++;
598
1.86k
            statis->bytes_read_from_remote += read_stats.bytes_read;
599
1.86k
            statis->remote_io_timer += read_stats.remote_read_timer;
600
1.86k
        }
601
1.86k
    }
602
10.0k
    statis->remote_wait_timer += read_stats.remote_wait_timer;
603
10.0k
    statis->local_io_timer += read_stats.local_read_timer;
604
10.0k
    statis->num_skip_cache_io_total += read_stats.skip_cache;
605
10.0k
    statis->bytes_write_into_cache += read_stats.bytes_write_into_file_cache;
606
10.0k
    statis->write_cache_io_timer += read_stats.local_write_timer;
607
608
10.0k
    statis->read_cache_file_directly_timer += read_stats.read_cache_file_directly_timer;
609
10.0k
    statis->cache_get_or_set_timer += read_stats.cache_get_or_set_timer;
610
10.0k
    statis->lock_wait_timer += read_stats.lock_wait_timer;
611
10.0k
    statis->get_timer += read_stats.get_timer;
612
10.0k
    statis->set_timer += read_stats.set_timer;
613
614
10.0k
    if (is_inverted_index) {
615
0
        if (read_stats.hit_cache) {
616
0
            statis->inverted_index_num_local_io_total++;
617
0
            statis->inverted_index_bytes_read_from_local += read_stats.bytes_read;
618
0
        } else {
619
0
            if (read_stats.from_peer_cache) {
620
0
                statis->inverted_index_num_peer_io_total++;
621
0
                statis->inverted_index_bytes_read_from_peer += read_stats.bytes_read;
622
0
                statis->inverted_index_peer_io_timer += read_stats.peer_read_timer;
623
0
            } else {
624
0
                statis->inverted_index_num_remote_io_total++;
625
0
                statis->inverted_index_bytes_read_from_remote += read_stats.bytes_read;
626
0
                statis->inverted_index_remote_io_timer += read_stats.remote_read_timer;
627
0
            }
628
0
        }
629
0
        statis->inverted_index_local_io_timer += read_stats.local_read_timer;
630
0
    }
631
632
10.0k
    g_skip_cache_sum << read_stats.skip_cache;
633
10.0k
}
634
635
0
void CachedRemoteFileReader::prefetch_range(size_t offset, size_t size, const IOContext* io_ctx) {
636
0
    if (offset >= this->size() || size == 0) {
637
0
        return;
638
0
    }
639
640
0
    size = std::min(size, this->size() - offset);
641
642
0
    ThreadPool* pool = ExecEnv::GetInstance()->segment_prefetch_thread_pool();
643
0
    if (pool == nullptr) {
644
0
        return;
645
0
    }
646
647
0
    IOContext dryrun_ctx;
648
0
    if (io_ctx != nullptr) {
649
0
        dryrun_ctx = *io_ctx;
650
0
    }
651
0
    dryrun_ctx.is_dryrun = true;
652
0
    dryrun_ctx.query_id = nullptr;
653
0
    dryrun_ctx.file_cache_stats = nullptr;
654
0
    dryrun_ctx.file_reader_stats = nullptr;
655
656
0
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log)
657
0
            << fmt::format("[verbose] Submitting prefetch task for offset={} size={}, file={}",
658
0
                           offset, size, path().filename().native());
659
0
    std::weak_ptr<CachedRemoteFileReader> weak_this = shared_from_this();
660
0
    auto st = pool->submit_func([weak_this, offset, size, dryrun_ctx]() {
661
0
        auto self = weak_this.lock();
662
0
        if (self == nullptr) {
663
0
            return;
664
0
        }
665
0
        size_t bytes_read;
666
0
        Slice dummy_buffer((char*)nullptr, size);
667
0
        (void)self->read_at_impl(offset, dummy_buffer, &bytes_read, &dryrun_ctx);
668
0
        LOG_IF(INFO, config::enable_segment_prefetch_verbose_log)
669
0
                << fmt::format("[verbose] Prefetch task completed for offset={} size={}, file={}",
670
0
                               offset, size, self->path().filename().native());
671
0
    });
672
673
0
    if (!st.ok()) {
674
0
        VLOG_DEBUG << "Failed to submit prefetch task for offset=" << offset << " size=" << size
675
0
                   << " error=" << st.to_string();
676
0
    }
677
0
}
678
679
} // namespace doris::io