Coverage Report

Created: 2026-08-02 21:00

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.16k
        const io::FileCacheStatistics& stats, PTopNLazyMaterializationFileCacheStats* pstats) {
81
3.16k
    pstats->set_local_io_count(stats.num_local_io_total);
82
3.16k
    pstats->set_local_io_bytes(stats.bytes_read_from_local);
83
3.16k
    pstats->set_remote_io_count(stats.num_remote_io_total);
84
3.16k
    pstats->set_remote_io_bytes(stats.bytes_read_from_remote);
85
3.16k
    pstats->set_skip_cache_io_count(stats.num_skip_cache_io_total);
86
3.16k
    pstats->set_write_cache_bytes(stats.bytes_write_into_cache);
87
3.16k
    pstats->set_local_io_time(stats.local_io_timer);
88
3.16k
    pstats->set_remote_io_time(stats.remote_io_timer);
89
3.16k
    pstats->set_write_cache_io_time(stats.write_cache_io_timer);
90
3.16k
}
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.9k
    bool operator==(const IteratorKey& rhs) const {
290
12.9k
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
291
12.9k
               segment_id == rhs.segment_id && slot_id == rhs.slot_id;
292
12.9k
    }
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.31k
    bool operator==(const SegKey& rhs) const {
302
6.31k
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
303
6.31k
               segment_id == rhs.segment_id;
304
6.31k
    }
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.8k
    size_t operator()(const IteratorKey& key) const {
321
25.8k
        size_t seed = 0;
322
25.8k
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
323
25.8k
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
324
25.8k
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
325
25.8k
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
326
25.8k
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
327
25.8k
        seed = HashUtil::hash64(&key.slot_id, sizeof(key.slot_id), seed);
328
25.8k
        return seed;
329
25.8k
    }
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.9k
                                  StorageReadOptions& storage_read_options) {
341
12.9k
    int32_t unique_id = slot.col_unique_id();
342
12.9k
    const int field_index =
343
18.4E
            unique_id >= 0 ? schema.field_index(unique_id) : schema.field_index(slot.col_name());
344
12.9k
    if (field_index >= 0) {
345
12.9k
        const auto& column = schema.column(field_index);
346
12.9k
        unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
347
12.9k
    }
348
12.9k
    if (unique_id < 0) {
349
0
        return;
350
0
    }
351
352
12.9k
    if (!slot.all_access_paths().empty()) {
353
1.51k
        storage_read_options.all_access_paths[unique_id] = slot.all_access_paths();
354
1.51k
    }
355
356
12.9k
    if (!slot.predicate_access_paths().empty()) {
357
0
        storage_read_options.predicate_access_paths[unique_id] = slot.predicate_access_paths();
358
0
    }
359
12.9k
}
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.4k
    for (size_t column_id = 0; column_id < result_block.columns(); ++column_id) {
381
14.4k
        auto dst_col_guard = result_block.mutate_column_scoped(column_id);
382
14.4k
        MutableColumnPtr& dst_col = dst_col_guard.mutable_column();
383
384
14.4k
        std::vector<const IColumn*> scan_src_columns;
385
14.4k
        scan_src_columns.reserve(row_id_block_idx.size());
386
14.4k
        std::vector<size_t> scan_positions;
387
14.4k
        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.4k
        dst_col->insert_from_multi_column(scan_src_columns, scan_positions);
396
14.4k
    }
397
2.98k
}
398
399
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequest& request,
400
2
                                          PMultiGetResponse* response) {
401
    // read from storage engine row id by row id
402
2
    OlapReaderStatistics stats;
403
2
    Block result_block;
404
2
    int64_t acquire_tablet_ms = 0;
405
2
    int64_t acquire_rowsets_ms = 0;
406
2
    int64_t acquire_segments_ms = 0;
407
2
    int64_t lookup_row_data_ms = 0;
408
409
    // init desc
410
2
    std::vector<SlotDescriptor> slots;
411
2
    slots.reserve(request.slots().size());
412
4
    for (const auto& pslot : request.slots()) {
413
4
        slots.push_back(SlotDescriptor(pslot));
414
4
    }
415
416
    // init read schema
417
2
    TabletSchema full_read_schema;
418
2
    for (const ColumnPB& column_pb : request.column_desc()) {
419
2
        full_read_schema.append_column(TabletColumn(column_pb));
420
2
    }
421
422
2
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
423
    // read row by row
424
8
    for (int i = 0; i < request.row_locs_size(); ++i) {
425
6
        const auto& row_loc = request.row_locs(i);
426
6
        MonotonicStopWatch watch;
427
6
        watch.start();
428
6
        BaseTabletSPtr tablet = scope_timer_run(
429
6
                [&]() {
430
6
                    auto res = ExecEnv::get_tablet(row_loc.tablet_id(), nullptr, true);
431
6
                    return !res.has_value() ? nullptr
432
6
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
433
6
                },
434
6
                &acquire_tablet_ms);
435
6
        RowsetId rowset_id;
436
6
        rowset_id.init(row_loc.rowset_id());
437
6
        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
6
        BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
442
6
                [&]() {
443
6
                    return ExecEnv::GetInstance()->storage_engine().get_quering_rowset(rowset_id);
444
6
                },
445
6
                &acquire_rowsets_ms));
446
6
        if (!rowset) {
447
0
            LOG(INFO) << "no such rowset " << rowset_id;
448
0
            continue;
449
0
        }
450
6
        size_t row_size = 0;
451
6
        Defer _defer([&]() {
452
6
            LOG_EVERY_N(INFO, 100)
453
1
                    << "multiget_data single_row, cost(us):" << watch.elapsed_time() / 1000
454
1
                    << ", row_size:" << row_size;
455
6
            *response->add_row_locs() = row_loc;
456
6
        });
