Coverage Report

Created: 2026-05-29 11:51

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
64
void CachedRemoteFileReader::_insert_file_reader(FileBlockSPtr file_block) {
124
64
    if (_is_doris_table && config::enable_read_cache_file_directly) {
125
41
        std::lock_guard lock(_mtx);
126
41
        DCHECK(file_block->state() == FileBlock::State::DOWNLOADED);
127
41
        file_block->_owned_by_cached_reader = true;
128
41
        _cache_file_readers.emplace(file_block->offset(), std::move(file_block));
129
41
    }
130
64
}
131
132
2.02k
CachedRemoteFileReader::~CachedRemoteFileReader() {
133
2.02k
    for (auto& it : _cache_file_readers) {
134
953
        it.second->_owned_by_cached_reader = false;
135
953
    }
136
2.02k
    static_cast<void>(close());
137
2.02k
}
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.47k
                                                               size_t length) {
145
2.47k
    size_t left = offset;
146
2.47k
    size_t right = offset + read_size - 1;
147
2.47k
    size_t align_left =
148
2.47k
            (left / config::file_cache_each_block_size) * config::file_cache_each_block_size;
149
2.47k
    size_t align_right =
150
2.47k
            (right / config::file_cache_each_block_size + 1) * config::file_cache_each_block_size;
151
2.47k
    align_right = align_right < length ? align_right : length;
152
2.47k
    size_t align_size = align_right - align_left;
153
2.47k
    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.47k
    return std::make_pair(align_left, align_size);
158
2.47k
}
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.45k
                       FileReaderSPtr remote_file_reader) {
165
1.45k
    s3_read_counter << 1;
166
1.45k
    SCOPED_RAW_TIMER(&stats.remote_read_timer);
167
1.45k
    stats.from_peer_cache = false;
168
1.45k
    return remote_file_reader->read_at(empty_start, Slice(buffer.get(), size), &size, io_ctx);
169
1.45k
}
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.45k
                                                    const IOContext* io_ctx) {
235
1.45k
    DBUG_EXECUTE_IF("CachedRemoteFileReader.read_at_impl.change_type", {
236
        // Determine read type from debug point or default to S3
237
1.45k
        std::string read_type = "s3";
238
1.45k
        read_type = dp->param<std::string>("type", "s3");
239
1.45k
        LOG_WARNING("CachedRemoteFileReader.read_at_impl.change_type")
240
1.45k
                .tag("path", path().native())
241
1.45k
                .tag("off", empty_start)
242
1.45k
                .tag("size", size)
243
1.45k
                .tag("type", read_type);
244
        // Execute appropriate read strategy
245
1.45k
        if (read_type == "s3") {
246
1.45k
            return execute_s3_read(empty_start, size, buffer, stats, io_ctx, _remote_file_reader);
247
1.45k
        } else {
248
1.45k
            return execute_peer_read(empty_blocks, empty_start, size, buffer, path().native(),
249
1.45k
                                     this->size(), _is_doris_table, _tablet_id, stats, io_ctx);
250
1.45k
        }
251
1.45k
    });
252
253
1.45k
    if (!doris::config::is_cloud_mode() || !_is_doris_table || io_ctx->is_warmup ||
254
1.45k
        !doris::config::enable_cache_read_from_peer) {
255
1.45k
        return execute_s3_read(empty_start, size, buffer, stats, io_ctx, _remote_file_reader);
256
1.45k
    } 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.45k
}
273
274
Status CachedRemoteFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
275
9.87k
                                            const IOContext* io_ctx) {
276
9.87k
    size_t already_read = 0;
277
9.87k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().cached_remote_reader_read_at);
278
279
9.87k
    const IOContext default_io_ctx;
280
9.87k
    if (io_ctx == nullptr) {
281
1
        io_ctx = &default_io_ctx;
282
1
    }
283
9.87k
    DCHECK(io_ctx);
284
9.87k
    const bool is_dryrun = io_ctx->is_dryrun;
285
9.87k
    DCHECK(!closed());
286
9.87k
    if (offset > size()) {
287
1
        return Status::InvalidArgument(
288
1
                fmt::format("offset exceeds file size(offset: {}, file size: {}, path: {})", offset,
289
1
                            size(), path().native()));
290
1
    }
