Coverage Report

Created: 2026-07-29 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/rowid_fetcher.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 "exec/rowid_fetcher.h"
19
20
#include <brpc/callback.h>
21
#include <butil/endpoint.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/data.pb.h>
24
#include <gen_cpp/internal_service.pb.h>
25
#include <gen_cpp/olap_file.pb.h>
26
#include <gen_cpp/types.pb.h>
27
#include <glog/logging.h>
28
#include <stddef.h>
29
#include <stdint.h>
30
31
#include <algorithm>
32
#include <cstdint>
33
#include <memory>
34
#include <ostream>
35
#include <string>
36
#include <unordered_map>
37
#include <utility>
38
#include <vector>
39
40
#include "bthread/countdown_event.h"
41
#include "common/config.h"
42
#include "common/consts.h"
43
#include "common/exception.h"
44
#include "common/signal_handler.h"
45
#include "core/assert_cast.h"
46
#include "core/block/block.h" // Block
47
#include "core/column/column.h"
48
#include "core/column/column_nullable.h"
49
#include "core/column/column_string.h"
50
#include "core/data_type/data_type_struct.h"
51
#include "core/data_type_serde/data_type_serde.h"
52
#include "core/string_ref.h"
53
#include "exec/scan/file_scanner.h"
54
#include "format/orc/vorc_reader.h"
55
#include "format/parquet/vparquet_reader.h"
56
#include "io/io_common.h"
57
#include "runtime/descriptors.h"
58
#include "runtime/exec_env.h"      // ExecEnv
59
#include "runtime/fragment_mgr.h"  // FragmentMgr
60
#include "runtime/runtime_state.h" // RuntimeState
61
#include "runtime/workload_group/workload_group_manager.h"
62
#include "semaphore"
63
#include "storage/olap_common.h"
64
#include "storage/rowset/beta_rowset.h"
65
#include "storage/segment/column_reader.h"
66
#include "storage/storage_engine.h"
67
#include "storage/tablet/tablet_fwd.h"
68
#include "storage/tablet/tablet_schema.h"
69
#include "storage/tablet_info.h" // DorisNodesInfo
70
#include "storage/utils.h"
71
#include "util/brpc_client_cache.h" // BrpcClientCache
72
#include "util/defer_op.h"
73
#include "util/jsonb/serialize.h"
74
75
namespace doris {
76
77
namespace {
78
79
void set_topn_lazy_materialization_file_cache_stats(
80
3.21k
        const io::FileCacheStatistics& stats, PTopNLazyMaterializationFileCacheStats* pstats) {
81
3.21k
    pstats->set_local_io_count(stats.num_local_io_total);
82
3.21k
    pstats->set_local_io_bytes(stats.bytes_read_from_local);
83
3.21k
    pstats->set_remote_io_count(stats.num_remote_io_total);
84
3.21k
    pstats->set_remote_io_bytes(stats.bytes_read_from_remote);
85
3.21k
    pstats->set_skip_cache_io_count(stats.num_skip_cache_io_total);
86
3.21k
    pstats->set_write_cache_bytes(stats.bytes_write_into_cache);
87
3.21k
    pstats->set_local_io_time(stats.local_io_timer);
88
3.21k
    pstats->set_remote_io_time(stats.remote_io_timer);
89
3.21k
    pstats->set_write_cache_io_time(stats.write_cache_io_timer);
90
3.21k
}
91
92
} // namespace
93
94
0
Status RowIDFetcher::init() {
95
0
    DorisNodesInfo nodes_info;
96
0
    nodes_info.setNodes(_fetch_option.t_fetch_opt.nodes_info);
97
0
    for (auto [node_id, node_info] : nodes_info.nodes_info()) {
98
0
        auto client = ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
99
0
                node_info.host, node_info.brpc_port);
100
0
        if (!client) {
101
0
            LOG(WARNING) << "Get rpc stub failed, host=" << node_info.host
102
0
                         << ", port=" << node_info.brpc_port;
103
0
            return Status::InternalError("RowIDFetcher failed to init rpc client, host={}, port={}",
104
0
                                         node_info.host, node_info.brpc_port);
105
0
        }
106
0
        _stubs.push_back(client);
107
0
    }
108
0
    return Status::OK();
109
0
}
110
111
0
PMultiGetRequest RowIDFetcher::_init_fetch_request(const ColumnString& row_locs) const {
112
0
    PMultiGetRequest mget_req;
113
0
    _fetch_option.desc->to_protobuf(mget_req.mutable_desc());
114
0
    for (SlotDescriptor* slot : _fetch_option.desc->slots()) {
115
        // ignore rowid
116
0
        if (slot->col_name() == BeConsts::ROWID_COL) {
117
0
            continue;
118
0
        }
119
0
        slot->to_protobuf(mget_req.add_slots());
120
0
    }
121
0
    for (size_t i = 0; i < row_locs.size(); ++i) {
122
0
        PRowLocation row_loc;
123
0
        StringRef row_id_rep = row_locs.get_data_at(i);
124
        // TODO: When transferring data between machines with different byte orders (endianness),
125
        // not performing proper handling may lead to issues in parsing and exchanging the data.
126
0
        auto location = reinterpret_cast<const GlobalRowLoacation*>(row_id_rep.data);
127
0
        row_loc.set_tablet_id(location->tablet_id);
128
0
        row_loc.set_rowset_id(location->row_location.rowset_id.to_string());
129
0
        row_loc.set_segment_id(location->row_location.segment_id);
130
0
        row_loc.set_ordinal_id(location->row_location.row_id);
131
0
        *mget_req.add_row_locs() = std::move(row_loc);
132
0
    }
133
    // Set column desc
134
0
    for (const TColumn& tcolumn : _fetch_option.t_fetch_opt.column_desc) {
135
0
        TabletColumn column(tcolumn);
136
0
        column.to_schema_pb(mget_req.add_column_desc());
137
0
    }
138
0
    PUniqueId& query_id = *mget_req.mutable_query_id();
139
0
    query_id.set_hi(_fetch_option.runtime_state->query_id().hi);
140
0
    query_id.set_lo(_fetch_option.runtime_state->query_id().lo);
141
0
    mget_req.set_be_exec_version(_fetch_option.runtime_state->be_exec_version());
142
0
    mget_req.set_fetch_row_store(_fetch_option.t_fetch_opt.fetch_row_store);
143
0
    return mget_req;
144
0
}
145
146
Status RowIDFetcher::_merge_rpc_results(const PMultiGetRequest& request,
147
                                        const std::vector<PMultiGetResponse>& rsps,
148
                                        const std::vector<brpc::Controller>& cntls,
149
                                        Block* output_block,
150
0
                                        std::vector<PRowLocation>* rows_id) const {
151
0
    output_block->clear();
152
0
    for (const auto& cntl : cntls) {
153
0
        if (cntl.Failed()) {
154
0
            LOG(WARNING) << "Failed to fetch meet rpc error:" << cntl.ErrorText()
155
0
                         << ", host:" << cntl.remote_side();
156
0
            return Status::InternalError(cntl.ErrorText());
157
0
        }
158
0
    }
159
0
    DataTypeSerDeSPtrs serdes;
160
0
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
161
0
    std::vector<std::string> default_values;
162
0
    default_values.resize(_fetch_option.desc->slots().size());
163
0
    auto merge_function = [&](const PMultiGetResponse& resp) {
164
0
        Status st(Status::create(resp.status()));
165
0
        if (!st.ok()) {
166
0
            LOG(WARNING) << "Failed to fetch " << st.to_string();
167
0
            return st;
168
0
        }
169
0
        for (const PRowLocation& row_id : resp.row_locs()) {
170
0
            rows_id->push_back(row_id);
171
0
        }
172
        // Merge binary rows
173
0
        if (request.fetch_row_store()) {
174
0
            CHECK(resp.row_locs().size() == resp.binary_row_data_size());
175
0
            if (output_block->is_empty_column()) {
176
0
                *output_block = Block(_fetch_option.desc->slots(), 1);
177
0
            }
178
0
            if (serdes.empty() && col_uid_to_idx.empty()) {
179
0
                serdes = create_data_type_serdes(_fetch_option.desc->slots());
180
0
                for (int i = 0; i < _fetch_option.desc->slots().size(); ++i) {
181
0
                    col_uid_to_idx[_fetch_option.desc->slots()[i]->col_unique_id()] = i;
182
0
                    default_values[i] = _fetch_option.desc->slots()[i]->col_default_value();
183
0
                }
184
0
            }
185
0
            auto output_columns_guard = output_block->mutate_columns_scoped();
186
0
            MutableColumns& output_columns = output_columns_guard.mutable_columns();
187
0
            for (int i = 0; i < resp.binary_row_data_size(); ++i) {
188
0
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
189
0
                        serdes, resp.binary_row_data(i).data(), resp.binary_row_data(i).size(),
190
0
                        col_uid_to_idx, output_columns, default_values, {}));
191
0
            }
192
0
            return Status::OK();
193
0
        }
