Coverage Report

Created: 2026-03-23 15:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/buffered_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/fs/buffered_reader.h"
19
20
#include <bvar/reducer.h>
21
#include <bvar/window.h>
22
#include <string.h>
23
24
#include <algorithm>
25
#include <chrono>
26
#include <cstdint>
27
#include <memory>
28
29
#include "common/cast_set.h"
30
#include "common/compiler_util.h" // IWYU pragma: keep
31
#include "common/config.h"
32
#include "common/status.h"
33
#include "core/custom_allocator.h"
34
#include "runtime/exec_env.h"
35
#include "runtime/runtime_profile.h"
36
#include "runtime/thread_context.h"
37
#include "runtime/workload_management/io_throttle.h"
38
#include "util/slice.h"
39
#include "util/threadpool.h"
40
namespace doris {
41
42
#include "common/compile_check_begin.h"
43
44
namespace io {
45
struct IOContext;
46
47
// add bvar to capture the download bytes per second by buffered reader
48
bvar::Adder<uint64_t> g_bytes_downloaded("buffered_reader", "bytes_downloaded");
49
bvar::PerSecond<bvar::Adder<uint64_t>> g_bytes_downloaded_per_second("buffered_reader",
50
                                                                     "bytes_downloaded_per_second",
51
                                                                     &g_bytes_downloaded, 60);
52
53
Status MergeRangeFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
54
635k
                                          const IOContext* io_ctx) {
55
635k
    _statistics.request_io++;
56
635k
    *bytes_read = 0;
57
635k
    if (result.size == 0) {
58
0
        return Status::OK();
59
0
    }
60
635k
    const int range_index = _search_read_range(offset, offset + result.size);
61
635k
    if (range_index < 0) {
62
0
        SCOPED_RAW_TIMER(&_statistics.read_time);
63
0
        Status st = _reader->read_at(offset, result, bytes_read, io_ctx);
64
0
        _statistics.merged_io++;
65
0
        _statistics.request_bytes += *bytes_read;
66
0
        _statistics.merged_bytes += *bytes_read;
67
0
        return st;
68
0
    }
69
635k
    if (offset + result.size > _random_access_ranges[range_index].end_offset) {
70
        // return _reader->read_at(offset, result, bytes_read, io_ctx);
71
0
        return Status::IOError("Range in RandomAccessReader should be read sequentially");
72
0
    }
73
74
635k
    size_t has_read = 0;
75
635k
    RangeCachedData& cached_data = _range_cached_data[range_index];
76
635k
    cached_data.has_read = true;
77
635k
    if (cached_data.contains(offset)) {
78
        // has cached data in box
79
629k
        _read_in_box(cached_data, offset, result, &has_read);
80
629k
        _statistics.request_bytes += has_read;
81
629k
        if (has_read == result.size) {
82
            // all data is read in cache
83
629k
            *bytes_read = has_read;
84
629k
            return Status::OK();
85
629k
        }
86
629k
    } else if (!cached_data.empty()) {
87
        // the data in range may be skipped or ignored
88
10
        for (int16_t box_index : cached_data.ref_box) {
89
10
            _dec_box_ref(box_index);
90
10
        }
91
10
        cached_data.reset();
92
10
    }
93
94
5.86k
    size_t to_read = result.size - has_read;
95
5.87k
    if (to_read >= SMALL_IO || to_read >= _remaining) {
96
0
        SCOPED_RAW_TIMER(&_statistics.read_time);
97
0
        size_t read_size = 0;
98
0
        RETURN_IF_ERROR(_reader->read_at(offset + has_read, Slice(result.data + has_read, to_read),
99
0
                                         &read_size, io_ctx));
100
0
        *bytes_read = has_read + read_size;
101
0
        _statistics.merged_io++;
102
0
        _statistics.request_bytes += read_size;
103
0
        _statistics.merged_bytes += read_size;
104
0
        return Status::OK();
105
0
    }
106
107
    // merge small IO
108
5.86k
    size_t merge_start = offset + has_read;
109
5.86k
    const size_t merge_end = merge_start + _merged_read_slice_size;
110
    // <slice_size, is_content>
111
5.86k
    std::vector<std::pair<size_t, bool>> merged_slice;
112
5.86k
    size_t content_size = 0;
113
5.86k
    size_t hollow_size = 0;
114
5.86k
    if (merge_start > _random_access_ranges[range_index].end_offset) {
115
0
        return Status::IOError("Fail to merge small IO");
116
0
    }
117
5.86k
    int merge_index = range_index;
118
52.6k
    while (merge_start < merge_end && merge_index < _random_access_ranges.size()) {
119
47.2k
        size_t content_max = _remaining - content_size;
120
47.2k
        if (content_max == 0) {
121
0
            break;
122
0
        }
123
47.2k
        if (merge_index != range_index && _range_cached_data[merge_index].has_read) {
124
            // don't read or merge twice
125
0
            break;
126
0
        }
127
47.2k
        if (_random_access_ranges[merge_index].end_offset > merge_end) {
128
129
            size_t add_content = std::min(merge_end - merge_start, content_max);
129
129
            content_size += add_content;
130
129
            merge_start += add_content;
131
129
            merged_slice.emplace_back(add_content, true);
132
129
            break;
133
129
        }
134
47.1k
        size_t add_content =
135
47.1k
                std::min(_random_access_ranges[merge_index].end_offset - merge_start, content_max);
136
47.1k
        content_size += add_content;
137
47.1k
        merge_start += add_content;
138
47.1k
        merged_slice.emplace_back(add_content, true);
139
47.1k
        if (merge_start != _random_access_ranges[merge_index].end_offset) {
140
0
            break;
141
0
        }
142
47.1k
        if (merge_index < _random_access_ranges.size() - 1 && merge_start < merge_end) {
143
41.7k
            size_t gap = _random_access_ranges[merge_index + 1].start_offset -
144
41.7k
                         _random_access_ranges[merge_index].end_offset;
145
41.7k
            if ((content_size + hollow_size) > SMALL_IO && gap >= SMALL_IO) {
146
                // too large gap
147
0
                break;
148
0
            }
149
41.7k
            if (gap < merge_end - merge_start && content_size < _remaining &&
150
41.7k
                !_range_cached_data[merge_index + 1].has_read) {
151
41.4k
                hollow_size += gap;
152
41.4k
                merge_start = _random_access_ranges[merge_index + 1].start_offset;
153
41.4k
                merged_slice.emplace_back(gap, false);
154
41.4k
            } else {
155
                // there's no enough memory to read hollow data
156
347
                break;
157
347
            }
158
41.7k
        }
159
46.8k
        merge_index++;
160
46.8k
    }
161
5.86k
    content_size = 0;
162
5.86k
    hollow_size = 0;
163
5.86k
    std::vector<std::pair<double, size_t>> ratio_and_size;
164
    // Calculate the read amplified ratio for each merge operation and the size of the merged data.
165
    // Find the largest size of the merged data whose amplified ratio is less than config::max_amplified_read_ratio
166
88.6k
    for (const std::pair<size_t, bool>& slice : merged_slice) {
167
88.6k
        if (slice.second) {
168
47.2k
            content_size += slice.first;
169
47.2k
            if (slice.first > 0) {
170
47.2k
                ratio_and_size.emplace_back((double)hollow_size / (double)content_size,
171
47.2k
                                            content_size + hollow_size);
172
47.2k
            }
173
47.2k
        } else {
174
41.4k
            hollow_size += slice.first;
175
41.4k
        }
176
88.6k
    }
177
5.86k
    size_t best_merged_size = 0;
178
53.1k
    for (int i = 0; i < ratio_and_size.size(); ++i) {
179
47.2k
        const std::pair<double, size_t>& rs = ratio_and_size[i];
180
47.2k
        size_t equivalent_size = rs.second / (i + 1);
181
47.2k
        if (rs.second > best_merged_size) {
182
47.2k
            if (rs.first <= _max_amplified_ratio ||
183
47.2k
                (_max_amplified_ratio < 1 && equivalent_size <= _equivalent_io_size)) {
184
47.1k
                best_merged_size = rs.second;
185
47.1k
            }
186
47.2k
        }
187
47.2k
    }
188
189
5.86k
    if (best_merged_size == to_read) {
190
        // read directly to avoid copy operation
191
1.17k
        SCOPED_RAW_TIMER(&_statistics.read_time);
192
1.17k
        size_t read_size = 0;
193
1.17k
        RETURN_IF_ERROR(_reader->read_at(offset + has_read, Slice(result.data + has_read, to_read),
194
1.17k
                                         &read_size, io_ctx));
195
1.17k
        *bytes_read = has_read + read_size;
196
1.17k
        _statistics.merged_io++;
197
1.17k
        _statistics.request_bytes += read_size;
198
1.17k
        _statistics.merged_bytes += read_size;
199
1.17k
        return Status::OK();
200
1.17k
    }
201
202
4.69k
    merge_start = offset + has_read;
203
4.69k
    size_t merge_read_size = 0;
204
4.69k
    RETURN_IF_ERROR(
205
4.69k
            _fill_box(range_index, merge_start, best_merged_size, &merge_read_size, io_ctx));
206
4.69k
    if (cached_data.start_offset != merge_start) {
207
0
        return Status::IOError("Wrong start offset in merged IO");
208
0
    }
209
210
    // read from cached data
211
4.69k
    size_t box_read_size = 0;
212
4.69k
    _read_in_box(cached_data, merge_start, Slice(result.data + has_read, to_read), &box_read_size);
213
4.69k
    *bytes_read = has_read + box_read_size;
214
4.69k
    _statistics.request_bytes += box_read_size;
215
4.69k
    if (*bytes_read < result.size && box_read_size < merge_read_size) {
216
0
        return Status::IOError("Can't read enough bytes in merged IO");
217
0
    }
218
4.69k
    return Status::OK();
219
4.69k
}
220
221
635k
int MergeRangeFileReader::_search_read_range(size_t start_offset, size_t end_offset) {
222
635k
    if (_random_access_ranges.empty()) {
223
0
        return -1;
224
0
    }
225
635k
    int left = 0, right = cast_set<int>(_random_access_ranges.size()) - 1;
226
1.75M
    do {
227
1.75M
        int mid = left + (right - left) / 2;
228
1.75M
        const PrefetchRange& range = _random_access_ranges[mid];
229
1.75M
        if (range.start_offset <= start_offset && start_offset < range.end_offset) {
230
635k
            if (range.start_offset <= end_offset && end_offset <= range.end_offset) {
231
635k
                return mid;
232
635k
            } else {
233
2
                return -1;
234
2
            }
235
1.12M
        } else if (range.start_offset > start_offset) {
236
363k
            right = mid - 1;
237
756k
        } else {
238
756k
            left = mid + 1;
239
756k
        }
240
1.75M
    } while (left <= right);
241
18.4E
    return -1;
242
635k
}
243
244
41.2k
void MergeRangeFileReader::_clean_cached_data(RangeCachedData& cached_data) {
245
41.2k
    if (!cached_data.empty()) {
246
0
        for (int i = 0; i < cached_data.ref_box.size(); ++i) {
247
0
            DCHECK_GT(cached_data.box_end_offset[i], cached_data.box_start_offset[i]);
248
0
            int16_t box_index = cached_data.ref_box[i];
249
0
            DCHECK_GT(_box_ref[box_index], 0);
250
0
            _box_ref[box_index]--;
251
0
        }
252
0
    }
253
41.2k
    cached_data.reset();
254
41.2k
}
255
256
43.1k
void MergeRangeFileReader::_dec_box_ref(int16_t box_index) {
257
43.1k
    if (--_box_ref[box_index] == 0) {
258
5.44k
        _remaining += BOX_SIZE;
259
5.44k
    }
260
43.1k
    if (box_index == _last_box_ref) {
261
3.97k
        _last_box_ref = -1;
262
3.97k
        _last_box_usage = 0;
263
3.97k
    }
264
43.1k
}
265
266
void MergeRangeFileReader::_read_in_box(RangeCachedData& cached_data, size_t offset, Slice result,
267
634k
                                        size_t* bytes_read) {
268
634k
    SCOPED_RAW_TIMER(&_statistics.copy_time);
269
642k
    auto handle_in_box = [&](size_t remaining, char* copy_out) {
270
642k
        size_t to_handle = remaining;
271
642k
        int cleaned_box = 0;
272
1.28M
        for (int i = 0; i < cached_data.ref_box.size() && remaining > 0; ++i) {
273
644k
            int16_t box_index = cached_data.ref_box[i];
274
644k
            size_t box_to_handle = std::min(remaining, (size_t)(cached_data.box_end_offset[i] -
275
644k
                                                                cached_data.box_start_offset[i]));
276
644k
            if (copy_out != nullptr) {
277
636k
            }
278
644k
            if (copy_out != nullptr) {
279
636k
                memcpy(copy_out + to_handle - remaining,
280
636k
                       _boxes[box_index].data() + cached_data.box_start_offset[i], box_to_handle);
281
636k
            }
282
644k
            remaining -= box_to_handle;
283
644k
            cached_data.box_start_offset[i] += box_to_handle;
284
644k
            if (cached_data.box_start_offset[i] == cached_data.box_end_offset[i]) {
285
43.1k
                cleaned_box++;
286
43.1k
                _dec_box_ref(box_index);
287
43.1k
            }
288
644k
        }
289
642k
        DCHECK_EQ(remaining, 0);
290
642k
        if (cleaned_box > 0) {
291
43.0k
            cached_data.ref_box.erase(cached_data.ref_box.begin(),
292
43.0k
                                      cached_data.ref_box.begin() + cleaned_box);
293
43.0k
            cached_data.box_start_offset.erase(cached_data.box_start_offset.begin(),
294
43.0k
                                               cached_data.box_start_offset.begin() + cleaned_box);
295
43.0k
            cached_data.box_end_offset.erase(cached_data.box_end_offset.begin(),
296
43.0k
                                             cached_data.box_end_offset.begin() + cleaned_box);
297
43.0k
        }
298
642k
        cached_data.start_offset += to_handle;
299
642k
        if (cached_data.start_offset == cached_data.end_offset) {
300
41.2k
            _clean_cached_data(cached_data);
301
41.2k
        }
302
642k
    };
303
304
634k
    if (offset > cached_data.start_offset) {
305
        // the data in range may be skipped
306
7.88k
        size_t to_skip = offset - cached_data.start_offset;
307
7.88k
        handle_in_box(to_skip, nullptr);
308
7.88k
    }
309
310
634k
    size_t to_read = std::min(cached_data.end_offset - cached_data.start_offset, result.size);
311
634k
    handle_in_box(to_read, result.data);
312
634k
    *bytes_read = to_read;
313
634k
}
314
315
Status MergeRangeFileReader::_fill_box(int range_index, size_t start_offset, size_t to_read,
316
4.69k
                                       size_t* bytes_read, const IOContext* io_ctx) {
317
4.69k
    if (!_read_slice) {
318
4.15k
        _read_slice = std::make_unique<OwnedSlice>(_merged_read_slice_size);
319
4.15k
    }
320
321
4.69k
    *bytes_read = 0;
322
4.69k
    {
323
4.69k
        SCOPED_RAW_TIMER(&_statistics.read_time);
324
4.69k
        RETURN_IF_ERROR(_reader->read_at(start_offset, Slice(_read_slice->data(), to_read),
325
4.69k
                                         bytes_read, io_ctx));
326
4.69k
        _statistics.merged_io++;
327
4.69k
        _statistics.merged_bytes += *bytes_read;
328
4.69k
    }
329
330
4.69k
    SCOPED_RAW_TIMER(&_statistics.copy_time);
331
4.69k
    size_t copy_start = start_offset;
332
4.69k
    const size_t copy_end = start_offset + *bytes_read;
333
    // copy data into small boxes
334
    // tuple(box_index, box_start_offset, file_start_offset, file_end_offset)
335
4.69k
    std::vector<std::tuple<int16_t, uint32_t, size_t, size_t>> filled_boxes;
336
337
48.5k
    auto fill_box = [&](int16_t fill_box_ref, uint32_t box_usage, size_t box_copy_end) {
338
48.5k
        size_t copy_size = std::min(box_copy_end - copy_start, BOX_SIZE - box_usage);
339
48.5k
        memcpy(_boxes[fill_box_ref].data() + box_usage,
340
48.5k
               _read_slice->data() + copy_start - start_offset, copy_size);
341
48.5k
        filled_boxes.emplace_back(fill_box_ref, box_usage, copy_start, copy_start + copy_size);
342
48.5k
        copy_start += copy_size;
343
48.5k
        _last_box_ref = fill_box_ref;
344
48.5k
        _last_box_usage = box_usage + cast_set<int>(copy_size);
345
48.5k
        _box_ref[fill_box_ref]++;
346
48.5k
        if (box_usage == 0) {
347
6.91k
            _remaining -= BOX_SIZE;
348
6.91k
        }
349
48.5k
    };
350
351
4.69k
    for (int fill_range_index = range_index;
352
50.7k
         fill_range_index < _random_access_ranges.size() && copy_start < copy_end;
353
46.0k
         ++fill_range_index) {
354
46.0k
        RangeCachedData& fill_range_cache = _range_cached_data[fill_range_index];
355
46.0k
        DCHECK(fill_range_cache.empty());
356
46.0k
        fill_range_cache.reset();
357
46.0k
        const PrefetchRange& fill_range = _random_access_ranges[fill_range_index];
358
46.0k
        if (fill_range.start_offset > copy_start) {
359
            // don't copy hollow data
360
21.2k
            size_t hollow_size = fill_range.start_offset - copy_start;
361
21.2k
            DCHECK_GT(copy_end - copy_start, hollow_size);
362
21.2k
            copy_start += hollow_size;
363
21.2k
        }
364
365
46.0k
        const size_t range_copy_end = std::min(copy_end, fill_range.end_offset);
366
        // reuse the remaining capacity of last box
367
46.0k
        if (_last_box_ref >= 0 && _last_box_usage < BOX_SIZE) {
368
41.6k
            fill_box(_last_box_ref, _last_box_usage, range_copy_end);
369
41.6k
        }
370
        // reuse the former released box
371
55.4k
        for (int16_t i = 0; i < _boxes.size() && copy_start < range_copy_end; ++i) {
372
9.40k
            if (_box_ref[i] == 0) {
373
168
                fill_box(i, 0, range_copy_end);
374
168
            }
375
9.40k
        }
376
        // apply for new box to copy data
377
52.7k
        while (copy_start < range_copy_end && _boxes.size() < NUM_BOX) {
378
6.75k
            _boxes.emplace_back(BOX_SIZE);
379
6.75k
            _box_ref.emplace_back(0);
380
6.75k
            fill_box(cast_set<int16_t>(_boxes.size()) - 1, 0, range_copy_end);
381
6.75k
        }
382
46.0k
        DCHECK_EQ(copy_start, range_copy_end);
383
384
46.0k
        if (!filled_boxes.empty()) {
385
46.0k
            fill_range_cache.start_offset = std::get<2>(filled_boxes[0]);
386
46.0k
            fill_range_cache.end_offset = std::get<3>(filled_boxes.back());
387
48.5k
            for (auto& tuple : filled_boxes) {
388
48.5k
                fill_range_cache.ref_box.emplace_back(std::get<0>(tuple));
389
48.5k
                fill_range_cache.box_start_offset.emplace_back(std::get<1>(tuple));
390
48.5k
                fill_range_cache.box_end_offset.emplace_back(
391
48.5k
                        std::get<1>(tuple) + std::get<3>(tuple) - std::get<2>(tuple));
392
48.5k
            }
393
46.0k
            filled_boxes.clear();
394
46.0k
        }
395
46.0k
    }
396
4.69k
    return Status::OK();
397
4.69k
}
398
399
// there exists occasions where the buffer is already closed but
400
// some prior tasks are still queued in thread pool, so we have to check whether
401
// the buffer is closed each time the condition variable is notified.
402
375
void PrefetchBuffer::reset_offset(size_t offset) {
403
375
    {
404
375
        std::unique_lock lck {_lock};
405
375
        if (!_prefetched.wait_for(
406
375
                    lck, std::chrono::milliseconds(config::buffered_reader_read_timeout_ms),
407
375
                    [this]() { return _buffer_status != BufferStatus::PENDING; })) {
408
0
            _prefetch_status = Status::TimedOut("time out when reset prefetch buffer");
409
0
            return;
410
0
        }
411
375
        if (UNLIKELY(_buffer_status == BufferStatus::CLOSED)) {
412
0
            _prefetched.notify_all();
413
0
            return;
414
0
        }
415
375
        _buffer_status = BufferStatus::RESET;
416
375
        _offset = offset;
417
375
        _prefetched.notify_all();
418
375
    }
419
375
    if (UNLIKELY(offset >= _file_range.end_offset)) {
420
199
        _len = 0;
421
199
        _exceed = true;
422
199
        return;
423
199
    } else {
424
176
        _exceed = false;
425
176
    }
426
176
    _prefetch_status = ExecEnv::GetInstance()->buffered_reader_prefetch_thread_pool()->submit_func(
427
176
            [buffer_ptr = shared_from_this()]() { buffer_ptr->prefetch_buffer(); });
428
176
}
429
430
// only this function would run concurrently in another thread
431
172
void PrefetchBuffer::prefetch_buffer() {
432
172
    {
433
172
        std::unique_lock lck {_lock};
434
172
        if (!_prefetched.wait_for(
435
172
                    lck, std::chrono::milliseconds(config::buffered_reader_read_timeout_ms),
436
176
                    [this]() {
437
176
                        return _buffer_status == BufferStatus::RESET ||
438
176
                               _buffer_status == BufferStatus::CLOSED;
439
176
                    })) {
440
0
            _prefetch_status = Status::TimedOut("time out when invoking prefetch buffer");
441
0
            return;
442
0
        }
443
        // in case buffer is already closed
444
172
        if (UNLIKELY(_buffer_status == BufferStatus::CLOSED)) {
445
0
            _prefetched.notify_all();
446
0
            return;
447
0
        }
448
172
        _buffer_status = BufferStatus::PENDING;
449
172
        _prefetched.notify_all();
450
172
    }
451
452
0
    // Lazy-allocate the backing buffer on first actual prefetch, avoiding the cost of
453
172
    // pre-allocating memory for readers that are initialized but never read (e.g. when
454
172
    // many file readers are created concurrently for a TVF scan over many small S3 files).
455
172
    if (!_buf) {
456
172
        _buf = std::make_unique<char[]>(_size);
457
172
    }
458
0
459
0
    int read_range_index = search_read_range(_offset);
460
    size_t buf_size;
461
172
    if (read_range_index == -1) {
462
172
        buf_size =
463
                _file_range.end_offset - _offset > _size ? _size : _file_range.end_offset - _offset;
464
172
    } else {
465
172
        buf_size = merge_small_ranges(_offset, read_range_index);
466
172
    }
467
172
468
172
    _len = 0;
469
    Status s;
470
471
    {
472
0
        SCOPED_RAW_TIMER(&_statis.read_time);
473
0
        s = _reader->read_at(_offset, Slice {_buf.get(), buf_size}, &_len, _io_ctx);
474
0
    }
475
0
    if (UNLIKELY(s.ok() && buf_size != _len)) {
476
172
        // This indicates that the data size returned by S3 object storage is smaller than what we requested,
477
172
        // which seems to be a violation of the S3 protocol since our request range was valid.
478
172
        // We currently consider this situation a bug and will treat this task as a failure.
479
172
        s = Status::InternalError("Data size returned by S3 is smaller than requested");
480
172
        LOG(WARNING) << "Data size returned by S3 is smaller than requested" << _reader->path()
481
172
                     << " request bytes " << buf_size << " returned size " << _len;
482
176
    }
483
0
    g_bytes_downloaded << _len;
484
0
    _statis.prefetch_request_io += 1;
485
0
    _statis.prefetch_request_bytes += _len;
486
172
    std::unique_lock lck {_lock};
487
    if (!_prefetched.wait_for(lck,
488
                              std::chrono::milliseconds(config::buffered_reader_read_timeout_ms),
489
0
                              [this]() { return _buffer_status == BufferStatus::PENDING; })) {
490
0
        _prefetch_status = Status::TimedOut("time out when invoking prefetch buffer");
491
0
        return;
492
0
    }
493
172
    if (!s.ok() && _offset < _reader->size()) {
494
172
        // We should print the error msg since this buffer might not be accessed by the consumer
495
        // which would result in the status being missed
496
172
        LOG_WARNING("prefetch path {} failed, offset {}, error {}", _reader->path().native(),
497
                    _offset, s.to_string());
498
176
        _prefetch_status = std::move(s);
499
176
    }
500
176
    _buffer_status = BufferStatus::PREFETCHED;
501
176
    _prefetched.notify_all();
502
0
    // eof would come up with len == 0, it would be handled by read_buffer
503
0
}
504
0
505
0
int PrefetchBuffer::search_read_range(size_t off) const {
506
0
    if (_random_access_ranges == nullptr || _random_access_ranges->empty()) {
507
0
        return -1;
508
0
    }
509
0
    const std::vector<PrefetchRange>& random_access_ranges = *_random_access_ranges;
510
0
    int left = 0, right = cast_set<int>(random_access_ranges.size()) - 1;
511
0
    do {
512
0
        int mid = left + (right - left) / 2;
513
0
        const PrefetchRange& range = random_access_ranges[mid];
514
0
        if (range.start_offset <= off && range.end_offset > off) {
515
0
            return mid;
516
0
        } else if (range.start_offset > off) {
517
0
            right = mid;
518
0
        } else {
519
0
            left = mid + 1;
520
0
        }
521
    } while (left < right);
522
0
    if (random_access_ranges[right].start_offset > off) {
523
0
        return right;
524
0
    } else {
525
0
        return -1;
526
0
    }
527
0
}
528
0
529
0
size_t PrefetchBuffer::merge_small_ranges(size_t off, int range_index) const {
530
0
    if (_random_access_ranges == nullptr || _random_access_ranges->empty()) {
531
0
        return _size;
532
0
    }
533
0
    int64_t remaining = _size;
534
0
    const std::vector<PrefetchRange>& random_access_ranges = *_random_access_ranges;
535
    while (remaining > 0 && range_index < random_access_ranges.size()) {
536
0
        const PrefetchRange& range = random_access_ranges[range_index];
537
0
        if (range.start_offset <= off && range.end_offset > off) {
538
0
            remaining -= range.end_offset - off;
539
0
            off = range.end_offset;
540
0
            range_index++;
541
0
        } else if (range.start_offset > off) {
542
0
            // merge small range
543
0
            size_t hollow = range.start_offset - off;
544
0
            if (hollow < remaining) {
545
0
                remaining -= hollow;
546
0
                off = range.start_offset;
547
0
            } else {
548
0
                break;
549
0
            }
550
0
        } else {
551
0
            DCHECK(false);
552
        }
553
    }
554
251
    if (remaining < 0 || remaining == _size) {
555
251
        remaining = 0;
556
    }
557
0
    return _size - remaining;
558
0
}
559
251
560
0
Status PrefetchBuffer::read_buffer(size_t off, const char* out, size_t buf_len,
561
0
                                   size_t* bytes_read) {
562
0
    if (UNLIKELY(off >= _file_range.end_offset)) {
563
251
        // Reader can read out of [start_offset, end_offset) by synchronous method.
564
        return _reader->read_at(off, Slice {out, buf_len}, bytes_read, _io_ctx);
565
    }
566
251
    if (_exceed) {
567
251
        reset_offset((off / _size) * _size);
568
251
        return read_buffer(off, out, buf_len, bytes_read);
569
    }
570
251
    auto start = std::chrono::steady_clock::now();
571
251
    // The baseline time is calculated by dividing the size of each buffer by MB/s.
572
347
    // If it exceeds this value, it is considered a slow I/O operation.
573
347
    constexpr auto read_time_baseline = std::chrono::seconds(s_max_pre_buffer_size / 1024 / 1024);
574
347
    {
575
347
        std::unique_lock lck {_lock};
576
0
        // buffer must be prefetched or it's closed
577
0
        if (!_prefetched.wait_for(
578
0
                    lck, std::chrono::milliseconds(config::buffered_reader_read_timeout_ms),
579
251
                    [this]() {
580
0
                        return _buffer_status == BufferStatus::PREFETCHED ||
581
0
                               _buffer_status == BufferStatus::CLOSED;
582
251
                    })) {
583
251
            _prefetch_status = Status::TimedOut("time out when read prefetch buffer");
584
251
            return _prefetch_status;
585
251
        }
586
0
        if (UNLIKELY(BufferStatus::CLOSED == _buffer_status)) {
587
0
            return Status::OK();
588
251
        }
589
    }
590
    auto duration = std::chrono::duration_cast<std::chrono::seconds>(
591
251
            std::chrono::steady_clock::now() - start);
592
0
    if (duration > read_time_baseline) [[unlikely]] {
593
0
        LOG_WARNING("The prefetch io is too slow");
594
0
    }
595
251
    RETURN_IF_ERROR(_prefetch_status);
596
0
    // there is only parquet would do not sequence read
597
0
    // it would read the end of the file first
598
    if (UNLIKELY(!contains(off))) {
599
251
        reset_offset((off / _size) * _size);
600
251
        return read_buffer(off, out, buf_len, bytes_read);
601
    }
602
251
    if (UNLIKELY(0 == _len || _offset + _len < off)) {
603
251
        return Status::OK();
604
251
    }
605
251
606
251
    {
607
251
        LIMIT_REMOTE_SCAN_IO(bytes_read);
608
251
        // [0]: maximum len trying to read, [1] maximum length buffer can provide, [2] actual len buffer has
609
251
        size_t read_len = std::min({buf_len, _offset + _size - off, _offset + _len - off});
610
251
        {
611
251
            SCOPED_RAW_TIMER(&_statis.copy_time);
612
135
            memcpy((void*)out, _buf.get() + (off - _offset), read_len);
613
135
        }
614
251
        *bytes_read = read_len;
615
251
        _statis.request_io += 1;
616
        _statis.request_bytes += read_len;
617
240
    }
618
240
    if (off + *bytes_read == _offset + _len) {
619
        reset_offset(_offset + _whole_buffer_size);
620
240
    }
621
240
    return Status::OK();
622
242
}
623
0
624
0
void PrefetchBuffer::close() {
625
0
    std::unique_lock lck {_lock};
626
240
    // in case _reader still tries to write to the buf after we close the buffer
627
240
    if (!_prefetched.wait_for(lck,
628
240
                              std::chrono::milliseconds(config::buffered_reader_read_timeout_ms),
629
                              [this]() { return _buffer_status != BufferStatus::PENDING; })) {
630
72
        _prefetch_status = Status::TimedOut("time out when close prefetch buffer");
631
72
        return;
632
72
    }
633
72
    _buffer_status = BufferStatus::CLOSED;
634
72
    _prefetched.notify_all();
635
}
636
637
void PrefetchBuffer::_collect_profile_before_close() {
638
    if (_sync_profile != nullptr) {
639
        _sync_profile(*this);
640
    }
641
60
}
642
60
643
4
// buffered reader
644
4
PrefetchBufferedReader::PrefetchBufferedReader(RuntimeProfile* profile, io::FileReaderSPtr reader,
645
60
                                               PrefetchRange file_range,
646
60
                                               std::shared_ptr<const IOContext> io_ctx,
647
60
                                               int64_t buffer_size)
648
60
        : _reader(std::move(reader)), _file_range(file_range), _io_ctx_holder(std::move(io_ctx)) {
649
60
    if (_io_ctx_holder == nullptr) {
650
60
        _io_ctx_holder = std::make_shared<IOContext>();
651
60
    }
652
60
    _io_ctx = _io_ctx_holder.get();
653
60
    if (buffer_size == -1L) {
654
60
        buffer_size = config::remote_storage_read_buffer_mb * 1024 * 1024;
655
60
    }
656
60
    _size = _reader->size();
657
56
    _whole_pre_buffer_size = buffer_size;
658
56
    _file_range.end_offset = std::min(_file_range.end_offset, _size);
659
56
    int buffer_num = buffer_size > s_max_pre_buffer_size
660
56
                             ? cast_set<int>(buffer_size) / cast_set<int>(s_max_pre_buffer_size)
661
56
                             : 1;
662
56
    std::function<void(PrefetchBuffer&)> sync_buffer = nullptr;
663
56
    if (profile != nullptr) {
664
56
        const char* prefetch_buffered_reader = "PrefetchBufferedReader";
665
56
        ADD_TIMER(profile, prefetch_buffered_reader);
666
56
        auto copy_time = ADD_CHILD_TIMER(profile, "CopyTime", prefetch_buffered_reader);
667
56
        auto read_time = ADD_CHILD_TIMER(profile, "ReadTime", prefetch_buffered_reader);
668
56
        auto prefetch_request_io =
669
72
                ADD_CHILD_COUNTER(profile, "PreRequestIO", TUnit::UNIT, prefetch_buffered_reader);
670
72
        auto prefetch_request_bytes = ADD_CHILD_COUNTER(profile, "PreRequestBytes", TUnit::BYTES,
671
72
                                                        prefetch_buffered_reader);
672
72
        auto request_io =
673
72
                ADD_CHILD_COUNTER(profile, "RequestIO", TUnit::UNIT, prefetch_buffered_reader);
674
72
        auto request_bytes =
675
72
                ADD_CHILD_COUNTER(profile, "RequestBytes", TUnit::BYTES, prefetch_buffered_reader);
676
72
        sync_buffer = [=](PrefetchBuffer& buf) {
677
56
            COUNTER_UPDATE(copy_time, buf._statis.copy_time);
678
            COUNTER_UPDATE(read_time, buf._statis.read_time);
679
            COUNTER_UPDATE(prefetch_request_io, buf._statis.prefetch_request_io);
680
300
            COUNTER_UPDATE(prefetch_request_bytes, buf._statis.prefetch_request_bytes);
681
240
            COUNTER_UPDATE(request_io, buf._statis.request_io);
682
240
            COUNTER_UPDATE(request_bytes, buf._statis.request_bytes);
683
240
        };
684
240
    }
685
60
    // set the _cur_offset of this reader as same as the inner reader's,
686
    // to make sure the buffer reader will start to read at right position.
687
60
    for (int i = 0; i < buffer_num; i++) {
688
        _pre_buffers.emplace_back(std::make_shared<PrefetchBuffer>(
689
60
                _file_range, s_max_pre_buffer_size, _whole_pre_buffer_size, _reader.get(),
690
60
                _io_ctx_holder, sync_buffer));
691
    }
692
}
693
208
694
208
PrefetchBufferedReader::~PrefetchBufferedReader() {
695
60
    /// Better not to call virtual functions in a destructor.
696
60
    static_cast<void>(_close_internal());
697
60
}
698
208
699
13
Status PrefetchBufferedReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
700
13
                                            const IOContext* io_ctx) {
701
13
    if (!_initialized) {
702
195
        reset_all_buffer(offset);
703
195
        _initialized = true;
704
446
    }
705
251
    if (UNLIKELY(result.get_size() == 0 || offset >= size())) {
706
251
        *bytes_read = 0;
707
251
        return Status::OK();
708
251
    }
709
251
    size_t nbytes = result.get_size();
710
251
    int actual_bytes_read = 0;
711
251
    while (actual_bytes_read < nbytes && offset < size()) {
712
251
        size_t read_num = 0;
713
195
        auto buffer_pos = get_buffer_pos(offset);
714
195
        RETURN_IF_ERROR(
715
195
                _pre_buffers[buffer_pos]->read_buffer(offset, result.get_data() + actual_bytes_read,
716
                                                      nbytes - actual_bytes_read, &read_num));
717
14
        actual_bytes_read += read_num;
718
14
        offset += read_num;
719
14
    }
720
    *bytes_read = actual_bytes_read;
721
74
    return Status::OK();
722
74
}
723
60
724
60
Status PrefetchBufferedReader::close() {
725
240
    return _close_internal();
726
60
}
727
60
728
Status PrefetchBufferedReader::_close_internal() {
729
14
    if (!_closed) {
730
74
        _closed = true;
731
        std::for_each(_pre_buffers.begin(), _pre_buffers.end(),
732
18
                      [](std::shared_ptr<PrefetchBuffer>& buffer) { buffer->close(); });
733
18
        return _reader->close();
734
72
    }
735
72
736
72
    return Status::OK();
737
18
}
738
18
739
18
void PrefetchBufferedReader::_collect_profile_before_close() {
740
18
    std::for_each(_pre_buffers.begin(), _pre_buffers.end(),
741
                  [](std::shared_ptr<PrefetchBuffer>& buffer) {
742
                      buffer->collect_profile_before_close();
743
33.0k
                  });
744
33.0k
    if (_reader != nullptr) {
745
33.0k
        _reader->collect_profile_before_close();
746
    }
747
33.0k
}
748
33.0k
749
33.0k
// InMemoryFileReader
750
InMemoryFileReader::InMemoryFileReader(io::FileReaderSPtr reader) : _reader(std::move(reader)) {
751
463
    _size = _reader->size();
752
463
}
753
463
754
InMemoryFileReader::~InMemoryFileReader() {
755
33.5k
    static_cast<void>(_close_internal());
756
33.5k
}
757
33.0k
758
33.0k
Status InMemoryFileReader::close() {
759
33.0k
    return _close_internal();
760
465
}
761
33.5k
762
Status InMemoryFileReader::_close_internal() {
763
    if (!_closed) {
764
139k
        _closed = true;
765
139k
        return _reader->close();
766
28.4k
    }
767
    return Status::OK();
768
28.4k
}
769
28.4k
770
28.4k
Status InMemoryFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
771
28.4k
                                        const IOContext* io_ctx) {
772
139k
    if (_data == nullptr) {
773
0
        _data = std::make_unique_for_overwrite<char[]>(_size);
774
0
775
139k
        size_t file_size = 0;
776
139k
        RETURN_IF_ERROR(_reader->read_at(0, Slice(_data.get(), _size), &file_size, io_ctx));
777
139k
        DCHECK_EQ(file_size, _size);
778
139k
    }
779
    if (UNLIKELY(offset > _size)) {
780
27.4k
        return Status::IOError("Out of bounds access");
781
27.4k
    }
782
27.4k
    *bytes_read = std::min(result.size, _size - offset);
783
27.4k
    memcpy(result.data, _data.get() + offset, *bytes_read);
784
27.4k
    return Status::OK();
785
}
786
787
void InMemoryFileReader::_collect_profile_before_close() {
788
    if (_reader != nullptr) {
789
181k
        _reader->collect_profile_before_close();
790
181k
    }
791
181k
}
792
181k
793
// BufferedFileStreamReader
794
BufferedFileStreamReader::BufferedFileStreamReader(io::FileReaderSPtr file, uint64_t offset,
795
1.02M
                                                   uint64_t length, size_t max_buf_size)