457
        // TODO: supoort session variable enable_page_cache and disable_file_cache if necessary.
458
6
        SegmentCacheHandle segment_cache;
459
6
        RETURN_IF_ERROR(scope_timer_run(
460
6
                [&]() {
461
6
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
462
6
                },
463
6
                &acquire_segments_ms));
464
        // find segment
465
6
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
466
6
                               segment_cache.get_segments().cend(),
467
6
                               [&row_loc](const segment_v2::SegmentSharedPtr& seg) {
468
6
                                   return seg->id() == row_loc.segment_id();
469
6
                               });
470
6
        if (it == segment_cache.get_segments().end()) {
471
0
            continue;
472
0
        }
473
6
        segment_v2::SegmentSharedPtr segment = *it;
474
6
        GlobalRowLoacation row_location(row_loc.tablet_id(), rowset->rowset_id(),
475
6
                                        cast_set<uint32_t>(row_loc.segment_id()),
476
6
                                        cast_set<uint32_t>(row_loc.ordinal_id()));
477
        // fetch by row store, more effcient way
478
6
        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
6
        if (result_block.is_empty_column()) {
494
2
            result_block = Block(slots, request.row_locs().size());
495
2
        }
496
6
        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
18
        for (int x = 0; x < slots.size(); ++x) {
502
12
            std::vector<segment_v2::rowid_t> row_ids {
503
12
                    static_cast<segment_v2::rowid_t>(row_loc.ordinal_id())};
504
            // The scoped mutation republishes a potentially replaced V2 column when the reader
505
            // transfers ownership of its first assembled batch.
506
12
            auto column_guard = result_block.mutate_column_scoped(x);
507
12
            MutableColumnPtr& column = column_guard.mutable_column();
508
12
            IteratorKey iterator_key {.tablet_id = tablet->tablet_id(),
509
12
                                      .rowset_id = rowset_id,
510
12
                                      .segment_id = row_loc.segment_id(),
511
12
                                      .slot_id = slots[x].id()};
512
12
            IteratorItem& iterator_item = iterator_map[iterator_key];
513
12
            if (iterator_item.segment == nullptr) {
514
                // hold the reference
515
4
                iterator_map[iterator_key].segment = segment;
516
4
                iterator_item.storage_read_options.stats = &stats;
517
4
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
518
4
            }
519
12
            segment = iterator_item.segment;
520
12
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
521
12
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
522
12
                    full_read_schema, &slots[x], row_ids, column,
523
12
                    iterator_item.storage_read_options, iterator_item.iterator));
524
12
        }
525
6
    }
526
    // serialize block if not empty
527
2
    if (!result_block.is_empty_column()) {
528
2
        VLOG_DEBUG << "dump block:" << result_block.dump_data(0, 10)
529
0
                   << ", be_exec_version:" << request.be_exec_version();
530
2
        [[maybe_unused]] size_t compressed_size = 0;
531
2
        [[maybe_unused]] size_t uncompressed_size = 0;
532
2
        [[maybe_unused]] int64_t compress_time = 0;
533
2
        int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
534
2
        RETURN_IF_ERROR(result_block.serialize(be_exec_version, response->mutable_block(),
535
2
                                               &uncompressed_size, &compressed_size, &compress_time,
536
2
                                               segment_v2::CompressionTypePB::LZ4));
537
2
    }
538
539
2
    LOG(INFO) << "Query stats: "
540
2
              << fmt::format(
541
2
                         "query_id:{}, "
542
2
                         "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
543
2
                         "io_latency:{}ns, "
544
2
                         "uncompressed_bytes_read:{},"
545
2
                         "bytes_read:{},"
546
2
                         "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
547
2
                         "lookup_row_data_ms:{}",
548
2
                         print_id(request.query_id()), stats.cached_pages_num,
549
2
                         stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
550
2
                         stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
551
2
                         acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms);
552
2
    return Status::OK();