194
        // Merge partial blocks
195
0
        Block partial_block;
196
0
        [[maybe_unused]] size_t uncompressed_size = 0;
197
0
        [[maybe_unused]] int64_t uncompressed_time = 0;
198
199
0
        RETURN_IF_ERROR(
200
0
                partial_block.deserialize(resp.block(), &uncompressed_size, &uncompressed_time));
201
0
        if (partial_block.is_empty_column()) {
202
0
            return Status::OK();
203
0
        }
204
0
        CHECK(resp.row_locs().size() == partial_block.rows());
205
0
        if (output_block->is_empty_column()) {
206
0
            output_block->swap(partial_block);
207
0
        } else if (partial_block.columns() != output_block->columns()) {
208
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
209
0
                    "Merge block not match, self:[{}], input:[{}], ", output_block->dump_types(),
210
0
                    partial_block.dump_types());
211
0
        } else {
212
0
            for (int i = 0; i < output_block->columns(); ++i) {
213
0
                auto column_guard = output_block->mutate_column_scoped(i);
214
0
                MutableColumnPtr& column = column_guard.mutable_column();
215
0
                column->insert_range_from(
216
0
                        *partial_block.get_by_position(i).column->convert_to_full_column_if_const(),
217
0
                        0, partial_block.rows());
218
0
            }
219
0
        }
220
0
        return Status::OK();
221
0
    };
222
223
0
    for (const auto& resp : rsps) {
224
0
        RETURN_IF_ERROR(merge_function(resp));
225
0
    }
226
0
    return Status::OK();