291
9.86k
    size_t bytes_req = result.size;
292
9.86k
    bytes_req = std::min(bytes_req, size() - offset);
293
9.86k
    if (UNLIKELY(bytes_req == 0)) {
294
1
        *bytes_read = 0;
295
1
        return Status::OK();
296
1
    }
297
298
9.86k
    ReadStatistics stats;
299
9.86k
    stats.bytes_read += bytes_req;
300
9.86k
    MonotonicStopWatch read_at_sw;
301
9.86k
    read_at_sw.start();
302
9.86k
    auto defer_func = [&](int*) {
303
9.86k
        if (config::print_stack_when_cache_miss) {
304
0
            if (io_ctx->file_cache_stats == nullptr && !stats.hit_cache && !io_ctx->is_warmup) {
305
0
                LOG_INFO("[verbose] {}", Status::InternalError<true>("not hit cache"));
306
0
            }
307
0
        }
308
9.86k
        if (!stats.hit_cache && config::read_cluster_cache_opt_verbose_log) {
309
0
            LOG_INFO(
310
0
                    "[verbose] not hit cache, path: {}, offset: {}, size: {}, cost: {} ms, warmup: "
311
0
                    "{}",
312
0
                    path().native(), offset, bytes_req, read_at_sw.elapsed_time_milliseconds(),
313
0
                    io_ctx->is_warmup);
314
0
        }
315
9.86k
        if (is_dryrun) {
316
2
            return;
317
2
        }
318
        // update stats increment in this reading procedure for file cache metrics
319
9.86k
        FileCacheStatistics fcache_stats_increment;
320
9.86k
        _update_stats(stats, &fcache_stats_increment, io_ctx->is_inverted_index);
321
9.86k
        io::FileCacheMetrics::instance().update(&fcache_stats_increment);
322
9.86k
        if (io_ctx->file_cache_stats) {
323
            // update stats in io_ctx, for query profile
324
25
            _update_stats(stats, io_ctx->file_cache_stats, io_ctx->is_inverted_index);
325
25
        }
326
9.86k
    };
327
9.86k
    std::unique_ptr<int, decltype(defer_func)> defer((int*)0x01, std::move(defer_func));
328
9.86k
    if (_is_doris_table && config::enable_read_cache_file_directly) {
329
        // read directly
330
9.85k
        SCOPED_RAW_TIMER(&stats.read_cache_file_directly_timer);
331
9.85k
        size_t need_read_size = bytes_req;
332
9.85k
        std::shared_lock lock(_mtx);
333
9.85k
        if (!_cache_file_readers.empty()) {
334
            // find the last offset > offset.
335
8.40k
            auto iter = _cache_file_readers.upper_bound(offset);
336
8.40k
            if (iter != _cache_file_readers.begin()) {
337
8.40k
                iter--;
338
8.40k
            }
339
8.40k
            size_t cur_offset = offset;
340
17.2k
            while (need_read_size != 0 && iter != _cache_file_readers.end()) {
341
8.82k
                if (iter->second->offset() > cur_offset ||
342
8.82k
                    iter->second->range().right < cur_offset) {
343
4
                    break;
344
4
                }
345
8.82k
                size_t file_offset = cur_offset - iter->second->offset();
346
8.82k
                size_t reserve_bytes =
347
8.82k
                        std::min(need_read_size, iter->second->range().size() - file_offset);
348
8.82k
                if (is_dryrun) [[unlikely]] {
349
0
                    g_skip_local_cache_io_sum_bytes << reserve_bytes;
350
8.82k
                } else {
351
8.82k
                    SCOPED_RAW_TIMER(&stats.local_read_timer);
352
8.82k
                    if (!iter->second
353
8.82k
                                 ->read(Slice(result.data + (cur_offset - offset), reserve_bytes),
354
8.82k
                                        file_offset)
355
8.82k
                                 .ok()) { //TODO: maybe read failed because block evict, should handle error
356
0
                        break;
357
0
                    }
358
8.82k
                }
359
8.82k
                _cache->add_need_update_lru_block(iter->second);
360
8.82k
                need_read_size -= reserve_bytes;
361
8.82k
                cur_offset += reserve_bytes;
362
8.82k
                already_read += reserve_bytes;
363
8.82k
                iter++;
364
8.82k
            }
365
8.40k
            if (need_read_size == 0) {
366
8.40k
                *bytes_read = bytes_req;
367
8.40k
                stats.hit_cache = true;
368
8.40k
                g_read_cache_direct_whole_num << 1;
369
8.40k
                g_read_cache_direct_whole_bytes << bytes_req;
370
8.40k
                return Status::OK();
371
8.40k
            } else {
372
0
                g_read_cache_direct_partial_num << 1;
373
0
                g_read_cache_direct_partial_bytes << already_read;
374
0
            }
375
8.40k
        }
376
9.85k
    }
