Coverage Report

Created: 2026-07-02 15:06

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