227
0
}
228
229
0
Status RowIDFetcher::fetch(const ColumnPtr& column_row_ids, Block* res_block) {
230
0
    CHECK(!_stubs.empty());
231
0
    PMultiGetRequest mget_req = _init_fetch_request(
232
0
            assert_cast<const ColumnString&>(*remove_nullable(column_row_ids).get()));
233
0
    std::vector<PMultiGetResponse> resps(_stubs.size());
234
0
    std::vector<brpc::Controller> cntls(_stubs.size());
235
0
    bthread::CountdownEvent counter(cast_set<int>(_stubs.size()));
236
0
    for (size_t i = 0; i < _stubs.size(); ++i) {
237
0
        cntls[i].set_timeout_ms(_fetch_option.runtime_state->execution_timeout() * 1000);
238
0
        auto callback = brpc::NewCallback(fetch_callback, &counter);
239
0
        _stubs[i]->multiget_data(&cntls[i], &mget_req, &resps[i], callback);
240
0
    }
241
0
    counter.wait();
242
243
    // Merge
244
0
    std::vector<PRowLocation> rows_locs;
245
0
    rows_locs.reserve(rows_locs.size());
246
0
    RETURN_IF_ERROR(_merge_rpc_results(mget_req, resps, cntls, res_block, &rows_locs));
247
0
    if (rows_locs.size() < column_row_ids->size()) {
248
0
        return Status::InternalError("Miss matched return row loc count {}, expected {}, input {}",
249
0
                                     rows_locs.size(), res_block->rows(), column_row_ids->size());
250
0
    }
251
    // Final sort by row_ids sequence, since row_ids is already sorted if need
252
0
    std::map<GlobalRowLoacation, size_t> positions;
253
0
    for (size_t i = 0; i < rows_locs.size(); ++i) {
254
0
        RowsetId rowset_id;
255
0
        rowset_id.init(rows_locs[i].rowset_id());
256
0
        GlobalRowLoacation grl(rows_locs[i].tablet_id(), rowset_id,
257
0
                               cast_set<uint32_t>(rows_locs[i].segment_id()),
258
0
                               cast_set<uint32_t>(rows_locs[i].ordinal_id()));
259
0
        positions[grl] = i;
260
0
    };
261
    // TODO remove this warning code
262
0
    if (positions.size() < rows_locs.size()) {
263
0
        LOG(WARNING) << "cwntains duplicated row entry";
264
0
    }
265
0
    IColumn::Permutation permutation;
266
0
    permutation.reserve(column_row_ids->size());
267
0
    for (size_t i = 0; i < column_row_ids->size(); ++i) {
268
0
        auto location =
269
0
                reinterpret_cast<const GlobalRowLoacation*>(column_row_ids->get_data_at(i).data);
270
0
        permutation.push_back(positions[*location]);
271
0
    }
272
0
    for (size_t i = 0; i < res_block->columns(); ++i) {
273
0
        res_block->get_by_position(i).column =
274
0
                res_block->get_by_position(i).column->permute(permutation, permutation.size());
275
0
    }
276
    // Check row consistency
277
0
    RETURN_IF_CATCH_EXCEPTION(res_block->check_number_of_rows());
278
0
    VLOG_DEBUG << "dump block:" << res_block->dump_data(0, 10);
279
0
    return Status::OK();
280
0
}
281
282
struct IteratorKey {
283
    int64_t tablet_id;
284
    RowsetId rowset_id;
285
    uint64_t segment_id;
286
    int slot_id;
287
288
    // unordered map std::equal_to
289
12.8k
    bool operator==(const IteratorKey& rhs) const {
290
12.8k
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
291
12.8k
               segment_id == rhs.segment_id && slot_id == rhs.slot_id;
292
12.8k
    }
293
};
294
295
struct SegKey {
296
    int64_t tablet_id;
297
    RowsetId rowset_id;
298
    uint64_t segment_id;
299
300
    // unordered map std::equal_to
301
6.41k
    bool operator==(const SegKey& rhs) const {
302
6.41k
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
303
6.41k
               segment_id == rhs.segment_id;
304
6.41k
    }
305
};
306
307
struct HashOfSegKey {
308
17.6k
    size_t operator()(const SegKey& key) const {
309
17.6k
        size_t seed = 0;
310
17.6k
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
311
17.6k
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
312
17.6k
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
313
17.6k
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
314
17.6k
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
315
17.6k
        return seed;
316
17.6k
    }
317
};
318
319
struct HashOfIteratorKey {
320
25.7k
    size_t operator()(const IteratorKey& key) const {
321
25.7k
        size_t seed = 0;
322
25.7k
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
323
25.7k
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
324
25.7k
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
325
25.7k
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
326
25.7k
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
327
25.7k
        seed = HashUtil::hash64(&key.slot_id, sizeof(key.slot_id), seed);
328
25.7k
        return seed;
329
25.7k
    }
330
};
331
332
struct IteratorItem {
333
    std::unique_ptr<ColumnIterator> iterator;
334
    SegmentSharedPtr segment;
335
    // for holding the reference of storage read options to avoid use after release
336
    StorageReadOptions storage_read_options;
337
};
338
339
static void set_slot_access_paths(const SlotDescriptor& slot, const TabletSchema& schema,
340
12.8k
                                  StorageReadOptions& storage_read_options) {
341
12.8k
    int32_t unique_id = slot.col_unique_id();
342
12.8k
    const int field_index =
343
12.8k
            unique_id >= 0 ? schema.field_index(unique_id) : schema.field_index(slot.col_name());
344
12.8k
    if (field_index >= 0) {
345
12.8k
        const auto& column = schema.column(field_index);
346
12.8k
        unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
347
12.8k
    }
348
12.8k
    if (unique_id < 0) {
349
0
        return;
350
0
    }
351
352
12.8k
    if (!slot.all_access_paths().empty()) {
353
1.48k
        storage_read_options.all_access_paths[unique_id] = slot.all_access_paths();
354
1.48k
    }
355
356
12.8k
    if (!slot.predicate_access_paths().empty()) {
357
0
        storage_read_options.predicate_access_paths[unique_id] = slot.predicate_access_paths();
358
0
    }
359
12.8k
}
360
361
struct SegItem {
362
    BaseTabletSPtr tablet;
363
    BetaRowsetSharedPtr rowset;
364
    // for holding the reference of segment to avoid use after release
365
    SegmentSharedPtr segment;
366
};
367
368
// Groups all row_ids belonging to the same segment for batched reading.
369
// Position index tracks where each row_id originated in the original request,
370
// so results can be scattered back to the correct output positions.
371
struct DorisFormatReadBatch {
372
    std::shared_ptr<FileMapping> file_mapping;
373
    // (row_id, index_in_request) pairs for all rows in this segment.
374
    std::vector<std::pair<segment_v2::rowid_t, size_t>> row_ids_with_positions;
375
};
376
377
static void scatter_scan_blocks_to_result_block(
378
        const std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
379
2.98k
        const std::vector<Block>& scan_blocks, Block& result_block) {
380
17.6k
    for (size_t column_id = 0; column_id < result_block.columns(); ++column_id) {
381
14.6k
        auto dst_col_guard = result_block.mutate_column_scoped(column_id);
382
14.6k
        MutableColumnPtr& dst_col = dst_col_guard.mutable_column();
383
384
14.6k
        std::vector<const IColumn*> scan_src_columns;
385
14.6k
        scan_src_columns.reserve(row_id_block_idx.size());
386
14.6k
        std::vector<size_t> scan_positions;
387
14.6k
        scan_positions.reserve(row_id_block_idx.size());
388
172k
        for (const auto& [pos_block, block_idx] : row_id_block_idx) {
389
172k
            DCHECK(scan_blocks.size() > pos_block);
390
172k
            DCHECK(scan_blocks[pos_block].columns() > column_id);
391
172k
            scan_src_columns.emplace_back(
392
172k
                    scan_blocks[pos_block].get_by_position(column_id).column.get());
393
172k
            scan_positions.emplace_back(block_idx);
394
172k
        }
395
14.6k
        dst_col->insert_from_multi_column(scan_src_columns, scan_positions);
396
14.6k
    }
397
2.98k
}
398
399
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequest& request,
400
1
                                          PMultiGetResponse* response) {
401
    // read from storage engine row id by row id
402
1
    OlapReaderStatistics stats;
403
1
    Block result_block;
404
1
    int64_t acquire_tablet_ms = 0;
405
1
    int64_t acquire_rowsets_ms = 0;
406
1
    int64_t acquire_segments_ms = 0;
407
1
    int64_t lookup_row_data_ms = 0;
408
409
    // init desc
410
1
    std::vector<SlotDescriptor> slots;
411
1
    slots.reserve(request.slots().size());
412
2
    for (const auto& pslot : request.slots()) {
413
2
        slots.push_back(SlotDescriptor(pslot));
414
2
    }
415
416
    // init read schema
417
1
    TabletSchema full_read_schema;
418
1
    for (const ColumnPB& column_pb : request.column_desc()) {
419
1
        full_read_schema.append_column(TabletColumn(column_pb));
420
1
    }
421
422
1
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
423
    // read row by row
424
4
    for (int i = 0; i < request.row_locs_size(); ++i) {
425
3
        const auto& row_loc = request.row_locs(i);
426
3
        MonotonicStopWatch watch;
427
3
        watch.start();
428
3
        BaseTabletSPtr tablet = scope_timer_run(
429
3
                [&]() {
430
3
                    auto res = ExecEnv::get_tablet(row_loc.tablet_id(), nullptr, true);
431
3
                    return !res.has_value() ? nullptr
432
3
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
433
3
                },
434
3
                &acquire_tablet_ms);
435
3
        RowsetId rowset_id;
436
3
        rowset_id.init(row_loc.rowset_id());
437
3
        if (!tablet) {
438
0
            continue;
439
0
        }
440
        // We ensured it's rowset is not released when init Tablet reader param, rowset->update_delayed_expired_timestamp();
441
3
        BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
442
3
                [&]() {
443
3
                    return ExecEnv::GetInstance()->storage_engine().get_quering_rowset(rowset_id);
444
3
                },
445
3
                &acquire_rowsets_ms));
446
3
        if (!rowset) {
447
0
            LOG(INFO) << "no such rowset " << rowset_id;
448
0
            continue;
449
0
        }
450
3
        size_t row_size = 0;
451
3
        Defer _defer([&]() {
452
3
            LOG_EVERY_N(INFO, 100)
453
1
                    << "multiget_data single_row, cost(us):" << watch.elapsed_time() / 1000
454
1
                    << ", row_size:" << row_size;
455
3
            *response->add_row_locs() = row_loc;
456
3
        });
457
        // TODO: supoort session variable enable_page_cache and disable_file_cache if necessary.
458
3
        SegmentCacheHandle segment_cache;
459
3
        RETURN_IF_ERROR(scope_timer_run(
460
3
                [&]() {
461
3
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
462
3
                },
463
3
                &acquire_segments_ms));
464
        // find segment
465
3
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
466
3
                               segment_cache.get_segments().cend(),
467
3
                               [&row_loc](const segment_v2::SegmentSharedPtr& seg) {
468
3
                                   return seg->id() == row_loc.segment_id();
469
3
                               });
470
3
        if (it == segment_cache.get_segments().end()) {
471
0
            continue;
472
0
        }
473
3
        segment_v2::SegmentSharedPtr segment = *it;
474
3
        GlobalRowLoacation row_location(row_loc.tablet_id(), rowset->rowset_id(),
475
3
                                        cast_set<uint32_t>(row_loc.segment_id()),
476
3
                                        cast_set<uint32_t>(row_loc.ordinal_id()));
477
        // fetch by row store, more effcient way
478
3
        if (request.fetch_row_store()) {
479
0
            if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
480
0
                return Status::InternalError("Tablet {} does not have row store for all columns",
481
0
                                             tablet->tablet_id());
482
0
            }
483
0
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_loc.ordinal_id()));
484
0
            std::string* value = response->add_binary_row_data();
485
0
            RETURN_IF_ERROR(scope_timer_run(
486
0
                    [&]() { return tablet->lookup_row_data({}, loc, rowset, stats, *value); },
487
0
                    &lookup_row_data_ms));
488
0
            row_size = value->size();
489
0
            continue;
490
0
        }
491
492
        // fetch by column store
493
3
        if (result_block.is_empty_column()) {
494
1
            result_block = Block(slots, request.row_locs().size());
495
1
        }