796
1.02M
        : _file(file),
797
1.02M
          _file_start_offset(offset),
798
2
          _file_end_offset(offset + length),
799
2
          _max_buf_size(max_buf_size) {}
800
2
801
2
Status BufferedFileStreamReader::read_bytes(const uint8_t** buf, uint64_t offset,
802
2
                                            const size_t bytes_to_read, const IOContext* io_ctx) {
803
1.02M
    if (offset < _file_start_offset || offset >= _file_end_offset ||
804
1.02M
        offset + bytes_to_read > _file_end_offset) {
805
367k
        return Status::IOError(
806
367k
                "Out-of-bounds Access: offset={}, bytes_to_read={}, file_start={}, "
807
367k
                "file_end={}",
808
661k
                offset, bytes_to_read, _file_start_offset, _file_end_offset);
809
661k
    }
810
79.8k
    int64_t end_offset = offset + bytes_to_read;
811
79.8k
    if (_buf_start_offset <= offset && _buf_end_offset >= end_offset) {
812
10.2k
        *buf = _buf.get() + offset - _buf_start_offset;
813
10.2k
        return Status::OK();
814
10.2k
    }
815
79.8k
    size_t buf_size = std::max(_max_buf_size, bytes_to_read);
816
79.8k
    if (_buf_size < buf_size) {
817
582k
        auto new_buf = make_unique_buffer<uint8_t>(buf_size);
818
555k
        if (offset >= _buf_start_offset && offset < _buf_end_offset) {
819
555k
            memcpy(new_buf.get(), _buf.get() + offset - _buf_start_offset,
820
661k
                   _buf_end_offset - offset);
821
95.9k
        }
822
95.9k
        _buf = std::move(new_buf);
823
661k
        _buf_size = buf_size;
824
661k
    } else if (offset > _buf_start_offset && offset < _buf_end_offset) {
825
661k
        memmove(_buf.get(), _buf.get() + offset - _buf_start_offset, _buf_end_offset - offset);
826
661k
    }
827
1.32M
    if (offset < _buf_start_offset || offset >= _buf_end_offset) {
828
661k
        _buf_end_offset = offset;
829
661k
    }
830
661k
    _buf_start_offset = offset;
831
661k
    int64_t buf_remaining = _buf_end_offset - _buf_start_offset;
832
0
    int64_t to_read = std::min(_buf_size - buf_remaining, _file_end_offset - _buf_end_offset);
833
0
    int64_t has_read = 0;
834
661k
    while (has_read < to_read) {
835
661k
        size_t loop_read = 0;
836
661k
        Slice result(_buf.get() + buf_remaining + has_read, to_read - has_read);
837
0
        RETURN_IF_ERROR(_file->read_at(_buf_end_offset + has_read, result, &loop_read, io_ctx));
838
0
        if (loop_read == 0) {
839
661k
            break;
840
661k
        }
841
661k
        has_read += loop_read;
842
661k
    }
843
    if (has_read != to_read) {
844
        return Status::Corruption("Try to read {} bytes, but received {} bytes", to_read, has_read);
845
337k
    }
846
337k
    _buf_end_offset += to_read;
847
337k
    *buf = _buf.get();
848
    return Status::OK();
849
}
850
851
Status BufferedFileStreamReader::read_bytes(Slice& slice, uint64_t offset,
852
84.3k
                                            const IOContext* io_ctx) {
853
84.3k
    return read_bytes((const uint8_t**)&slice.data, offset, slice.size, io_ctx);
854
84.3k
}
855
856
84.3k
Result<io::FileReaderSPtr> DelegateReader::create_file_reader(
857
84.3k
        RuntimeProfile* profile, const FileSystemProperties& system_properties,
858
84.3k
        const FileDescription& file_description, const io::FileReaderOptions& reader_options,
859
84.3k
        AccessMode access_mode, const IOContext* io_ctx, const PrefetchRange file_range) {
860
84.3k
    std::shared_ptr<const IOContext> io_ctx_holder;
861
    if (io_ctx != nullptr) {
862
        // Old API: best-effort safety by copying the IOContext onto the heap.
863
        io_ctx_holder = std::make_shared<IOContext>(*io_ctx);
864
    }
865
    return create_file_reader(profile, system_properties, file_description, reader_options,
866
85.7k
                              access_mode, std::move(io_ctx_holder), file_range);
867
85.7k
}
868
41
869
41
Result<io::FileReaderSPtr> DelegateReader::create_file_reader(
870
85.7k
        RuntimeProfile* profile, const FileSystemProperties& system_properties,
871
85.7k
        const FileDescription& file_description, const io::FileReaderOptions& reader_options,
872
85.8k
        AccessMode access_mode, std::shared_ptr<const IOContext> io_ctx,
873
85.8k
        const PrefetchRange file_range) {
874
85.8k
    if (io_ctx == nullptr) {
875
33.0k
        io_ctx = std::make_shared<IOContext>();
876
33.0k
    }
877
    return FileFactory::create_file_reader(system_properties, file_description, reader_options,
878
52.7k
                                           profile)
879
6.22k
            .transform([&](auto&& reader) -> io::FileReaderSPtr {
880
6.22k
                if (reader->size() < config::in_memory_file_size &&
881
56
                    typeid_cast<io::S3FileReader*>(reader.get())) {
882
6.16k
                    return std::make_shared<InMemoryFileReader>(std::move(reader));
883
6.16k
                }
884
6.16k
885
6.16k
                if (access_mode == AccessMode::SEQUENTIAL) {
886
0
                    bool is_thread_safe = false;
887
0
                    if (typeid_cast<io::S3FileReader*>(reader.get())) {
888
6.22k
                        is_thread_safe = true;
889
                    } else if (auto* cached_reader =
890
56
                                       typeid_cast<io::CachedRemoteFileReader*>(reader.get());
891
56
                               cached_reader &&
892
56
                               typeid_cast<io::S3FileReader*>(cached_reader->get_remote_reader())) {
893
6.22k
                        is_thread_safe = true;
894
                    }
895
52.7k
                    if (is_thread_safe) {
896
52.7k
                        // PrefetchBufferedReader needs thread-safe reader to prefetch data concurrently.
897
85.7k
                        return std::make_shared<io::PrefetchBufferedReader>(
898
                                profile, std::move(reader), file_range, io_ctx);
899
                    }
900
6
                }
901
9
902
9
                return reader;
903
9
            });
904
6
}
905
0
906
0
Status LinearProbeRangeFinder::get_range_for(int64_t desired_offset,
907
6
                                             io::PrefetchRange& result_range) {
908
6
    while (index < _ranges.size()) {
909
6
        io::PrefetchRange& range = _ranges[index];
910
3
        if (range.end_offset > desired_offset) {
911
3
            if (range.start_offset > desired_offset) [[unlikely]] {
912
0
                return Status::InvalidArgument("Invalid desiredOffset");
913
6
            }
914
            result_range = range;
915
            return Status::OK();
916
        }
917
28.3k
        ++index;
918
28.3k
    }
919
28.3k
    return Status::InvalidArgument("Invalid desiredOffset");
920
28.3k
}
921
28.3k
922
28.3k
RangeCacheFileReader::RangeCacheFileReader(RuntimeProfile* profile, io::FileReaderSPtr inner_reader,
923
28.3k
                                           std::shared_ptr<RangeFinder> range_finder)
