Coverage Report

Created: 2025-11-17 18:15

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