496
3
        VLOG_DEBUG << "Read row location "
497
0
                   << fmt::format("{}, {}, {}, {}", row_location.tablet_id,
498
0
                                  row_location.row_location.rowset_id.to_string(),
499
0
                                  row_location.row_location.segment_id,
500
0
                                  row_location.row_location.row_id);
501
9
        for (int x = 0; x < slots.size(); ++x) {
502
6
            std::vector<segment_v2::rowid_t> row_ids {
503
6
                    static_cast<segment_v2::rowid_t>(row_loc.ordinal_id())};
504
6
            auto column_guard = result_block.mutate_column_scoped(x);
505
6
            MutableColumnPtr& column = column_guard.mutable_column();
506
6
            IteratorKey iterator_key {.tablet_id = tablet->tablet_id(),
507
6
                                      .rowset_id = rowset_id,
508
6
                                      .segment_id = row_loc.segment_id(),
509
6
                                      .slot_id = slots[x].id()};
510
6
            IteratorItem& iterator_item = iterator_map[iterator_key];
511
6
            if (iterator_item.segment == nullptr) {
512
                // hold the reference
513
2
                iterator_map[iterator_key].segment = segment;
514
2
                iterator_item.storage_read_options.stats = &stats;
515
2
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
516
2
            }
517
6
            segment = iterator_item.segment;
518
6
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
519
6
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
520
6
                    full_read_schema, &slots[x], row_ids, column,
521
6
                    iterator_item.storage_read_options, iterator_item.iterator));
522
6
        }
523
3
    }
524
    // serialize block if not empty
525
1
    if (!result_block.is_empty_column()) {
526
1
        VLOG_DEBUG << "dump block:" << result_block.dump_data(0, 10)
527
0
                   << ", be_exec_version:" << request.be_exec_version();
528
1
        [[maybe_unused]] size_t compressed_size = 0;
529
1
        [[maybe_unused]] size_t uncompressed_size = 0;
530
1
        [[maybe_unused]] int64_t compress_time = 0;
531
1
        int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
532
1
        RETURN_IF_ERROR(result_block.serialize(be_exec_version, response->mutable_block(),
533
1
                                               &uncompressed_size, &compressed_size, &compress_time,
534
1
                                               segment_v2::CompressionTypePB::LZ4));
535
1
    }
536
537
1
    LOG(INFO) << "Query stats: "
538
1
              << fmt::format(
539
1
                         "query_id:{}, "
540
1
                         "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
541
1
                         "io_latency:{}ns, "
542
1
                         "uncompressed_bytes_read:{},"
543
1
                         "bytes_read:{},"
544
1
                         "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
545
1
                         "lookup_row_data_ms:{}",
546
1
                         print_id(request.query_id()), stats.cached_pages_num,
547
1
                         stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
548
1
                         stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
549
1
                         acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms);
550
1
    return Status::OK();
551
1
}
552
553
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequestV2& request,
554
3.21k
                                          PMultiGetResponseV2* response) {
555
3.21k
    if (request.request_block_descs_size()) {
556
3.21k
        auto tquery_id = ((UniqueId)request.query_id()).to_thrift();
557
        // todo: use mutableBlock instead of block
558
3.21k
        std::vector<Block> result_blocks(request.request_block_descs_size());
559
560
3.21k
        OlapReaderStatistics stats;
561
3.21k
        int64_t acquire_tablet_ms = 0;
562
3.21k
        int64_t acquire_rowsets_ms = 0;
563
3.21k
        int64_t acquire_segments_ms = 0;
564
3.21k
        int64_t lookup_row_data_ms = 0;
565
566
3.21k
        int64_t external_init_reader_avg_ms = 0;
567
3.21k
        int64_t external_get_block_avg_ms = 0;
568
3.21k
        size_t external_scan_range_cnt = 0;
569
570
3.21k
        const auto file_cache_miss_policy =
571
3.21k
                request.file_cache_remote_only_on_miss()
572
3.21k
                        ? io::FileCacheMissPolicy::REMOTE_ONLY_ON_MISS
573
3.21k
                        : io::FileCacheMissPolicy::READ_THROUGH_AND_WRITE_BACK;
574
575
        // Add counters for different file mapping types
576
3.21k
        std::unordered_map<FileMappingType, int64_t> file_type_counts;
577
578
3.21k
        auto id_file_map =
579
3.21k
                ExecEnv::GetInstance()->get_id_manager()->get_id_file_map(request.query_id());
580
        // if id_file_map is null, means the BE not have scan range, just return ok
581
3.21k
        if (!id_file_map) {
582
            // padding empty block to response
583
0
            LOG(INFO) << "id_file_map not found for query_id: " << print_id(request.query_id());
584
0
            for (int i = 0; i < request.request_block_descs_size(); ++i) {
585
0
                response->add_blocks();
586
0
            }
587
0
            return Status::OK();
588
0
        }
589
590
6.52k
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
591
3.31k
            const auto& request_block_desc = request.request_block_descs(i);
592
3.31k
            PMultiGetBlockV2* pblock = response->add_blocks();
593
3.31k
            if (request_block_desc.row_id_size() >= 1) {
594
                // Since this block belongs to the same table, we only need to take the first type for judgment.
595
2.98k
                auto first_file_id = request_block_desc.file_id(0);
596
2.98k
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
597
2.98k
                if (!first_file_mapping) {
598
0
                    return Status::InternalError(
599
0
                            "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
600
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
601
0
                            first_file_id);
602
0
                }
603
2.98k
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
604
605
                // prepare slots to build block
606
2.98k
                std::vector<SlotDescriptor> slots;
607
2.98k
                slots.reserve(request_block_desc.slots_size());
608
14.6k
                for (const auto& pslot : request_block_desc.slots()) {
609
14.6k
                    slots.push_back(SlotDescriptor(pslot));
610
14.6k
                }
611
2.98k
                try {
612
2.98k
                    if (first_file_mapping->type == FileMappingType::INTERNAL) {
613
962
                        RETURN_IF_ERROR(read_batch_doris_format_row(
614
962
                                request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
615
962
                                stats, &acquire_tablet_ms, &acquire_rowsets_ms,
616
962
                                &acquire_segments_ms, &lookup_row_data_ms, file_cache_miss_policy));
617
2.02k
                    } else {
618
2.02k
                        RETURN_IF_ERROR(read_batch_external_row(
619
2.02k
                                request.wg_id(), request_block_desc, id_file_map, slots,
620
2.02k
                                first_file_mapping, tquery_id, result_blocks[i],
621
2.02k
                                pblock->mutable_profile(), &external_init_reader_avg_ms,
622
2.02k
                                &external_get_block_avg_ms, &external_scan_range_cnt));
623
2.02k
                    }
624
2.98k
                } catch (const Exception& e) {
625
0
                    return Status::Error<false>(e.code(), "Row id fetch failed because {}",
626
0
                                                e.what());
627
0
                }
628
2.98k
            }
629
630
3.31k
            [[maybe_unused]] size_t compressed_size = 0;
631
3.31k
            [[maybe_unused]] size_t uncompressed_size = 0;
632
3.31k
            [[maybe_unused]] int64_t compress_time = 0;
633
3.31k
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
634
3.31k
            RETURN_IF_ERROR(result_blocks[i].serialize(
635
3.31k
                    be_exec_version, pblock->mutable_block(), &uncompressed_size, &compressed_size,
636
3.31k
                    &compress_time, segment_v2::CompressionTypePB::LZ4));
637
3.31k
        }
638
639
        // Build file type statistics string
640
3.21k
        std::string file_type_stats;
641
3.21k
        for (const auto& [type, count] : file_type_counts) {
642
2.89k
            if (!file_type_stats.empty()) {
643
0
                file_type_stats += ", ";
644
0
            }
645
2.89k
            file_type_stats += fmt::format("{}:{}", type, count);
646
2.89k
        }
647
648
3.21k
        LOG(INFO) << "Query stats: "
649
3.21k
                  << fmt::format(
650
3.21k
                             "query_id:{}, "
651
3.21k
                             "Internal table:"
652
3.21k
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
653
3.21k
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
654
3.21k
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
655
3.21k
                             "lookup_row_data_ms:{}, file_types:[{}]; "
656
3.21k
                             "External table : init_reader_ms:{}, get_block_ms:{}, "
657
3.21k
                             "external_scan_range_cnt:{}",
658
3.21k
                             print_id(request.query_id()), stats.cached_pages_num,
659
3.21k
                             stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
660
3.21k
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
661
3.21k
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
662
3.21k
                             file_type_stats, external_init_reader_avg_ms,
663
3.21k
                             external_get_block_avg_ms, external_scan_range_cnt);
664
3.21k
        set_topn_lazy_materialization_file_cache_stats(
665
3.21k
                stats.file_cache_stats,
666
3.21k
                response->mutable_topn_lazy_materialization_file_cache_stats());
667
3.21k
    }
