Coverage Report

Created: 2026-03-31 08:33

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