Coverage Report

Created: 2026-04-15 15:52

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