668
669
3.21k
    return Status::OK();
670
3.21k
}
671
672
Status RowIdStorageReader::read_batch_doris_format_row(
673
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
674
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id, Block& result_block,
675
        OlapReaderStatistics& stats, int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms,
676
        int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms,
677
962
        io::FileCacheMissPolicy file_cache_miss_policy) {
678
962
    if (result_block.is_empty_column()) [[likely]] {
679
962
        result_block = Block(slots, request_block_desc.row_id_size());
680
962
    }
681
962
    TabletSchema full_read_schema;
682
5.90k
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
683
5.90k
        full_read_schema.append_column(TabletColumn(column_pb));
684
5.90k
    }
685
686
962
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
687
962
    std::unordered_map<SegKey, SegItem, HashOfSegKey> seg_map;
688
962
    std::string row_store_buffer;
689
962
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
690
962
    if (request_block_desc.fetch_row_store()) {
691
3.36k
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
692
3.15k
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
693
3.15k
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
694
3.15k
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
695
3.15k
        }
696
213
    }
697
698
    // Phase 1: Group all row_ids by their (tablet_id, rowset_id, segment_id) key.
699
    // Unlike the old code which only batched adjacent rows with the same file_id,
700
    // this merges non-contiguous same-segment requests into a single batch,
701
    // maximizing the number of rows read per seek_and_read_by_rowid call.
702
962
    std::vector<DorisFormatReadBatch> scan_batches;
703
962
    std::unordered_map<SegKey, size_t, HashOfSegKey> batch_idx_by_seg;
704
    // (batch_idx, position_in_batch) for each row in the original request.
705
962
    std::vector<std::pair<size_t, size_t>> row_id_block_idx(request_block_desc.row_id_size());
706
11.1k
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
707
10.1k
        auto file_id = request_block_desc.file_id(j);
708
10.1k
        auto file_mapping = id_file_map->get_file_mapping(file_id);
709
10.1k
        if (!file_mapping) {
710
0
            return Status::InternalError(
711
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
712
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
713
0
        }
714
715
        // Derive segment key and group by it — rows from the same segment are batched together
716
        // even if they are interleaved with rows from other segments in the request.
717
10.1k
        auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
718
10.1k
        SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
719
10.1k
        auto [it, inserted] = batch_idx_by_seg.emplace(seg_key, scan_batches.size());
720
10.1k
        if (inserted) {
721
            // First time seeing this segment, create a new batch for it.
722
3.75k
            scan_batches.emplace_back();
723
3.75k
            scan_batches.back().file_mapping = file_mapping;
724
3.75k
        }
725
        // Record (row_id, original_request_index) for later sorting and scattering.
726
10.1k
        scan_batches[it->second].row_ids_with_positions.emplace_back(request_block_desc.row_id(j),
727
10.1k
                                                                     j);
728
10.1k
    }
729
730
    // Phase 2: For each segment, sort row_ids ascending (required by ColumnIterator),
731
    // deduplicate, then read all rows in a single batch call.
732
962
    std::vector<Block> scan_blocks(scan_batches.size());
733
4.71k
    for (size_t batch_idx = 0; batch_idx < scan_batches.size(); ++batch_idx) {
734
3.75k
        auto& scan_batch = scan_batches[batch_idx];
735
3.75k
        auto& row_ids_with_positions = scan_batch.row_ids_with_positions;
736
3.75k
        std::sort(row_ids_with_positions.begin(), row_ids_with_positions.end(),
737
19.3k
                  [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; });
738
739
        // Column iterators read rowids monotonically. Deduplicate consecutive identical row_ids
740
        // (different file_ids may map to the same row), then scatter rows back to their original
741
        // request positions.
742
3.75k
        std::vector<uint32_t> row_ids;
743
3.75k
        row_ids.reserve(row_ids_with_positions.size());
744
745
        // Also builds the scatter map: row_id_block_idx[original_request_idx] ->
746
        // (batch_idx, deduplicated_position_in_batch).
747
10.1k
        for (const auto& [row_id, result_idx] : row_ids_with_positions) {
748
10.1k
            if (row_ids.empty() || row_ids.back() != row_id) {
749
9.94k
                row_ids.emplace_back(row_id);
750
9.94k
            }
751
10.1k
            row_id_block_idx[result_idx] = std::make_pair(batch_idx, row_ids.size() - 1);
752
10.1k
        }
753
754
3.75k
        scan_blocks[batch_idx] = Block(slots, row_ids.size());
755
3.75k
        RETURN_IF_ERROR(read_doris_format_row(
756
3.75k
                id_file_map, scan_batch.file_mapping, row_ids, slots, full_read_schema,
757
3.75k
                row_store_read_struct, stats, acquire_tablet_ms, acquire_rowsets_ms,
758
3.75k
                acquire_segments_ms, lookup_row_data_ms, seg_map, iterator_map,
759
3.75k
                file_cache_miss_policy, scan_blocks[batch_idx]));
760
3.75k
    }
761
762
962
    scatter_scan_blocks_to_result_block(row_id_block_idx, scan_blocks, result_block);
763
764
962
    return Status::OK();
765
962
}
766
767
const std::string RowIdStorageReader::ScannersRunningTimeProfile = "ScannersRunningTime";
768
const std::string RowIdStorageReader::InitReaderAvgTimeProfile = "InitReaderAvgTime";
769
const std::string RowIdStorageReader::GetBlockAvgTimeProfile = "GetBlockAvgTime";
770
const std::string RowIdStorageReader::FileReadLinesProfile = "FileReadLines";
771
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOCount =
772
        "TopNLazyMaterializationSecondPhaseLocalIOCount";
773
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOBytes =
774
        "TopNLazyMaterializationSecondPhaseLocalIOBytes";
775
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOCount =
776
        "TopNLazyMaterializationSecondPhaseRemoteIOCount";
777
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOBytes =
778
        "TopNLazyMaterializationSecondPhaseRemoteIOBytes";
779
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSkipCacheIOCount =
780
        "TopNLazyMaterializationSecondPhaseSkipCacheIOCount";
781
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheBytes =
782
        "TopNLazyMaterializationSecondPhaseWriteCacheBytes";
783
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOTime =
784
        "TopNLazyMaterializationSecondPhaseLocalIOTime";
785
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOTime =
786
        "TopNLazyMaterializationSecondPhaseRemoteIOTime";
787
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheIOTime =
788
        "TopNLazyMaterializationSecondPhaseWriteCacheIOTime";