377
    // read from cache or remote
378
1.46k
    g_read_cache_indirect_num << 1;
379
1.46k
    size_t indirect_read_bytes = 0;
380
1.46k
    auto [align_left, align_size] =
381
1.46k
            s_align_size(offset + already_read, bytes_req - already_read, size());
382
1.46k
    CacheContext cache_context(io_ctx);
383
1.46k
    cache_context.stats = &stats;
384
1.46k
    cache_context.tablet_id = _tablet_id;
385
1.46k
    MonotonicStopWatch sw;
386
1.46k
    sw.start();
387
388
1.46k
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set->increment();
389
1.46k
    FileBlocksHolder holder =
390
1.46k
            _cache->get_or_set(_cache_hash, align_left, align_size, cache_context);
391
1.46k
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set->decrement();
392
393
1.46k
    stats.cache_get_or_set_timer += sw.elapsed_time();
394
1.46k
    std::vector<FileBlockSPtr> empty_blocks;
395
1.48k
    for (auto& block : holder.file_blocks) {
396
1.48k
        switch (block->state()) {
397
61
        case FileBlock::State::EMPTY:
398
61
            VLOG_DEBUG << fmt::format("Block EMPTY path={} hash={}:{}:{} offset={} cache_path={}",
399
0
                                      path().native(), _cache_hash.to_string(), _cache_hash.high(),
400
0
                                      _cache_hash.low(), block->offset(), block->get_cache_file());
401
61
            block->get_or_set_downloader();
402
61
            if (block->is_downloader()) {
403
61
                empty_blocks.push_back(block);
404
61
                TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::EMPTY");
405
61
            }
406
61
            stats.hit_cache = false;
407
61
            break;
408
1.41k
        case FileBlock::State::SKIP_CACHE:
409
1.41k
            VLOG_DEBUG << fmt::format(
410
0
                    "Block SKIP_CACHE path={} hash={}:{}:{} offset={} cache_path={}",
411
0
                    path().native(), _cache_hash.to_string(), _cache_hash.high(), _cache_hash.low(),
412
0
                    block->offset(), block->get_cache_file());
413
1.41k
            empty_blocks.push_back(block);
414
1.41k
            stats.hit_cache = false;
415
1.41k
            stats.skip_cache = true;
416
1.41k
            break;
417
2
        case FileBlock::State::DOWNLOADING:
418
2
            stats.hit_cache = false;
419
2
            break;
420
5
        case FileBlock::State::DOWNLOADED:
421
5
            _insert_file_reader(block);
422
5
            break;
423
1.48k
        }
424
1.48k
    }
425
1.46k
    size_t empty_start = 0;
426
1.46k
    size_t empty_end = 0;