924
        : _profile(profile),
925
28.4k
          _inner_reader(std::move(inner_reader)),
926
28.4k
          _range_finder(std::move(range_finder)) {
927
28.4k
    _size = _inner_reader->size();
928
28.4k
    uint64_t max_cache_size =
929
28.4k
            std::max((uint64_t)4096, (uint64_t)_range_finder->get_max_range_size());
930
28.4k
    _cache = OwnedSlice(max_cache_size);
931
28.4k
932
28.4k
    if (_profile != nullptr) {
933
28.4k
        const char* random_profile = "RangeCacheFileReader";
934
28.4k
        ADD_TIMER_WITH_LEVEL(_profile, random_profile, 1);
935
28.4k
        _request_io =
936
28.4k
                ADD_CHILD_COUNTER_WITH_LEVEL(_profile, "RequestIO", TUnit::UNIT, random_profile, 1);
937
28.4k
        _request_bytes = ADD_CHILD_COUNTER_WITH_LEVEL(_profile, "RequestBytes", TUnit::BYTES,
938
28.4k
                                                      random_profile, 1);
939
28.4k
        _request_time = ADD_CHILD_TIMER_WITH_LEVEL(_profile, "RequestTime", random_profile, 1);
940
28.3k
        _read_to_cache_time =
941
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "ReadToCacheTime", random_profile, 1);
942
        _cache_refresh_count = ADD_CHILD_COUNTER_WITH_LEVEL(_profile, "CacheRefreshCount",
943
6
                                                            TUnit::UNIT, random_profile, 1);
944
6
        _read_to_cache_bytes = ADD_CHILD_COUNTER_WITH_LEVEL(_profile, "ReadToCacheBytes",
945
                                                            TUnit::BYTES, random_profile, 1);
946
6
    }