553
2
}
554
555
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequestV2& request,
556
3.16k
                                          PMultiGetResponseV2* response) {
557
3.16k
    if (request.request_block_descs_size()) {
558
3.16k
        auto tquery_id = ((UniqueId)request.query_id()).to_thrift();
559
        // todo: use mutableBlock instead of block
560
3.16k
        std::vector<Block> result_blocks(request.request_block_descs_size());
561
562
3.16k
        OlapReaderStatistics stats;
563
3.16k
        int64_t acquire_tablet_ms = 0;
564
3.16k
        int64_t acquire_rowsets_ms = 0;
565
3.16k
        int64_t acquire_segments_ms = 0;
566
3.16k
        int64_t lookup_row_data_ms = 0;
567
568
3.16k
        int64_t external_init_reader_avg_ms = 0;
569
3.16k
        int64_t external_get_block_avg_ms = 0;
570
3.16k
        size_t external_scan_range_cnt = 0;
571
572
3.16k
        const auto file_cache_miss_policy =
573
3.16k
                request.file_cache_remote_only_on_miss()
574
3.16k
                        ? io::FileCacheMissPolicy::REMOTE_ONLY_ON_MISS
575
3.16k
                        : io::FileCacheMissPolicy::READ_THROUGH_AND_WRITE_BACK;
576
577
        // Add counters for different file mapping types
578
3.16k
        std::unordered_map<FileMappingType, int64_t> file_type_counts;
579
580
3.16k
        auto id_file_map =
581
3.16k
                ExecEnv::GetInstance()->get_id_manager()->get_id_file_map(request.query_id());
582
        // if id_file_map is null, means the BE not have scan range, just return ok
583
3.16k
        if (!id_file_map) {
584
            // padding empty block to response
585
0
            LOG(INFO) << "id_file_map not found for query_id: " << print_id(request.query_id());
586
0
            for (int i = 0; i < request.request_block_descs_size(); ++i) {
587
0
                response->add_blocks();
588
0
            }
589
0
            return Status::OK();
590
0
        }
591
592
6.46k
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
593
3.29k
            const auto& request_block_desc = request.request_block_descs(i);
594
3.29k
            PMultiGetBlockV2* pblock = response->add_blocks();
595
3.29k
            if (request_block_desc.row_id_size() >= 1) {
596
                // Since this block belongs to the same table, we only need to take the first type for judgment.
597
2.98k
                auto first_file_id = request_block_desc.file_id(0);
598
2.98k
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
599
2.98k
                if (!first_file_mapping) {
600
0
                    return Status::InternalError(
601
0
                            "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
602
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
603
0
                            first_file_id);
604
0
                }
605
2.98k
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
606
607
                // prepare slots to build block
608
2.98k
                std::vector<SlotDescriptor> slots;
609
2.98k
                slots.reserve(request_block_desc.slots_size());
610
14.4k
                for (const auto& pslot : request_block_desc.slots()) {
611
14.4k
                    slots.push_back(SlotDescriptor(pslot));
612
14.4k
                }
613
2.98k
                try {
614
2.98k
                    if (first_file_mapping->type == FileMappingType::INTERNAL) {
615
969
                        RETURN_IF_ERROR(read_batch_doris_format_row(
616
969
                                request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
617
969
                                stats, &acquire_tablet_ms, &acquire_rowsets_ms,
618
969
                                &acquire_segments_ms, &lookup_row_data_ms, file_cache_miss_policy));
619
2.01k
                    } else {
620
2.01k
                        RETURN_IF_ERROR(read_batch_external_row(
621
2.01k
                                request.wg_id(), request_block_desc, id_file_map, slots,
622
2.01k
                                first_file_mapping, tquery_id, result_blocks[i],
623
2.01k
                                pblock->mutable_profile(), &external_init_reader_avg_ms,
624
2.01k
                                &external_get_block_avg_ms, &external_scan_range_cnt));
625
2.01k
                    }
626
2.98k
                } catch (const Exception& e) {
627
0
                    return Status::Error<false>(e.code(), "Row id fetch failed because {}",
628
0
                                                e.what());
629
0
                }
630
2.98k
            }
631
632
3.29k
            [[maybe_unused]] size_t compressed_size = 0;
633
3.29k
            [[maybe_unused]] size_t uncompressed_size = 0;
634
3.29k
            [[maybe_unused]] int64_t compress_time = 0;
635
3.29k
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
636
3.29k
            RETURN_IF_ERROR(result_blocks[i].serialize(
637
3.29k
                    be_exec_version, pblock->mutable_block(), &uncompressed_size, &compressed_size,
638
3.29k
                    &compress_time, segment_v2::CompressionTypePB::LZ4));
639
3.29k
        }
640
641
        // Build file type statistics string
642
3.16k
        std::string file_type_stats;
643
3.16k
        for (const auto& [type, count] : file_type_counts) {
644
2.86k
            if (!file_type_stats.empty()) {
645
0
                file_type_stats += ", ";
646
0
            }
647
2.86k
            file_type_stats += fmt::format("{}:{}", type, count);
648
2.86k
        }
649
650
3.16k
        LOG(INFO) << "Query stats: "
651
3.16k
                  << fmt::format(
652
3.16k
                             "query_id:{}, "
653
3.16k
                             "Internal table:"
654
3.16k
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
655
3.16k
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
656
3.16k
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
657
3.16k
                             "lookup_row_data_ms:{}, file_types:[{}]; "
658
3.16k
                             "External table : init_reader_ms:{}, get_block_ms:{}, "
659
3.16k
                             "external_scan_range_cnt:{}",
660
3.16k
                             print_id(request.query_id()), stats.cached_pages_num,
661
3.16k
                             stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
662
3.16k
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
663
3.16k
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
664
3.16k
                             file_type_stats, external_init_reader_avg_ms,
665
3.16k
                             external_get_block_avg_ms, external_scan_range_cnt);
666
3.16k
        set_topn_lazy_materialization_file_cache_stats(
667
3.16k
                stats.file_cache_stats,
668
3.16k
                response->mutable_topn_lazy_materialization_file_cache_stats());
669
3.16k
    }
670
671
3.16k
    return Status::OK();
672
3.16k
}
673
674
Status RowIdStorageReader::read_batch_doris_format_row(
675
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
676
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id, Block& result_block,
677
        OlapReaderStatistics& stats, int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms,
678
        int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms,
679
969
        io::FileCacheMissPolicy file_cache_miss_policy) {
680
969
    if (result_block.is_empty_column()) [[likely]] {
681
969
        result_block = Block(slots, request_block_desc.row_id_size());
682
969
    }
683
969
    TabletSchema full_read_schema;
684
5.83k
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
685
5.83k
        full_read_schema.append_column(TabletColumn(column_pb));
686
5.83k
    }
687
688
969
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
689
969
    std::unordered_map<SegKey, SegItem, HashOfSegKey> seg_map;
690
969
    std::string row_store_buffer;
691
969
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
692
969
    if (request_block_desc.fetch_row_store()) {
693
3.40k
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
694
3.18k
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
695
3.18k
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
696
3.18k
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
697
3.18k
        }
698
216
    }
699
700
    // Phase 1: Group all row_ids by their (tablet_id, rowset_id, segment_id) key.
701
    // Unlike the old code which only batched adjacent rows with the same file_id,