789
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRowsRead =
790
        "TopNLazyMaterializationSecondPhaseRowsRead";
791
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSegmentsRead =
792
        "TopNLazyMaterializationSecondPhaseSegmentsRead";
793
794
Status RowIdStorageReader::read_external_row_from_file_mapping(
795
        size_t idx, const std::multimap<segment_v2::rowid_t, size_t>& row_ids,
796
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<SlotDescriptor>& slots,
797
        const TUniqueId& query_id, const std::shared_ptr<RuntimeState>& runtime_state,
798
        std::vector<Block>& scan_blocks, std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
799
        std::vector<RowIdStorageReader::ExternalFetchStatistics>& fetch_statistics,
800
        const TFileScanRangeParams& rpc_scan_params,
801
        const std::unordered_map<std::string, int>& colname_to_slot_id,
802
        std::atomic<int>& producer_count, size_t scan_rows_count,
803
        std::counting_semaphore<>& semaphore, std::condition_variable& cv, std::mutex& mtx,
804
3.20k
        TupleDescriptor& tuple_desc) {
805
3.20k
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
806
3.20k
    signal::set_signal_task_id(query_id);
807
808
3.20k
    std::list<int64_t> read_ids;
809
    //Generate an ordered list with the help of the orderliness of the map.
810
13.3k
    for (const auto& [row_id, result_block_idx] : row_ids) {
811
13.3k
        if (read_ids.empty() || read_ids.back() != row_id) {
812
11.1k
            read_ids.emplace_back(row_id);
813
11.1k
        }
814
13.3k
        row_id_block_idx[result_block_idx] = std::make_pair(idx, read_ids.size() - 1);
815
13.3k
    }
816
817
3.20k
    scan_blocks[idx] = Block(slots, read_ids.size());
818
819
3.20k
    auto& external_info = file_mapping->get_external_file_info();
820
3.20k
    auto& scan_range_desc = external_info.scan_range_desc;
821
822
    // Clear to avoid reading iceberg position delete file...
823
3.20k
    scan_range_desc.table_format_params.iceberg_params = TIcebergFileDesc {};
824
825
    // Clear to avoid reading hive transactional delete delta file...
826
3.20k
    scan_range_desc.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
827
828
3.20k
    std::unique_ptr<RuntimeProfile> sub_runtime_profile =
829
3.20k
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
830
3.20k
    {
831
3.20k
        std::unique_ptr<FileScanner> vfile_scanner_ptr =
832
3.20k
                FileScanner::create_unique(runtime_state.get(), sub_runtime_profile.get(),
833
3.20k
                                           &rpc_scan_params, &colname_to_slot_id, &tuple_desc);
834
835
3.20k
        RETURN_IF_ERROR(vfile_scanner_ptr->prepare_for_read_lines(scan_range_desc));
836
3.20k
        RETURN_IF_ERROR(vfile_scanner_ptr->read_lines_from_range(
837
3.20k
                scan_range_desc, read_ids, &scan_blocks[idx], external_info,
838
3.20k
                &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
839
3.20k
    }
840
841
3.20k
    auto file_read_bytes_counter =
842
3.20k
            sub_runtime_profile->get_counter(FileScanner::FileReadBytesProfile);
843
844
3.20k
    if (file_read_bytes_counter != nullptr) {
845
3.19k
        fetch_statistics[idx].file_read_bytes = PrettyPrinter::print(
846
3.19k
                file_read_bytes_counter->value(), file_read_bytes_counter->type());
847
3.19k
    }
848
849
3.20k
    auto file_read_times_counter =
850
3.20k
            sub_runtime_profile->get_counter(FileScanner::FileReadTimeProfile);
851
3.20k
    if (file_read_times_counter != nullptr) {
852
3.19k
        fetch_statistics[idx].file_read_times = PrettyPrinter::print(
853
3.19k
                file_read_times_counter->value(), file_read_times_counter->type());
854
3.19k
    }
855
856
3.20k
    semaphore.release();
857
3.20k
    if (++producer_count == scan_rows_count) {
858
2.02k
        std::lock_guard<std::mutex> lock(mtx);
859
2.02k
        cv.notify_one();
860
2.02k
    }
861
3.20k
    return Status::OK();
862
3.20k
}
863
864
Status RowIdStorageReader::read_batch_external_row(
865
        const uint64_t workload_group_id, const PRequestBlockDesc& request_block_desc,
866
        std::shared_ptr<IdFileMap> id_file_map, std::vector<SlotDescriptor>& slots,
867
        std::shared_ptr<FileMapping> first_file_mapping, const TUniqueId& query_id,
868
        Block& result_block, PRuntimeProfileTree* pprofile, int64_t* init_reader_avg_ms,
869
2.02k
        int64_t* get_block_avg_ms, size_t* scan_range_cnt) {
870
2.02k
    TFileScanRangeParams rpc_scan_params;
871
2.02k
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
872
2.02k
    std::unordered_map<std::string, int> colname_to_slot_id;
873
2.02k
    std::shared_ptr<RuntimeState> runtime_state = nullptr;
874
875
2.02k
    int max_file_scanners = 0;
876
2.02k
    {
877
2.02k
        if (result_block.is_empty_column()) [[likely]] {
878
2.02k
            result_block = Block(slots, request_block_desc.row_id_size());
879
2.02k
        }
880
881
2.02k
        auto& external_info = first_file_mapping->get_external_file_info();
882
2.02k
        int plan_node_id = external_info.plan_node_id;
883
2.02k
        const auto& first_scan_range_desc = external_info.scan_range_desc;
884
885
2.02k
        DCHECK(id_file_map->get_external_scan_params().contains(plan_node_id));
886
2.02k
        const auto* old_scan_params = &(id_file_map->get_external_scan_params().at(plan_node_id));
887
2.02k
        rpc_scan_params = *old_scan_params;
888
889
2.02k
        rpc_scan_params.required_slots.clear();
890
2.02k
        rpc_scan_params.column_idxs.clear();
891
2.02k
        rpc_scan_params.slot_name_to_schema_pos.clear();
892
893
2.02k
        std::set partition_name_set(first_scan_range_desc.columns_from_path_keys.begin(),
894
2.02k
                                    first_scan_range_desc.columns_from_path_keys.end());
895
10.7k
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
896
8.74k
            auto& slot = slots[slot_idx];
897
8.74k
            tuple_desc.add_slot(&slot);
898
8.74k
            colname_to_slot_id.emplace(slot.col_name(), slot.id());
899
8.74k
            TFileScanSlotInfo slot_info;
900
8.74k
            slot_info.slot_id = slot.id();
901
8.74k
            auto column_idx = request_block_desc.column_idxs(slot_idx);
902
8.74k
            if (partition_name_set.contains(slot.col_name())) {
903
                //This is partition column.
904
402
                slot_info.is_file_slot = false;
905
8.34k
            } else {
906
8.34k
                rpc_scan_params.column_idxs.emplace_back(column_idx);
907
8.34k
                slot_info.is_file_slot = true;
908
8.34k
            }
909
8.74k
            rpc_scan_params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
910
8.74k
            rpc_scan_params.required_slots.emplace_back(slot_info);
911
8.74k
            rpc_scan_params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
912
8.74k
        }
913
914
2.02k
        const auto& query_options = id_file_map->get_query_options();
915
2.02k
        const auto& query_globals = id_file_map->get_query_globals();
916
        /*
917
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
918
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
919
         *
920
         * To ensure the same behavior as the scan stage, I get query_options query_globals from id_file_map, then create runtime_state
921
         * and pass it to vfile_scanner so that the runtime_state information is the same as the scan stage and the behavior is also consistent.
922
         */
923
2.02k
        runtime_state = RuntimeState::create_shared(
924
2.02k
                query_id, -1, query_options, query_globals, ExecEnv::GetInstance(),
925
2.02k
                ExecEnv::GetInstance()->rowid_storage_reader_tracker());
926
927
2.02k
        max_file_scanners = id_file_map->get_max_file_scanners();
928
2.02k
    }
929
930
    // Hash(TFileRangeDesc) => { all the rows that need to be read and their positions in the result block. } +  file mapping
931
    // std::multimap<segment_v2::rowid_t, size_t> : The reason for using multimap is: may need the same row of data multiple times.
932
2.02k
    std::map<std::string,
933
2.02k
             std::pair<std::multimap<segment_v2::rowid_t, size_t>, std::shared_ptr<FileMapping>>>
934
2.02k
            scan_rows;
935
936
    // Block corresponding to the order of `scan_rows` map.
937
2.02k
    std::vector<Block> scan_blocks;
938
939
    // row_id (Indexing of vectors) => < In which block, which line in the block >
940
2.02k
    std::vector<std::pair<size_t, size_t>> row_id_block_idx;
941
942
    // Count the time/bytes it takes to read each TFileRangeDesc. (for profile)
943
2.02k
    std::vector<ExternalFetchStatistics> fetch_statistics;
944
945
13.3k
    auto hash_file_range = [](const TFileRangeDesc& file_range_desc) {
946
13.3k
        std::string value;
947
13.3k
        value.resize(file_range_desc.path.size() + sizeof(file_range_desc.start_offset));
948
13.3k
        auto* ptr = value.data();
949
950
13.3k
        memcpy(ptr, &file_range_desc.start_offset, sizeof(file_range_desc.start_offset));
951
13.3k
        ptr += sizeof(file_range_desc.start_offset);
952
13.3k
        memcpy(ptr, file_range_desc.path.data(), file_range_desc.path.size());
953
13.3k
        return value;
954
13.3k
    };
955
956
15.3k
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
957
13.3k
        auto file_id = request_block_desc.file_id(j);
958
13.3k
        auto file_mapping = id_file_map->get_file_mapping(file_id);
959
13.3k
        if (!file_mapping) {
960
0
            return Status::InternalError(
961
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
962
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
963
0
        }
964
965
13.3k
        const auto& external_info = file_mapping->get_external_file_info();
966
13.3k
        const auto& scan_range_desc = external_info.scan_range_desc;
967
968
13.3k
        auto scan_range_hash = hash_file_range(scan_range_desc);
969
13.3k
        if (scan_rows.contains(scan_range_hash)) {
970
10.1k
            scan_rows.at(scan_range_hash).first.emplace(request_block_desc.row_id(j), j);
971
10.1k
        } else {
972
3.20k
            std::multimap<segment_v2::rowid_t, size_t> tmp {{request_block_desc.row_id(j), j}};
973
3.20k
            scan_rows.emplace(scan_range_hash, std::make_pair(tmp, file_mapping));
974
3.20k
        }
975
13.3k
    }
976
977
2.02k
    scan_blocks.resize(scan_rows.size());
978
2.02k
    row_id_block_idx.resize(request_block_desc.row_id_size());
979
2.02k
    fetch_statistics.resize(scan_rows.size());
980
981
    // Get the workload group for subsequent scan task submission.
982
2.02k
    std::vector<uint64_t> workload_group_ids;
983
2.02k
    workload_group_ids.emplace_back(workload_group_id);
984
2.02k
    auto wg = ExecEnv::GetInstance()->workload_group_mgr()->get_group(workload_group_ids);
985
2.02k
    doris::TaskScheduler* exec_sched = nullptr;
986
2.02k
    ScannerScheduler* scan_sched = nullptr;
987
2.02k
    ScannerScheduler* remote_scan_sched = nullptr;
988
2.02k
    wg->get_query_scheduler(&exec_sched, &scan_sched, &remote_scan_sched);
989
2.02k
    DCHECK(remote_scan_sched);
990
991
2.02k
    int64_t scan_running_time = 0;
992
2.02k
    RETURN_IF_ERROR(scope_timer_run(
993
2.02k
            [&]() -> Status {
994
                // Make sure to insert data into result_block only after all scan tasks have been executed.
995
2.02k
                std::atomic<int> producer_count {0};
996
2.02k
                std::condition_variable cv;
997
2.02k
                std::mutex mtx;
998
999
                //semaphore: Limit the number of scan tasks submitted at one time
1000
2.02k
                std::counting_semaphore semaphore {max_file_scanners};
1001
1002
2.02k
                size_t idx = 0;
1003
2.02k
                for (const auto& [_, scan_info] : scan_rows) {
1004
2.02k
                    semaphore.acquire();
1005
2.02k
                    RETURN_IF_ERROR(remote_scan_sched->submit_scan_task(
1006
2.02k
                            SimplifiedScanTask(
1007
2.02k
                                    [&, idx, scan_info]() -> Status {
1008
2.02k
                                        const auto& [row_ids, file_mapping] = scan_info;
1009
2.02k
                                        return read_external_row_from_file_mapping(
1010
2.02k
                                                idx, row_ids, file_mapping, slots, query_id,
1011
2.02k
                                                runtime_state, scan_blocks, row_id_block_idx,
1012
2.02k
                                                fetch_statistics, rpc_scan_params,
1013
2.02k
                                                colname_to_slot_id, producer_count,
1014
2.02k
                                                scan_rows.size(), semaphore, cv, mtx, tuple_desc);
1015
2.02k
                                    },
1016
2.02k
                                    nullptr, nullptr),
1017
2.02k
                            fmt::format("{}-read_batch_external_row-{}", print_id(query_id), idx)));
1018
2.02k
                    idx++;
1019
2.02k
                }
1020
1021
2.02k
                {
1022
2.02k
                    std::unique_lock<std::mutex> lock(mtx);
1023
2.02k
                    cv.wait(lock, [&] { return producer_count == scan_rows.size(); });
1024
2.02k
                }
1025
2.02k
                return Status::OK();
1026
2.02k
            },
1027
2.02k
            &scan_running_time));
1028
1029
2.02k
    scatter_scan_blocks_to_result_block(row_id_block_idx, scan_blocks, result_block);
1030
1031
    // Statistical runtime profile information.
1032
2.02k
    std::unique_ptr<RuntimeProfile> runtime_profile =
1033
2.02k
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
1034
2.02k
    {
1035
2.02k
        runtime_profile->add_info_string(ScannersRunningTimeProfile,
1036
2.02k
                                         std::to_string(scan_running_time) + "ms");
1037
2.02k
        fmt::memory_buffer file_read_lines_buffer;
1038
2.02k
        format_to(file_read_lines_buffer, "[");
1039
2.02k
        fmt::memory_buffer file_read_bytes_buffer;
1040
2.02k
        format_to(file_read_bytes_buffer, "[");
1041
2.02k
        fmt::memory_buffer file_read_times_buffer;
1042
2.02k
        format_to(file_read_times_buffer, "[");
1043
1044
2.02k
        size_t idx = 0;
1045
3.20k
        for (const auto& [_, scan_info] : scan_rows) {
1046
3.20k
            format_to(file_read_lines_buffer, "{}, ", scan_info.first.size());
1047
3.20k
            *init_reader_avg_ms = fetch_statistics[idx].init_reader_ms;
1048
3.20k
            *get_block_avg_ms += fetch_statistics[idx].get_block_ms;
1049
3.20k
            format_to(file_read_bytes_buffer, "{}, ", fetch_statistics[idx].file_read_bytes);
1050
3.20k
            format_to(file_read_times_buffer, "{}, ", fetch_statistics[idx].file_read_times);
1051
3.20k
            idx++;
1052
3.20k
        }
1053
1054
2.02k
        format_to(file_read_lines_buffer, "]");
1055
2.02k
        format_to(file_read_bytes_buffer, "]");
1056
2.02k
        format_to(file_read_times_buffer, "]");
1057
1058
2.02k
        *init_reader_avg_ms /= fetch_statistics.size();
1059
2.02k
        *get_block_avg_ms /= fetch_statistics.size();
1060
2.02k
        runtime_profile->add_info_string(InitReaderAvgTimeProfile,
1061
2.02k
                                         std::to_string(*init_reader_avg_ms) + "ms");
1062
2.02k
        runtime_profile->add_info_string(GetBlockAvgTimeProfile,
1063
2.02k
                                         std::to_string(*init_reader_avg_ms) + "ms");
1064
2.02k
        runtime_profile->add_info_string(FileReadLinesProfile,
1065
2.02k
                                         fmt::to_string(file_read_lines_buffer));
1066
2.02k
        runtime_profile->add_info_string(FileScanner::FileReadBytesProfile,
1067
2.02k
                                         fmt::to_string(file_read_bytes_buffer));
1068
2.02k
        runtime_profile->add_info_string(FileScanner::FileReadTimeProfile,
1069
2.02k
                                         fmt::to_string(file_read_times_buffer));
1070
2.02k
    }
1071
1072
2.02k
    runtime_profile->to_proto(pprofile, 2);
1073
1074
2.02k
    *scan_range_cnt = scan_rows.size();
1075
1076
2.02k
    return Status::OK();
1077
2.02k
}
1078
1079
Status RowIdStorageReader::read_doris_format_row(
1080
        const std::shared_ptr<IdFileMap>& id_file_map,
1081
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<uint32_t>& row_ids,
1082
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
1083
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
1084
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
1085
        int64_t* lookup_row_data_ms, std::unordered_map<SegKey, SegItem, HashOfSegKey>& seg_map,
1086
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
1087
3.75k
        io::FileCacheMissPolicy file_cache_miss_policy, Block& result_block) {
1088
3.75k
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
1089
3.75k
    SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
1090
1091
3.75k
    BaseTabletSPtr tablet;
1092
3.75k
    BetaRowsetSharedPtr rowset;
1093
3.75k
    SegmentSharedPtr segment;
1094
3.75k
    if (seg_map.find(seg_key) == seg_map.end()) {
1095
3.75k
        tablet = scope_timer_run(
1096
3.75k
                [&]() {
1097
3.75k
                    auto res = ExecEnv::get_tablet(tablet_id);
1098
3.75k
                    return !res.has_value() ? nullptr
1099
3.75k
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
1100
3.75k
                },
1101
3.75k
                acquire_tablet_ms);
1102
3.75k
        if (!tablet) {
1103
0
            return Status::InternalError(
1104
0
                    "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1105
0
                    "row_id: {}",
1106
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1107
0
                    row_ids[0]);
1108
0
        }
1109
1110
3.75k
        rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
1111
3.75k
                [&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
1112
3.75k
                acquire_rowsets_ms));
1113
3.75k
        if (!rowset) {
1114
0
            return Status::InternalError(
1115
0
                    "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1116
0
                    "row_id: {}",
1117
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1118
0
                    row_ids[0]);
1119
0
        }
1120
1121
3.75k
        SegmentCacheHandle segment_cache;
1122
3.75k
        RETURN_IF_ERROR(scope_timer_run(
1123
3.75k
                [&]() {
1124
3.75k
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
1125
3.75k
                },
1126
3.75k
                acquire_segments_ms));
1127
1128
3.75k
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
1129
3.75k
                               segment_cache.get_segments().cend(),
1130
3.75k
                               [segment_id](const segment_v2::SegmentSharedPtr& seg) {
1131
3.75k
                                   return seg->id() == segment_id;
1132
3.75k
                               });
1133
3.75k
        if (it == segment_cache.get_segments().end()) {
1134
0
            return Status::InternalError(
1135
0
                    "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1136
0
                    "row_id: {}",
1137
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1138
0
                    row_ids[0]);
1139
0
        }
1140
3.75k
        segment = *it;
1141
3.75k
        seg_map[seg_key] = SegItem {.tablet = tablet, .rowset = rowset, .segment = segment};
1142
3.75k
    } else {
1143
0
        auto& seg_item = seg_map[seg_key];
1144
0
        tablet = seg_item.tablet;
1145
0
        rowset = seg_item.rowset;
1146
0
        segment = seg_item.segment;
1147
0
    }