427
1.46k
    if (!empty_blocks.empty()) {
428
1.45k
        empty_start = empty_blocks.front()->range().left;
429
1.45k
        empty_end = empty_blocks.back()->range().right;
430
1.45k
        size_t size = empty_end - empty_start + 1;
431
1.45k
        std::unique_ptr<char[]> buffer(new char[size]);
432
433
        // Apply rate limiting for warmup download tasks (node level)
434
        // Rate limiting is applied before remote read to limit both S3 read and local cache write
435
1.45k
        if (io_ctx->is_warmup) {
436
0
            auto* rate_limiter = ExecEnv::GetInstance()->warmup_download_rate_limiter();
437
0
            if (rate_limiter != nullptr) {
438
0
                rate_limiter->add(size);
439
0
            }
440
0
        }
441
442
        // Determine read type and execute remote read
443
1.45k
        RETURN_IF_ERROR(
444
1.45k
                _execute_remote_read(empty_blocks, empty_start, size, buffer, stats, io_ctx));
445
446
1.45k
        {
447
1.45k
            SCOPED_CONCURRENCY_COUNT(
448
1.45k
                    ConcurrencyStatsManager::instance().cached_remote_reader_write_back);
449
1.47k
            for (auto& block : empty_blocks) {
450
1.47k
                if (block->state() == FileBlock::State::SKIP_CACHE) {
451
1.41k
                    continue;
452
1.41k
                }
453
61
                SCOPED_RAW_TIMER(&stats.local_write_timer);
454
61
                char* cur_ptr = buffer.get() + block->range().left - empty_start;
455
61
                size_t block_size = block->range().size();
456
61
                Status st = block->append(Slice(cur_ptr, block_size));
457
61
                if (st.ok()) {
458
60
                    st = block->finalize();
459
60
                }
460
61
                if (!st.ok()) {
461
2
                    LOG_EVERY_N(WARNING, 100)
462
1
                            << "Write data to file cache failed. err=" << st.msg();
463
59
                } else {
464
59
                    _insert_file_reader(block);
465
59
                }
466
61
                stats.bytes_write_into_file_cache += block_size;
467
61
            }
468
1.45k
        }
469
        // copy from memory directly
470
1.45k
        size_t right_offset = offset + bytes_req - 1;
471
1.45k
        if (empty_start <= right_offset && empty_end >= offset + already_read && !is_dryrun) {
472
1.45k
            size_t copy_left_offset = std::max(offset + already_read, empty_start);
473
1.45k
            size_t copy_right_offset = std::min(right_offset, empty_end);
474
1.45k
            char* dst = result.data + (copy_left_offset - offset);
475
1.45k
            char* src = buffer.get() + (copy_left_offset - empty_start);
476
1.45k
            size_t copy_size = copy_right_offset - copy_left_offset + 1;
477
1.45k
            memcpy(dst, src, copy_size);
478
1.45k
            indirect_read_bytes += copy_size;
479
1.45k
        }
480
1.45k
    }
481
482
1.46k
    size_t current_offset = offset;
483
1.46k
    size_t end_offset = offset + bytes_req - 1;
484
1.46k
    bool need_self_heal = false;
485
1.46k
    *bytes_read = 0;