702
    // this merges non-contiguous same-segment requests into a single batch,
703
    // maximizing the number of rows read per seek_and_read_by_rowid call.
704
969
    std::vector<DorisFormatReadBatch> scan_batches;
705
969
    std::unordered_map<SegKey, size_t, HashOfSegKey> batch_idx_by_seg;
706
    // (batch_idx, position_in_batch) for each row in the original request.
707
969
    std::vector<std::pair<size_t, size_t>> row_id_block_idx(request_block_desc.row_id_size());
708
11.0k
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
709
10.0k
        auto file_id = request_block_desc.file_id(j);
710
10.0k
        auto file_mapping = id_file_map->get_file_mapping(file_id);
711
10.0k
        if (!file_mapping) {
712
0
            return Status::InternalError(
713
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
714
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
715
0
        }
716
717
        // Derive segment key and group by it — rows from the same segment are batched together
718
        // even if they are interleaved with rows from other segments in the request.
719
10.0k
        auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
720
10.0k
        SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
721
10.0k
        auto [it, inserted] = batch_idx_by_seg.emplace(seg_key, scan_batches.size());
722
10.0k
        if (inserted) {
723
            // First time seeing this segment, create a new batch for it.
724
3.77k
            scan_batches.emplace_back();
725
3.77k
            scan_batches.back().file_mapping = file_mapping;
726
3.77k
        }
727
        // Record (row_id, original_request_index) for later sorting and scattering.
728
10.0k
        scan_batches[it->second].row_ids_with_positions.emplace_back(request_block_desc.row_id(j),
729
10.0k
                                                                     j);
730
10.0k
    }
731
732
    // Phase 2: For each segment, sort row_ids ascending (required by ColumnIterator),
733
    // deduplicate, then read all rows in a single batch call.
734
969
    std::vector<Block> scan_blocks(scan_batches.size());
735
4.74k
    for (size_t batch_idx = 0; batch_idx < scan_batches.size(); ++batch_idx) {
736
3.77k
        auto& scan_batch = scan_batches[batch_idx];
737
3.77k
        auto& row_ids_with_positions = scan_batch.row_ids_with_positions;
738
3.77k
        std::sort(row_ids_with_positions.begin(), row_ids_with_positions.end(),
739
18.9k
                  [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; });
740
741
        // Column iterators read rowids monotonically. Deduplicate consecutive identical row_ids
742
        // (different file_ids may map to the same row), then scatter rows back to their original
743
        // request positions.
744
3.77k
        std::vector<uint32_t> row_ids;
745
3.77k
        row_ids.reserve(row_ids_with_positions.size());
746
747
        // Also builds the scatter map: row_id_block_idx[original_request_idx] ->
748
        // (batch_idx, deduplicated_position_in_batch).
749
10.0k
        for (const auto& [row_id, result_idx] : row_ids_with_positions) {
750
10.0k
            if (row_ids.empty() || row_ids.back() != row_id) {
751
9.87k
                row_ids.emplace_back(row_id);
752
9.87k
            }
753
10.0k
            row_id_block_idx[result_idx] = std::make_pair(batch_idx, row_ids.size() - 1);
754
10.0k
        }
755
756
3.77k
        scan_blocks[batch_idx] = Block(slots, row_ids.size());
757
3.77k
        RETURN_IF_ERROR(read_doris_format_row(
758
3.77k
                id_file_map, scan_batch.file_mapping, row_ids, slots, full_read_schema,
759
3.77k
                row_store_read_struct, stats, acquire_tablet_ms, acquire_rowsets_ms,
760
3.77k
                acquire_segments_ms, lookup_row_data_ms, seg_map, iterator_map,
761
3.77k
                file_cache_miss_policy, scan_blocks[batch_idx]));
762
3.77k
    }
763
764
969
    scatter_scan_blocks_to_result_block(row_id_block_idx, scan_blocks, result_block);
765
766
969
    return Status::OK();
767
969
}
768
769
const std::string RowIdStorageReader::ScannersRunningTimeProfile = "ScannersRunningTime";
770
const std::string RowIdStorageReader::InitReaderAvgTimeProfile = "InitReaderAvgTime";
771
const std::string RowIdStorageReader::GetBlockAvgTimeProfile = "GetBlockAvgTime";
772
const std::string RowIdStorageReader::FileReadLinesProfile = "FileReadLines";
773
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOCount =
774
        "TopNLazyMaterializationSecondPhaseLocalIOCount";
775
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOBytes =
776
        "TopNLazyMaterializationSecondPhaseLocalIOBytes";
777
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOCount =
778
        "TopNLazyMaterializationSecondPhaseRemoteIOCount";
779
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOBytes =
780
        "TopNLazyMaterializationSecondPhaseRemoteIOBytes";
781
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSkipCacheIOCount =
782
        "TopNLazyMaterializationSecondPhaseSkipCacheIOCount";
783
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheBytes =
784
        "TopNLazyMaterializationSecondPhaseWriteCacheBytes";
785
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOTime =
786
        "TopNLazyMaterializationSecondPhaseLocalIOTime";
787
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOTime =
788
        "TopNLazyMaterializationSecondPhaseRemoteIOTime";
789
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheIOTime =
790
        "TopNLazyMaterializationSecondPhaseWriteCacheIOTime";
791
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRowsRead =
792
        "TopNLazyMaterializationSecondPhaseRowsRead";
793
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSegmentsRead =
794
        "TopNLazyMaterializationSecondPhaseSegmentsRead";