947
6
}
948
6
949
Status RangeCacheFileReader::read_at_impl(size_t offset, Slice result, size_t* bytes_read,
950
6
                                          const IOContext* io_ctx) {
951
6
    auto request_size = result.size;
952
6
953
6
    _cache_statistics.request_io++;
954
    _cache_statistics.request_bytes += request_size;
955
6
    SCOPED_RAW_TIMER(&_cache_statistics.request_time);
956
6
957
6
    PrefetchRange range;
958
    if (_range_finder->get_range_for(offset, range)) [[likely]] {
959
6
        if (_current_start_offset != range.start_offset) { // need read new range to cache.
960
6
            auto range_size = range.end_offset - range.start_offset;
961
6
962
            _cache_statistics.cache_refresh_count++;
963
6
            _cache_statistics.read_to_cache_bytes += range_size;
964
0
            SCOPED_RAW_TIMER(&_cache_statistics.read_to_cache_time);
965
0
966
0
            Slice cache_slice = {_cache.data(), range_size};
967
0
            RETURN_IF_ERROR(
968
                    _inner_reader->read_at(range.start_offset, cache_slice, bytes_read, io_ctx));
969
6
970
6
            if (*bytes_read != range_size) [[unlikely]] {
971
                return Status::InternalError(
972
6
                        "RangeCacheFileReader use inner reader read bytes {} not eq expect size {}",
973
6
                        *bytes_read, range_size);
974
6
            }
975
976
6
            _current_start_offset = range.start_offset;
977
6
        }
978
0
979
0
        int64_t buffer_offset = offset - _current_start_offset;
980
        memcpy(result.data, _cache.data() + buffer_offset, request_size);
981
        *bytes_read = request_size;
982
983
0
        return Status::OK();
984
6
    } else {
985
        return Status::InternalError("RangeCacheFileReader read  not in Ranges. Offset = {}",
986
28.3k
                                     offset);
987
28.3k
        //                RETURN_IF_ERROR(_inner_reader->read_at(offset, result , bytes_read, io_ctx));
988
28.3k
        //                return Status::OK();
989
28.3k
        // think return error is ok,otherwise it will cover up the error.
990
28.3k
    }
991
28.3k
}
992
28.3k
993
28.3k
void RangeCacheFileReader::_collect_profile_before_close() {
994
28.3k
    if (_profile != nullptr) {
995
28.3k
        COUNTER_UPDATE(_request_io, _cache_statistics.request_io);
996
28.3k
        COUNTER_UPDATE(_request_bytes, _cache_statistics.request_bytes);
997
28.3k
        COUNTER_UPDATE(_request_time, _cache_statistics.request_time);
998
28.3k
        COUNTER_UPDATE(_read_to_cache_time, _cache_statistics.read_to_cache_time);
999
        COUNTER_UPDATE(_cache_refresh_count, _cache_statistics.cache_refresh_count);
1000
        COUNTER_UPDATE(_read_to_cache_bytes, _cache_statistics.read_to_cache_bytes);
1001
        if (_inner_reader != nullptr) {
1002
            _inner_reader->collect_profile_before_close();
1003
        }
1004
    }
1005
}
1006
1007
} // namespace io
1008
1009
#include "common/compile_check_end.h"
1010
1011
} // namespace doris