486
1.48k
    for (auto& block : holder.file_blocks) {
487
1.48k
        if (current_offset > end_offset) {
488
0
            break;
489
0
        }
490
1.48k
        size_t left = block->range().left;
491
1.48k
        size_t right = block->range().right;
492
1.48k
        if (right < offset) {
493
1
            continue;
494
1
        }
495
1.48k
        size_t read_size =
496
1.48k
                end_offset > right ? right - current_offset + 1 : end_offset - current_offset + 1;
497
1.48k
        if (empty_start <= left && right <= empty_end) {
498
1.47k
            *bytes_read += read_size;
499
1.47k
            current_offset = right + 1;
500
1.47k
            continue;
501
1.47k
        }
502
7
        FileBlock::State block_state = block->state();
503
7
        int64_t wait_time = 0;
504
7
        static int64_t max_wait_time = 10;
505
7
        TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::max_wait_time", &max_wait_time);
506
7
        if (block_state != FileBlock::State::DOWNLOADED) {
507
2
            SCOPED_CONCURRENCY_COUNT(
508
2
                    ConcurrencyStatsManager::instance().cached_remote_reader_blocking);
509
3
            do {
510
3
                SCOPED_RAW_TIMER(&stats.remote_wait_timer);
511
3
                SCOPED_RAW_TIMER(&stats.remote_read_timer);
512
3
                TEST_SYNC_POINT_CALLBACK("CachedRemoteFileReader::DOWNLOADING");
513
3
                block_state = block->wait();
514
3
                if (block_state != FileBlock::State::DOWNLOADING) {
515
1
                    break;
516
1
                }
517
3
            } while (++wait_time < max_wait_time);
518
2
        }
519
7
        if (wait_time == max_wait_time) [[unlikely]] {
520
1
            LOG_WARNING("Waiting too long for the download to complete");
521
1
        }
522
7
        {
523
7
            Status st;
524
            /*
525
             * If block_state == EMPTY, the thread reads the data from remote.
526
             * If block_state == DOWNLOADED, when the cache file is deleted by the other process,
527
             * the thread reads the data from remote too.
528
             */
529
7
            if (block_state == FileBlock::State::DOWNLOADED) {
530
6
                if (is_dryrun) [[unlikely]] {
531
1
                    g_skip_local_cache_io_sum_bytes << read_size;
532
5
                } else {
533
5
                    size_t file_offset = current_offset - left;
534
5
                    SCOPED_RAW_TIMER(&stats.local_read_timer);
535
5
                    SCOPED_CONCURRENCY_COUNT(
536
5
                            ConcurrencyStatsManager::instance().cached_remote_reader_local_read);
537
5
                    st = block->read(Slice(result.data + (current_offset - offset), read_size),
538
5
                                     file_offset);
539
5
                    indirect_read_bytes += read_size;
540
5
                }
541
6
            }
542
7
            if (!st || block_state != FileBlock::State::DOWNLOADED) {
543
3
                if (is_dryrun) [[unlikely]] {
544
                    // dryrun mode uses a null buffer, skip actual remote IO
545
3
                } else {
546
3
                    if (block_state == FileBlock::State::DOWNLOADED &&
547
3
                        st.is<ErrorCode::NOT_FOUND>()) {
548
1
                        need_self_heal = true;
549
1
                        g_read_cache_self_heal_on_not_found << 1;
550
1
                        LOG_EVERY_N(WARNING, 100)
551
1
                                << "Cache block file is missing, will self-heal by clearing cache "
552
1
                                   "hash. "
553
1
                                << "path=" << path().native()
554
1
                                << ", hash=" << _cache_hash.to_string() << ", offset=" << left
555
1
                                << ", err=" << st.msg();
556
1
                    }
557
3
                    LOG(WARNING) << "Read data failed from file cache downloaded by others. err="
558
3
                                 << st.msg() << ", block state=" << block_state;
559
3
                    size_t nest_bytes_read {0};
560
3
                    stats.hit_cache = false;
561
3
                    stats.from_peer_cache = false;
562
3
                    s3_read_counter << 1;
563
3
                    SCOPED_RAW_TIMER(&stats.remote_read_timer);
564
3
                    RETURN_IF_ERROR(_remote_file_reader->read_at(
565
3
                            current_offset,
566
3
                            Slice(result.data + (current_offset - offset), read_size),
567
3
                            &nest_bytes_read));
568
2
                    indirect_read_bytes += read_size;
569
2
                    DCHECK(nest_bytes_read == read_size);
570
2
                }
571
3
            }
572
7
        }
573
6
        *bytes_read += read_size;
574
6
        current_offset = right + 1;
575
6
    }
576
1.45k
    if (need_self_heal && _cache != nullptr) {
577
1
        _cache->remove_if_cached_async(_cache_hash);
578
1
    }
579
1.45k
    g_read_cache_indirect_bytes << indirect_read_bytes;
580
1.45k
    g_read_cache_indirect_total_bytes << *bytes_read;
581
582
1.45k
    DCHECK(*bytes_read == bytes_req);
583
1.45k
    return Status::OK();