795
796
Status RowIdStorageReader::read_external_row_from_file_mapping(
797
        size_t idx, const std::multimap<segment_v2::rowid_t, size_t>& row_ids,
798
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<SlotDescriptor>& slots,
799
        const TUniqueId& query_id, const std::shared_ptr<RuntimeState>& runtime_state,
800
        std::vector<Block>& scan_blocks, std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
801
        std::vector<RowIdStorageReader::ExternalFetchStatistics>& fetch_statistics,
802
        const TFileScanRangeParams& rpc_scan_params,
803
        const std::unordered_map<std::string, int>& colname_to_slot_id,
804
        std::atomic<int>& producer_count, size_t scan_rows_count,
805
        std::counting_semaphore<>& semaphore, std::condition_variable& cv, std::mutex& mtx,
806
3.19k
        TupleDescriptor& tuple_desc) {
807
3.19k
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
808
3.19k
    signal::set_signal_task_id(query_id);
809
810
3.19k
    std::list<int64_t> read_ids;
811
    //Generate an ordered list with the help of the orderliness of the map.
812
13.3k
    for (const auto& [row_id, result_block_idx] : row_ids) {
813
13.3k
        if (read_ids.empty() || read_ids.back() != row_id) {
814
11.1k
            read_ids.emplace_back(row_id);
815
11.1k
        }
816
13.3k
        row_id_block_idx[result_block_idx] = std::make_pair(idx, read_ids.size() - 1);
817
13.3k
    }
818
819
3.19k
    scan_blocks[idx] = Block(slots, read_ids.size());
820
821
3.19k
    auto& external_info = file_mapping->get_external_file_info();
822
3.19k
    auto& scan_range_desc = external_info.scan_range_desc;
823
824
    // Clear to avoid reading iceberg position delete file...
825
3.19k
    scan_range_desc.table_format_params.iceberg_params = TIcebergFileDesc {};
826
827
    // Clear to avoid reading hive transactional delete delta file...
828
3.19k
    scan_range_desc.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
829
830
3.19k
    std::unique_ptr<RuntimeProfile> sub_runtime_profile =
831
3.19k
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
832
3.19k
    {
833
3.19k
        std::unique_ptr<FileScanner> vfile_scanner_ptr =
834
3.19k
                FileScanner::create_unique(runtime_state.get(), sub_runtime_profile.get(),
835
3.19k
                                           &rpc_scan_params, &colname_to_slot_id, &tuple_desc);
836
837
3.19k
        RETURN_IF_ERROR(vfile_scanner_ptr->prepare_for_read_lines(scan_range_desc));
838
3.19k
        RETURN_IF_ERROR(vfile_scanner_ptr->read_lines_from_range(
839
3.19k
                scan_range_desc, read_ids, &scan_blocks[idx], external_info,
840
3.19k
                &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
841
3.19k
    }
842
843
3.19k
    auto file_read_bytes_counter =
844
3.19k
            sub_runtime_profile->get_counter(FileScanner::FileReadBytesProfile);
845
846
3.19k
    if (file_read_bytes_counter != nullptr) {
847
3.19k
        fetch_statistics[idx].file_read_bytes = PrettyPrinter::print(
848
3.19k
                file_read_bytes_counter->value(), file_read_bytes_counter->type());
849
3.19k
    }
850
851
3.19k
    auto file_read_times_counter =
852
3.19k
            sub_runtime_profile->get_counter(FileScanner::FileReadTimeProfile);
853
3.19k
    if (file_read_times_counter != nullptr) {
854
3.19k
        fetch_statistics[idx].file_read_times = PrettyPrinter::print(
855
3.19k
                file_read_times_counter->value(), file_read_times_counter->type());
856
3.19k
    }
857
858
3.19k
    semaphore.release();
859
3.19k
    if (++producer_count == scan_rows_count) {
860
2.01k
        std::lock_guard<std::mutex> lock(mtx);
861
2.01k
        cv.notify_one();
862
2.01k
    }
863
3.19k
    return Status::OK();
864
3.19k
}
865
866
Status RowIdStorageReader::read_batch_external_row(
867
        const uint64_t workload_group_id, const PRequestBlockDesc& request_block_desc,
868
        std::shared_ptr<IdFileMap> id_file_map, std::vector<SlotDescriptor>& slots,
869
        std::shared_ptr<FileMapping> first_file_mapping, const TUniqueId& query_id,
870
        Block& result_block, PRuntimeProfileTree* pprofile, int64_t* init_reader_avg_ms,
871
2.01k
        int64_t* get_block_avg_ms, size_t* scan_range_cnt) {
872
2.01k
    TFileScanRangeParams rpc_scan_params;
873
2.01k
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
874
2.01k
    std::unordered_map<std::string, int> colname_to_slot_id;
875
2.01k
    std::shared_ptr<RuntimeState> runtime_state = nullptr;
876
877
2.01k
    int max_file_scanners = 0;
878
2.01k
    {
879
2.01k
        if (result_block.is_empty_column()) [[likely]] {
880
2.01k
            result_block = Block(slots, request_block_desc.row_id_size());
881
2.01k
        }
882
883
2.01k
        auto& external_info = first_file_mapping->get_external_file_info();
884
2.01k
        int plan_node_id = external_info.plan_node_id;
885
2.01k
        const auto& first_scan_range_desc = external_info.scan_range_desc;
886
887
2.01k
        DCHECK(id_file_map->get_external_scan_params().contains(plan_node_id));
888
2.01k
        const auto* old_scan_params = &(id_file_map->get_external_scan_params().at(plan_node_id));
889
2.01k
        rpc_scan_params = *old_scan_params;
890
891
2.01k
        rpc_scan_params.required_slots.clear();
892
2.01k
        rpc_scan_params.column_idxs.clear();
893
2.01k
        rpc_scan_params.slot_name_to_schema_pos.clear();
894
895
2.01k
        std::set partition_name_set(first_scan_range_desc.columns_from_path_keys.begin(),
896
2.01k
                                    first_scan_range_desc.columns_from_path_keys.end());
897
10.6k
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
898
8.64k
            auto& slot = slots[slot_idx];
899
8.64k
            tuple_desc.add_slot(&slot);
900
8.64k
            colname_to_slot_id.emplace(slot.col_name(), slot.id());
901
8.64k
            TFileScanSlotInfo slot_info;
902
8.64k
            slot_info.slot_id = slot.id();
903
8.64k
            auto column_idx = request_block_desc.column_idxs(slot_idx);
904
8.64k
            if (partition_name_set.contains(slot.col_name())) {
905
                //This is partition column.
906
390
                slot_info.is_file_slot = false;
907
8.25k
            } else {
908
8.25k
                rpc_scan_params.column_idxs.emplace_back(column_idx);
909
8.25k
                slot_info.is_file_slot = true;
910
8.25k
            }
911
8.64k
            rpc_scan_params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
912
8.64k
            rpc_scan_params.required_slots.emplace_back(slot_info);
913
8.64k
            rpc_scan_params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
914
8.64k
        }
915
916
2.01k
        const auto& query_options = id_file_map->get_query_options();
917
2.01k
        const auto& query_globals = id_file_map->get_query_globals();
918
        /*
919
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
920
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
921
         *
922
         * To ensure the same behavior as the scan stage, I get query_options query_globals from id_file_map, then create runtime_state
923
         * 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.
924
         */
925
2.01k
        runtime_state = RuntimeState::create_shared(
926
2.01k
                query_id, -1, query_options, query_globals, ExecEnv::GetInstance(),
927
2.01k
                ExecEnv::GetInstance()->rowid_storage_reader_tracker());
928
929
2.01k
        max_file_scanners = id_file_map->get_max_file_scanners();
930
2.01k
    }
931
932
    // Hash(TFileRangeDesc) => { all the rows that need to be read and their positions in the result block. } +  file mapping
933
    // std::multimap<segment_v2::rowid_t, size_t> : The reason for using multimap is: may need the same row of data multiple times.
934
2.01k
    std::map<std::string,
935
2.01k
             std::pair<std::multimap<segment_v2::rowid_t, size_t>, std::shared_ptr<FileMapping>>>
936
2.01k
            scan_rows;
937
938
    // Block corresponding to the order of `scan_rows` map.
939
2.01k
    std::vector<Block> scan_blocks;
940
941
    // row_id (Indexing of vectors) => < In which block, which line in the block >
942
2.01k
    std::vector<std::pair<size_t, size_t>> row_id_block_idx;
943
944
    // Count the time/bytes it takes to read each TFileRangeDesc. (for profile)
945
2.01k
    std::vector<ExternalFetchStatistics> fetch_statistics;
946
947
13.3k
    auto hash_file_range = [](const TFileRangeDesc& file_range_desc) {
948
13.3k
        std::string value;
949
13.3k
        value.resize(file_range_desc.path.size() + sizeof(file_range_desc.start_offset));
950
13.3k
        auto* ptr = value.data();
951
952
13.3k
        memcpy(ptr, &file_range_desc.start_offset, sizeof(file_range_desc.start_offset));
953
13.3k
        ptr += sizeof(file_range_desc.start_offset);
954
13.3k
        memcpy(ptr, file_range_desc.path.data(), file_range_desc.path.size());
955
13.3k
        return value;
956
13.3k
    };
957
958
15.3k
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
959
13.3k
        auto file_id = request_block_desc.file_id(j);
960
13.3k
        auto file_mapping = id_file_map->get_file_mapping(file_id);
961
13.3k
        if (!file_mapping) {
962
0
            return Status::InternalError(
963
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
964
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
965
0
        }
966
967
13.3k
        const auto& external_info = file_mapping->get_external_file_info();
968
13.3k
        const auto& scan_range_desc = external_info.scan_range_desc;
969
970
13.3k
        auto scan_range_hash = hash_file_range(scan_range_desc);
971
13.3k
        if (scan_rows.contains(scan_range_hash)) {
972
10.1k
            scan_rows.at(scan_range_hash).first.emplace(request_block_desc.row_id(j), j);
973
10.1k
        } else {
974
3.19k
            std::multimap<segment_v2::rowid_t, size_t> tmp {{request_block_desc.row_id(j), j}};
975
3.19k
            scan_rows.emplace(scan_range_hash, std::make_pair(tmp, file_mapping));
976
3.19k
        }
977
13.3k
    }
978
979
2.01k
    scan_blocks.resize(scan_rows.size());
980
2.01k
    row_id_block_idx.resize(request_block_desc.row_id_size());
981
2.01k
    fetch_statistics.resize(scan_rows.size());
982
983
    // Get the workload group for subsequent scan task submission.
984
2.01k
    std::vector<uint64_t> workload_group_ids;
985
2.01k
    workload_group_ids.emplace_back(workload_group_id);
986
2.01k
    auto wg = ExecEnv::GetInstance()->workload_group_mgr()->get_group(workload_group_ids);
987
2.01k
    doris::TaskScheduler* exec_sched = nullptr;
988
2.01k
    ScannerScheduler* scan_sched = nullptr;
989
2.01k
    ScannerScheduler* remote_scan_sched = nullptr;
990
2.01k
    wg->get_query_scheduler(&exec_sched, &scan_sched, &remote_scan_sched);
991
2.01k
    DCHECK(remote_scan_sched);
992
993
2.01k
    int64_t scan_running_time = 0;
994
2.01k
    RETURN_IF_ERROR(scope_timer_run(
995
2.01k
            [&]() -> Status {
996
                // Make sure to insert data into result_block only after all scan tasks have been executed.
997
2.01k
                std::atomic<int> producer_count {0};
998
2.01k
                std::condition_variable cv;
999
2.01k
                std::mutex mtx;
1000
1001
                //semaphore: Limit the number of scan tasks submitted at one time
1002
2.01k
                std::counting_semaphore semaphore {max_file_scanners};
1003
1004
2.01k
                size_t idx = 0;
1005
2.01k
                for (const auto& [_, scan_info] : scan_rows) {
1006
2.01k
                    semaphore.acquire();
1007
2.01k
                    RETURN_IF_ERROR(remote_scan_sched->submit_scan_task(
1008
2.01k
                            SimplifiedScanTask(
1009
2.01k
                                    [&, idx, scan_info]() -> Status {
1010
2.01k
                                        const auto& [row_ids, file_mapping] = scan_info;
1011
2.01k
                                        return read_external_row_from_file_mapping(
1012
2.01k
                                                idx, row_ids, file_mapping, slots, query_id,
1013
2.01k
                                                runtime_state, scan_blocks, row_id_block_idx,
1014
2.01k
                                                fetch_statistics, rpc_scan_params,
1015
2.01k
                                                colname_to_slot_id, producer_count,
1016
2.01k
                                                scan_rows.size(), semaphore, cv, mtx, tuple_desc);
1017
2.01k
                                    },
1018
2.01k
                                    nullptr, nullptr),
1019
2.01k
                            fmt::format("{}-read_batch_external_row-{}", print_id(query_id), idx)));
1020
2.01k
                    idx++;
1021
2.01k
                }
1022
1023
2.01k
                {
1024
2.01k
                    std::unique_lock<std::mutex> lock(mtx);
1025
2.01k
                    cv.wait(lock, [&] { return producer_count == scan_rows.size(); });
1026
2.01k
                }
1027
2.01k
                return Status::OK();
1028
2.01k
            },
1029
2.01k
            &scan_running_time));
1030
1031
2.01k
    scatter_scan_blocks_to_result_block(row_id_block_idx, scan_blocks, result_block);
1032
1033
    // Statistical runtime profile information.
1034
2.01k
    std::unique_ptr<RuntimeProfile> runtime_profile =
1035
2.01k
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
1036
2.01k
    {
1037
2.01k
        runtime_profile->add_info_string(ScannersRunningTimeProfile,
1038
2.01k
                                         std::to_string(scan_running_time) + "ms");
1039
2.01k
        fmt::memory_buffer file_read_lines_buffer;
1040
2.01k
        format_to(file_read_lines_buffer, "[");
1041
2.01k
        fmt::memory_buffer file_read_bytes_buffer;
1042
2.01k
        format_to(file_read_bytes_buffer, "[");
1043
2.01k
        fmt::memory_buffer file_read_times_buffer;
1044
2.01k
        format_to(file_read_times_buffer, "[");
1045
1046
2.01k
        size_t idx = 0;
1047
3.19k
        for (const auto& [_, scan_info] : scan_rows) {
1048
3.19k
            format_to(file_read_lines_buffer, "{}, ", scan_info.first.size());
1049
3.19k
            *init_reader_avg_ms = fetch_statistics[idx].init_reader_ms;
1050
3.19k
            *get_block_avg_ms += fetch_statistics[idx].get_block_ms;
1051
3.19k
            format_to(file_read_bytes_buffer, "{}, ", fetch_statistics[idx].file_read_bytes);
1052
3.19k
            format_to(file_read_times_buffer, "{}, ", fetch_statistics[idx].file_read_times);
1053
3.19k
            idx++;
1054
3.19k
        }
1055
1056
2.01k
        format_to(file_read_lines_buffer, "]");
1057
2.01k
        format_to(file_read_bytes_buffer, "]");
1058
2.01k
        format_to(file_read_times_buffer, "]");
1059
1060
2.01k
        *init_reader_avg_ms /= fetch_statistics.size();
1061
2.01k
        *get_block_avg_ms /= fetch_statistics.size();
1062
2.01k
        runtime_profile->add_info_string(InitReaderAvgTimeProfile,
1063
2.01k
                                         std::to_string(*init_reader_avg_ms) + "ms");
1064
2.01k
        runtime_profile->add_info_string(GetBlockAvgTimeProfile,
1065
2.01k
                                         std::to_string(*init_reader_avg_ms) + "ms");
1066
2.01k
        runtime_profile->add_info_string(FileReadLinesProfile,
1067
2.01k
                                         fmt::to_string(file_read_lines_buffer));
1068
2.01k
        runtime_profile->add_info_string(FileScanner::FileReadBytesProfile,
1069
2.01k
                                         fmt::to_string(file_read_bytes_buffer));
1070
2.01k
        runtime_profile->add_info_string(FileScanner::FileReadTimeProfile,
1071
2.01k
                                         fmt::to_string(file_read_times_buffer));
1072
2.01k
    }
1073
1074
2.01k
    runtime_profile->to_proto(pprofile, 2);
1075
1076
2.01k
    *scan_range_cnt = scan_rows.size();
1077
1078
2.01k
    return Status::OK();
1079
2.01k
}
1080
1081
Status RowIdStorageReader::read_doris_format_row(
1082
        const std::shared_ptr<IdFileMap>& id_file_map,
1083
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<uint32_t>& row_ids,
1084
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
1085
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
1086
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
1087
        int64_t* lookup_row_data_ms, std::unordered_map<SegKey, SegItem, HashOfSegKey>& seg_map,
1088
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
1089
3.77k
        io::FileCacheMissPolicy file_cache_miss_policy, Block& result_block) {
1090
3.77k
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
1091
3.77k
    SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
1092
1093
3.77k
    BaseTabletSPtr tablet;
1094
3.77k
    BetaRowsetSharedPtr rowset;
1095
3.77k
    SegmentSharedPtr segment;
1096
3.77k
    if (seg_map.find(seg_key) == seg_map.end()) {
1097
3.77k
        tablet = scope_timer_run(
1098
3.77k
                [&]() {
1099
3.77k
                    auto res = ExecEnv::get_tablet(tablet_id);
1100
3.77k
                    return !res.has_value() ? nullptr
1101
3.77k
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
1102
3.77k
                },
1103
3.77k
                acquire_tablet_ms);
1104
3.77k
        if (!tablet) {
1105
0
            return Status::InternalError(
1106
0
                    "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1107
0
                    "row_id: {}",
1108
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1109
0
                    row_ids[0]);
1110
0
        }
1111
1112
3.77k
        rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
1113
3.77k
                [&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
1114
3.77k
                acquire_rowsets_ms));
1115
3.77k
        if (!rowset) {
1116
0
            return Status::InternalError(
1117
0
                    "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1118
0
                    "row_id: {}",
1119
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1120
0
                    row_ids[0]);
1121
0
        }
1122
1123
3.77k
        SegmentCacheHandle segment_cache;
1124
3.77k
        RETURN_IF_ERROR(scope_timer_run(
1125
3.77k
                [&]() {
1126
3.77k
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
1127
3.77k
                },
1128
3.77k
                acquire_segments_ms));
1129
1130
3.77k
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
1131
3.77k
                               segment_cache.get_segments().cend(),
1132
3.77k
                               [segment_id](const segment_v2::SegmentSharedPtr& seg) {
1133
3.77k
                                   return seg->id() == segment_id;
1134
3.77k
                               });
1135
3.77k
        if (it == segment_cache.get_segments().end()) {
1136
0
            return Status::InternalError(
1137
0
                    "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1138
0
                    "row_id: {}",
1139
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1140
0
                    row_ids[0]);
1141
0
        }
1142
3.77k
        segment = *it;
1143
3.77k
        seg_map[seg_key] = SegItem {.tablet = tablet, .rowset = rowset, .segment = segment};
1144
3.77k
    } else {
1145
0
        auto& seg_item = seg_map[seg_key];
1146
0
        tablet = seg_item.tablet;
1147
0
        rowset = seg_item.rowset;
1148
0
        segment = seg_item.segment;
1149
0
    }