1148
1149
    // if row_store_read_struct not empty, means the line we should read from row_store
1150
3.75k
    if (!row_store_read_struct.default_values.empty()) {
1151
1.33k
        if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
1152
0
            return Status::InternalError("Tablet {} does not have row store for all columns",
1153
0
                                         tablet->tablet_id());
1154
0
        }
1155
1.33k
        auto result_columns_guard = result_block.mutate_columns_scoped();
1156
1.33k
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
1157
1.33k
        io::IOContext io_ctx;
1158
1.33k
        io_ctx.reader_type = ReaderType::READER_QUERY;
1159
1.33k
        io_ctx.file_cache_stats = &stats.file_cache_stats;
1160
1.33k
        io_ctx.file_cache_miss_policy = file_cache_miss_policy;
1161
4.44k
        for (auto row_id : row_ids) {
1162
4.44k
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_id));
1163
4.44k
            row_store_read_struct.row_store_buffer.clear();
1164
4.44k
            RETURN_IF_ERROR(scope_timer_run(
1165
4.44k
                    [&]() {
1166
4.44k
                        return tablet->lookup_row_data({}, loc, rowset, stats,
1167
4.44k
                                                       row_store_read_struct.row_store_buffer,
1168
4.44k
                                                       false, &io_ctx);
1169
4.44k
                    },
1170
4.44k
                    lookup_row_data_ms));