584
1.46k
}
585
586
void CachedRemoteFileReader::_update_stats(const ReadStatistics& read_stats,
587
                                           FileCacheStatistics* statis,
588
9.88k
                                           bool is_inverted_index) const {
589
9.88k
    if (statis == nullptr) {
590
0
        return;
591
0
    }
592
9.88k
    if (read_stats.hit_cache) {
593
8.40k
        statis->num_local_io_total++;
594
8.40k
        statis->bytes_read_from_local += read_stats.bytes_read;
595
8.40k
    } else {
596
1.48k
        if (read_stats.from_peer_cache) {
597
0
            statis->num_peer_io_total++;
598
0
            statis->bytes_read_from_peer += read_stats.bytes_read;
599
0
            statis->peer_io_timer += read_stats.peer_read_timer;
600
1.48k
        } else {
601
1.48k
            statis->num_remote_io_total++;
602
1.48k
            statis->bytes_read_from_remote += read_stats.bytes_read;
603
1.48k
            statis->remote_io_timer += read_stats.remote_read_timer;
604
1.48k
        }
605
1.48k
    }
606
9.88k
    statis->remote_wait_timer += read_stats.remote_wait_timer;
607
9.88k
    statis->local_io_timer += read_stats.local_read_timer;
608
9.88k
    statis->num_skip_cache_io_total += read_stats.skip_cache;
609
9.88k
    statis->bytes_write_into_cache += read_stats.bytes_write_into_file_cache;
610
9.88k
    statis->write_cache_io_timer += read_stats.local_write_timer;
611
612
9.88k
    statis->read_cache_file_directly_timer += read_stats.read_cache_file_directly_timer;
613
9.88k
    statis->cache_get_or_set_timer += read_stats.cache_get_or_set_timer;
614
9.88k
    statis->lock_wait_timer += read_stats.lock_wait_timer;
615
9.88k
    statis->get_timer += read_stats.get_timer;
616
9.88k
    statis->set_timer += read_stats.set_timer;
617
618
9.88k
    if (is_inverted_index) {
619
0
        if (read_stats.hit_cache) {
620
0
            statis->inverted_index_num_local_io_total++;
621
0
            statis->inverted_index_bytes_read_from_local += read_stats.bytes_read;
622
0
        } else {
623
0
            if (read_stats.from_peer_cache) {
624
0
                statis->inverted_index_num_peer_io_total++;
625
0
                statis->inverted_index_bytes_read_from_peer += read_stats.bytes_read;
626
0
                statis->inverted_index_peer_io_timer += read_stats.peer_read_timer;
627
0
            } else {
628
0
                statis->inverted_index_num_remote_io_total++;
629
0
                statis->inverted_index_bytes_read_from_remote += read_stats.bytes_read;
630
0
                statis->inverted_index_remote_io_timer += read_stats.remote_read_timer;
631
0
            }
632
0
        }
633
0
        statis->inverted_index_local_io_timer += read_stats.local_read_timer;
634
0
    }
635
636
9.88k
    g_skip_cache_sum << read_stats.skip_cache;
637
9.88k
}
638
639
0
void CachedRemoteFileReader::prefetch_range(size_t offset, size_t size, const IOContext* io_ctx) {
640
0
    if (offset >= this->size() || size == 0) {
641
0
        return;
642
0
    }
643
644
0
    size = std::min(size, this->size() - offset);
645
646
0
    ThreadPool* pool = ExecEnv::GetInstance()->segment_prefetch_thread_pool();
647
0
    if (pool == nullptr) {
648
0
        return;
649
0
    }
650
651
0
    IOContext dryrun_ctx;
652
0
    if (io_ctx != nullptr) {
653
0
        dryrun_ctx = *io_ctx;
654
0
    }
655
0
    dryrun_ctx.is_dryrun = true;
656
0
    dryrun_ctx.query_id = nullptr;
657
0
    dryrun_ctx.file_cache_stats = nullptr;
658
0
    dryrun_ctx.file_reader_stats = nullptr;
659
660
0
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log)
661
0
            << fmt::format("[verbose] Submitting prefetch task for offset={} size={}, file={}",
662
0
                           offset, size, path().filename().native());
663
0
    std::weak_ptr<CachedRemoteFileReader> weak_this = shared_from_this();
664
0
    auto st = pool->submit_func([weak_this, offset, size, dryrun_ctx]() {
665
0
        auto self = weak_this.lock();
666
0
        if (self == nullptr) {
667
0
            return;
668
0
        }
669
0
        size_t bytes_read;
670
0
        Slice dummy_buffer((char*)nullptr, size);
671
0
        (void)self->read_at_impl(offset, dummy_buffer, &bytes_read, &dryrun_ctx);
672
0
        LOG_IF(INFO, config::enable_segment_prefetch_verbose_log)
673
0
                << fmt::format("[verbose] Prefetch task completed for offset={} size={}, file={}",
674
0
                               offset, size, self->path().filename().native());
675
0
    });
676
677
0
    if (!st.ok()) {
678
0
        VLOG_DEBUG << "Failed to submit prefetch task for offset=" << offset << " size=" << size
679
0
                   << " error=" << st.to_string();
680
0
    }
681
0
}
682
683
} // namespace doris::io