1150
1151
    // if row_store_read_struct not empty, means the line we should read from row_store
1152
3.77k
    if (!row_store_read_struct.default_values.empty()) {
1153
1.34k
        if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
1154
0
            return Status::InternalError("Tablet {} does not have row store for all columns",
1155
0
                                         tablet->tablet_id());
1156
0
        }
1157
1.34k
        auto result_columns_guard = result_block.mutate_columns_scoped();
1158
1.34k
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
1159
1.34k
        io::IOContext io_ctx;
1160
1.34k
        io_ctx.reader_type = ReaderType::READER_QUERY;
1161
1.34k
        io_ctx.file_cache_stats = &stats.file_cache_stats;
1162
1.34k
        io_ctx.file_cache_miss_policy = file_cache_miss_policy;
1163
4.46k
        for (auto row_id : row_ids) {
1164
4.46k
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_id));
1165
4.46k
            row_store_read_struct.row_store_buffer.clear();
1166
4.46k
            RETURN_IF_ERROR(scope_timer_run(
1167
4.46k
                    [&]() {
1168
4.46k
                        return tablet->lookup_row_data({}, loc, rowset, stats,
1169
4.46k
                                                       row_store_read_struct.row_store_buffer,
1170
4.46k
                                                       false, &io_ctx);
1171
4.46k
                    },
1172
4.46k
                    lookup_row_data_ms));