1171
1172
4.44k
            RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
1173
4.44k
                    row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
1174
4.44k
                    row_store_read_struct.row_store_buffer.size(),
1175
4.44k
                    row_store_read_struct.col_uid_to_idx, result_columns,
1176
4.44k
                    row_store_read_struct.default_values, {}));
1177
4.44k
        }
1178
2.41k
    } else {
1179
15.2k
        for (int x = 0; x < slots.size(); ++x) {
1180
12.8k
            auto column_guard = result_block.mutate_column_scoped(x);
1181
12.8k
            MutableColumnPtr& column = column_guard.mutable_column();
1182
12.8k
            IteratorKey iterator_key {.tablet_id = tablet_id,
1183
12.8k
                                      .rowset_id = rowset_id,
1184
12.8k
                                      .segment_id = segment_id,
1185
12.8k
                                      .slot_id = slots[x].id()};
1186
12.8k
            IteratorItem& iterator_item = iterator_map[iterator_key];
1187
12.8k
            if (iterator_item.segment == nullptr) {
1188
12.8k
                iterator_map[iterator_key].segment = segment;
1189
12.8k
                iterator_item.storage_read_options.stats = &stats;
1190
12.8k
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
1191
12.8k
                iterator_item.storage_read_options.io_ctx.file_cache_miss_policy =
1192
12.8k
                        file_cache_miss_policy;
1193
12.8k
            }
1194
12.8k
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
1195
12.8k
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
1196
12.8k
                    full_read_schema, &slots[x], row_ids, column,
1197
12.8k
                    iterator_item.storage_read_options, iterator_item.iterator));
1198
12.8k
        }
1199
2.41k
    }
1200
3.75k
    return Status::OK();
1201
3.75k
}
1202
1203
} // namespace doris