1173
1174
4.46k
            RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
1175
4.46k
                    row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
1176
4.46k
                    row_store_read_struct.row_store_buffer.size(),
1177
4.46k
                    row_store_read_struct.col_uid_to_idx, result_columns,
1178
4.46k
                    row_store_read_struct.default_values, {}));
1179
4.46k
        }
1180
2.42k
    } else {
1181
15.3k
        for (int x = 0; x < slots.size(); ++x) {
1182
12.9k
            auto column_guard = result_block.mutate_column_scoped(x);
1183
12.9k
            MutableColumnPtr& column = column_guard.mutable_column();
1184
12.9k
            IteratorKey iterator_key {.tablet_id = tablet_id,
1185
12.9k
                                      .rowset_id = rowset_id,
1186
12.9k
                                      .segment_id = segment_id,
1187
12.9k
                                      .slot_id = slots[x].id()};
1188
12.9k
            IteratorItem& iterator_item = iterator_map[iterator_key];
1189
12.9k
            if (iterator_item.segment == nullptr) {
1190
12.9k
                iterator_map[iterator_key].segment = segment;
1191
12.9k
                iterator_item.storage_read_options.stats = &stats;
1192
12.9k
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
1193
12.9k
                iterator_item.storage_read_options.io_ctx.file_cache_miss_policy =
1194
12.9k
                        file_cache_miss_policy;
1195
12.9k
            }
1196
12.9k
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
1197
12.9k
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
1198
12.9k
                    full_read_schema, &slots[x], row_ids, column,
1199
12.9k
                    iterator_item.storage_read_options, iterator_item.iterator));
1200
12.9k
        }
1201
2.42k
    }
1202
3.77k
    return Status::OK();
1203
3.77k
}
1204
1205
} // namespace doris