Coverage Report

Created: 2025-06-07 21:58

/root/doris/be/src/exec/rowid_fetcher.cpp
Line
Count
Source (jump to first uncovered line)
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 "exec/tablet_info.h" // DorisNodesInfo
49
#include "olap/olap_common.h"
50
#include "olap/rowset/beta_rowset.h"
51
#include "olap/storage_engine.h"
52
#include "olap/tablet_fwd.h"
53
#include "olap/tablet_manager.h"
54
#include "olap/tablet_schema.h"
55
#include "olap/utils.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/types.h"
61
#include "util/brpc_client_cache.h" // BrpcClientCache
62
#include "util/defer_op.h"
63
#include "vec/columns/column.h"
64
#include "vec/columns/column_nullable.h"
65
#include "vec/columns/column_string.h"
66
#include "vec/common/assert_cast.h"
67
#include "vec/common/string_ref.h"
68
#include "vec/core/block.h" // Block
69
#include "vec/data_types/data_type_factory.hpp"
70
#include "vec/data_types/data_type_struct.h"
71
#include "vec/data_types/serde/data_type_serde.h"
72
#include "vec/exec/format/orc/vorc_reader.h"
73
#include "vec/exec/format/parquet/vparquet_reader.h"
74
#include "vec/exec/scan/file_scanner.h"
75
#include "vec/functions/function_helpers.h"
76
#include "vec/jsonb/serialize.h"
77
78
namespace doris {
79
80
0
Status RowIDFetcher::init() {
81
0
    DorisNodesInfo nodes_info;
82
0
    nodes_info.setNodes(_fetch_option.t_fetch_opt.nodes_info);
83
0
    for (auto [node_id, node_info] : nodes_info.nodes_info()) {
84
0
        auto client = ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
85
0
                node_info.host, node_info.brpc_port);
86
0
        if (!client) {
87
0
            LOG(WARNING) << "Get rpc stub failed, host=" << node_info.host
88
0
                         << ", port=" << node_info.brpc_port;
89
0
            return Status::InternalError("RowIDFetcher failed to init rpc client, host={}, port={}",
90
0
                                         node_info.host, node_info.brpc_port);
91
0
        }
92
0
        _stubs.push_back(client);
93
0
    }
94
0
    return Status::OK();
95
0
}
96
97
0
PMultiGetRequest RowIDFetcher::_init_fetch_request(const vectorized::ColumnString& row_locs) const {
98
0
    PMultiGetRequest mget_req;
99
0
    _fetch_option.desc->to_protobuf(mget_req.mutable_desc());
100
0
    for (SlotDescriptor* slot : _fetch_option.desc->slots()) {
101
        // ignore rowid
102
0
        if (slot->col_name() == BeConsts::ROWID_COL) {
103
0
            continue;
104
0
        }
105
0
        slot->to_protobuf(mget_req.add_slots());
106
0
    }
107
0
    for (size_t i = 0; i < row_locs.size(); ++i) {
108
0
        PRowLocation row_loc;
109
0
        StringRef row_id_rep = row_locs.get_data_at(i);
110
        // TODO: When transferring data between machines with different byte orders (endianness),
111
        // not performing proper handling may lead to issues in parsing and exchanging the data.
112
0
        auto location = reinterpret_cast<const GlobalRowLoacation*>(row_id_rep.data);
113
0
        row_loc.set_tablet_id(location->tablet_id);
114
0
        row_loc.set_rowset_id(location->row_location.rowset_id.to_string());
115
0
        row_loc.set_segment_id(location->row_location.segment_id);
116
0
        row_loc.set_ordinal_id(location->row_location.row_id);
117
0
        *mget_req.add_row_locs() = std::move(row_loc);
118
0
    }
119
    // Set column desc
120
0
    for (const TColumn& tcolumn : _fetch_option.t_fetch_opt.column_desc) {
121
0
        TabletColumn column(tcolumn);
122
0
        column.to_schema_pb(mget_req.add_column_desc());
123
0
    }
124
0
    PUniqueId& query_id = *mget_req.mutable_query_id();
125
0
    query_id.set_hi(_fetch_option.runtime_state->query_id().hi);
126
0
    query_id.set_lo(_fetch_option.runtime_state->query_id().lo);
127
0
    mget_req.set_be_exec_version(_fetch_option.runtime_state->be_exec_version());
128
0
    mget_req.set_fetch_row_store(_fetch_option.t_fetch_opt.fetch_row_store);
129
0
    return mget_req;
130
0
}
131
132
0
static void fetch_callback(bthread::CountdownEvent* counter) {
133
0
    Defer __defer([&] { counter->signal(); });
134
0
}
135
136
Status RowIDFetcher::_merge_rpc_results(const PMultiGetRequest& request,
137
                                        const std::vector<PMultiGetResponse>& rsps,
138
                                        const std::vector<brpc::Controller>& cntls,
139
                                        vectorized::Block* output_block,
140
0
                                        std::vector<PRowLocation>* rows_id) const {
141
0
    output_block->clear();
142
0
    for (const auto& cntl : cntls) {
143
0
        if (cntl.Failed()) {
144
0
            LOG(WARNING) << "Failed to fetch meet rpc error:" << cntl.ErrorText()
145
0
                         << ", host:" << cntl.remote_side();
146
0
            return Status::InternalError(cntl.ErrorText());
147
0
        }
148
0
    }
149
0
    vectorized::DataTypeSerDeSPtrs serdes;
150
0
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
151
0
    std::vector<std::string> default_values;
152
0
    default_values.resize(_fetch_option.desc->slots().size());
153
0
    auto merge_function = [&](const PMultiGetResponse& resp) {
154
0
        Status st(Status::create(resp.status()));
155
0
        if (!st.ok()) {
156
0
            LOG(WARNING) << "Failed to fetch " << st.to_string();
157
0
            return st;
158
0
        }
159
0
        for (const PRowLocation& row_id : resp.row_locs()) {
160
0
            rows_id->push_back(row_id);
161
0
        }
162
        // Merge binary rows
163
0
        if (request.fetch_row_store()) {
164
0
            CHECK(resp.row_locs().size() == resp.binary_row_data_size());
165
0
            if (output_block->is_empty_column()) {
166
0
                *output_block = vectorized::Block(_fetch_option.desc->slots(), 1);
167
0
            }
168
0
            if (serdes.empty() && col_uid_to_idx.empty()) {
169
0
                serdes = vectorized::create_data_type_serdes(_fetch_option.desc->slots());
170
0
                for (int i = 0; i < _fetch_option.desc->slots().size(); ++i) {
171
0
                    col_uid_to_idx[_fetch_option.desc->slots()[i]->col_unique_id()] = i;
172
0
                    default_values[i] = _fetch_option.desc->slots()[i]->col_default_value();
173
0
                }
174
0
            }
175
0
            for (int i = 0; i < resp.binary_row_data_size(); ++i) {
176
0
                RETURN_IF_ERROR(vectorized::JsonbSerializeUtil::jsonb_to_block(
177
0
                        serdes, resp.binary_row_data(i).data(), resp.binary_row_data(i).size(),
178
0
                        col_uid_to_idx, *output_block, default_values, {}));
179
0
            }
180
0
            return Status::OK();
181
0
        }
182
        // Merge partial blocks
183
0
        vectorized::Block partial_block;
184
0
        RETURN_IF_ERROR(partial_block.deserialize(resp.block()));
185
0
        if (partial_block.is_empty_column()) {
186
0
            return Status::OK();
187
0
        }
188
0
        CHECK(resp.row_locs().size() == partial_block.rows());
189
0
        if (output_block->is_empty_column()) {
190
0
            output_block->swap(partial_block);
191
0
        } else if (partial_block.columns() != output_block->columns()) {
192
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
193
0
                    "Merge block not match, self:[{}], input:[{}], ", output_block->dump_types(),
194
0
                    partial_block.dump_types());
195
0
        } else {
196
0
            for (int i = 0; i < output_block->columns(); ++i) {
197
0
                output_block->get_by_position(i).column->assume_mutable()->insert_range_from(
198
0
                        *partial_block.get_by_position(i)
199
0
                                 .column->convert_to_full_column_if_const()
200
0
                                 .get(),
201
0
                        0, partial_block.rows());
202
0
            }
203
0
        }
204
0
        return Status::OK();
205
0
    };
206
207
0
    for (const auto& resp : rsps) {
208
0
        RETURN_IF_ERROR(merge_function(resp));
209
0
    }
210
0
    return Status::OK();
211
0
}
212
213
0
bool _has_char_type(const vectorized::DataTypePtr& type) {
214
0
    switch (type->get_primitive_type()) {
215
0
    case TYPE_CHAR: {
216
0
        return true;
217
0
    }
218
0
    case TYPE_ARRAY: {
219
0
        const auto* arr_type =
220
0
                assert_cast<const vectorized::DataTypeArray*>(remove_nullable(type).get());
221
0
        return _has_char_type(arr_type->get_nested_type());
222
0
    }
223
0
    case TYPE_MAP: {
224
0
        const auto* map_type =
225
0
                assert_cast<const vectorized::DataTypeMap*>(remove_nullable(type).get());
226
0
        return _has_char_type(map_type->get_key_type()) ||
227
0
               _has_char_type(map_type->get_value_type());
228
0
    }
229
0
    case TYPE_STRUCT: {
230
0
        const auto* struct_type =
231
0
                assert_cast<const vectorized::DataTypeStruct*>(remove_nullable(type).get());
232
0
        return std::any_of(
233
0
                struct_type->get_elements().begin(), struct_type->get_elements().end(),
234
0
                [&](const vectorized::DataTypePtr& dt) -> bool { return _has_char_type(dt); });
235
0
    }
236
0
    default:
237
0
        return false;
238
0
    }
239
0
}
240
241
Status RowIDFetcher::fetch(const vectorized::ColumnPtr& column_row_ids,
242
0
                           vectorized::Block* res_block) {
243
0
    CHECK(!_stubs.empty());
244
0
    PMultiGetRequest mget_req = _init_fetch_request(assert_cast<const vectorized::ColumnString&>(
245
0
            *vectorized::remove_nullable(column_row_ids).get()));
246
0
    std::vector<PMultiGetResponse> resps(_stubs.size());
247
0
    std::vector<brpc::Controller> cntls(_stubs.size());
248
0
    bthread::CountdownEvent counter(_stubs.size());
249
0
    for (size_t i = 0; i < _stubs.size(); ++i) {
250
0
        cntls[i].set_timeout_ms(config::fetch_rpc_timeout_seconds * 1000);
251
0
        auto callback = brpc::NewCallback(fetch_callback, &counter);
252
0
        _stubs[i]->multiget_data(&cntls[i], &mget_req, &resps[i], callback);
253
0
    }
254
0
    counter.wait();
255
256
    // Merge
257
0
    std::vector<PRowLocation> rows_locs;
258
0
    rows_locs.reserve(rows_locs.size());
259
0
    RETURN_IF_ERROR(_merge_rpc_results(mget_req, resps, cntls, res_block, &rows_locs));
260
0
    if (rows_locs.size() < column_row_ids->size()) {
261
0
        return Status::InternalError("Miss matched return row loc count {}, expected {}, input {}",
262
0
                                     rows_locs.size(), res_block->rows(), column_row_ids->size());
263
0
    }
264
    // Final sort by row_ids sequence, since row_ids is already sorted if need
265
0
    std::map<GlobalRowLoacation, size_t> positions;
266
0
    for (size_t i = 0; i < rows_locs.size(); ++i) {
267
0
        RowsetId rowset_id;
268
0
        rowset_id.init(rows_locs[i].rowset_id());
269
0
        GlobalRowLoacation grl(rows_locs[i].tablet_id(), rowset_id, rows_locs[i].segment_id(),
270
0
                               rows_locs[i].ordinal_id());
271
0
        positions[grl] = i;
272
0
    };
273
    // TODO remove this warning code
274
0
    if (positions.size() < rows_locs.size()) {
275
0
        LOG(WARNING) << "contains duplicated row entry";
276
0
    }
277
0
    vectorized::IColumn::Permutation permutation;
278
0
    permutation.reserve(column_row_ids->size());
279
0
    for (size_t i = 0; i < column_row_ids->size(); ++i) {
280
0
        auto location =
281
0
                reinterpret_cast<const GlobalRowLoacation*>(column_row_ids->get_data_at(i).data);
282
0
        permutation.push_back(positions[*location]);
283
0
    }
284
0
    for (size_t i = 0; i < res_block->columns(); ++i) {
285
0
        res_block->get_by_position(i).column =
286
0
                res_block->get_by_position(i).column->permute(permutation, permutation.size());
287
0
    }
288
    // Check row consistency
289
0
    RETURN_IF_CATCH_EXCEPTION(res_block->check_number_of_rows());
290
    // shrink for char type
291
0
    std::vector<size_t> char_type_idx;
292
0
    for (size_t i = 0; i < _fetch_option.desc->slots().size(); i++) {
293
0
        const auto& column_desc = _fetch_option.desc->slots()[i];
294
0
        const auto type = column_desc->type();
295
0
        if (_has_char_type(type)) {
296
0
            char_type_idx.push_back(i);
297
0
        }
298
0
    }
299
0
    res_block->shrink_char_type_column_suffix_zero(char_type_idx);
300
0
    VLOG_DEBUG << "dump block:" << res_block->dump_data(0, 10);
301
0
    return Status::OK();
302
0
}
303
304
struct IteratorKey {
305
    int64_t tablet_id;
306
    RowsetId rowset_id;
307
    uint64_t segment_id;
308
    int slot_id;
309
310
    // unordered map std::equal_to
311
0
    bool operator==(const IteratorKey& rhs) const {
312
0
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
313
0
               segment_id == rhs.segment_id && slot_id == rhs.slot_id;
314
0
    }
315
};
316
317
struct HashOfIteratorKey {
318
0
    size_t operator()(const IteratorKey& key) const {
319
0
        size_t seed = 0;
320
0
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
321
0
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
322
0
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
323
0
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
324
0
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
325
0
        seed = HashUtil::hash64(&key.slot_id, sizeof(key.slot_id), seed);
326
0
        return seed;
327
0
    }
328
};
329
330
struct IteratorItem {
331
    std::unique_ptr<ColumnIterator> iterator;
332
    // for holding the reference of segment to avoid use after release
333
    SegmentSharedPtr segment;
334
};
335
336
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequest& request,
337
0
                                          PMultiGetResponse* response) {
338
    // read from storage engine row id by row id
339
0
    OlapReaderStatistics stats;
340
0
    vectorized::Block result_block;
341
0
    int64_t acquire_tablet_ms = 0;
342
0
    int64_t acquire_rowsets_ms = 0;
343
0
    int64_t acquire_segments_ms = 0;
344
0
    int64_t lookup_row_data_ms = 0;
345
346
    // init desc
347
0
    std::vector<SlotDescriptor> slots;
348
0
    slots.reserve(request.slots().size());
349
0
    for (const auto& pslot : request.slots()) {
350
0
        slots.push_back(SlotDescriptor(pslot));
351
0
    }
352
353
    // init read schema
354
0
    TabletSchema full_read_schema;
355
0
    for (const ColumnPB& column_pb : request.column_desc()) {
356
0
        full_read_schema.append_column(TabletColumn(column_pb));
357
0
    }
358
359
0
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
360
    // read row by row
361
0
    for (size_t i = 0; i < request.row_locs_size(); ++i) {
362
0
        const auto& row_loc = request.row_locs(i);
363
0
        MonotonicStopWatch watch;
364
0
        watch.start();
365
0
        BaseTabletSPtr tablet = scope_timer_run(
366
0
                [&]() {
367
0
                    auto res = ExecEnv::get_tablet(row_loc.tablet_id(), nullptr, true);
368
0
                    return !res.has_value() ? nullptr
369
0
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
370
0
                },
371
0
                &acquire_tablet_ms);
372
0
        RowsetId rowset_id;
373
0
        rowset_id.init(row_loc.rowset_id());
374
0
        if (!tablet) {
375
0
            continue;
376
0
        }
377
        // We ensured it's rowset is not released when init Tablet reader param, rowset->update_delayed_expired_timestamp();
378
0
        BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
379
0
                [&]() {
380
0
                    return ExecEnv::GetInstance()->storage_engine().get_quering_rowset(rowset_id);
381
0
                },
382
0
                &acquire_rowsets_ms));
383
0
        if (!rowset) {
384
0
            LOG(INFO) << "no such rowset " << rowset_id;
385
0
            continue;
386
0
        }
387
0
        size_t row_size = 0;
388
0
        Defer _defer([&]() {
389
0
            LOG_EVERY_N(INFO, 100)
390
0
                    << "multiget_data single_row, cost(us):" << watch.elapsed_time() / 1000
391
0
                    << ", row_size:" << row_size;
392
0
            *response->add_row_locs() = row_loc;
393
0
        });
394
        // TODO: supoort session variable enable_page_cache and disable_file_cache if necessary.
395
0
        SegmentCacheHandle segment_cache;
396
0
        RETURN_IF_ERROR(scope_timer_run(
397
0
                [&]() {
398
0
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
399
0
                },
400
0
                &acquire_segments_ms));
401
        // find segment
402
0
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
403
0
                               segment_cache.get_segments().cend(),
404
0
                               [&row_loc](const segment_v2::SegmentSharedPtr& seg) {
405
0
                                   return seg->id() == row_loc.segment_id();
406
0
                               });
407
0
        if (it == segment_cache.get_segments().end()) {
408
0
            continue;
409
0
        }
410
0
        segment_v2::SegmentSharedPtr segment = *it;
411
0
        GlobalRowLoacation row_location(row_loc.tablet_id(), rowset->rowset_id(),
412
0
                                        row_loc.segment_id(), row_loc.ordinal_id());
413
        // fetch by row store, more effcient way
414
0
        if (request.fetch_row_store()) {
415
0
            CHECK(tablet->tablet_schema()->has_row_store_for_all_columns());
416
0
            RowLocation loc(rowset_id, segment->id(), row_loc.ordinal_id());
417
0
            string* value = response->add_binary_row_data();
418
0
            RETURN_IF_ERROR(scope_timer_run(
419
0
                    [&]() { return tablet->lookup_row_data({}, loc, rowset, stats, *value); },
420
0
                    &lookup_row_data_ms));
421
0
            row_size = value->size();
422
0
            continue;
423
0
        }
424
425
        // fetch by column store
426
0
        if (result_block.is_empty_column()) {
427
0
            result_block = vectorized::Block(slots, request.row_locs().size());
428
0
        }
429
0
        VLOG_DEBUG << "Read row location "
430
0
                   << fmt::format("{}, {}, {}, {}", row_location.tablet_id,
431
0
                                  row_location.row_location.rowset_id.to_string(),
432
0
                                  row_location.row_location.segment_id,
433
0
                                  row_location.row_location.row_id);
434
0
        for (int x = 0; x < slots.size(); ++x) {
435
0
            auto row_id = static_cast<segment_v2::rowid_t>(row_loc.ordinal_id());
436
0
            vectorized::MutableColumnPtr column =
437
0
                    result_block.get_by_position(x).column->assume_mutable();
438
0
            IteratorKey iterator_key {.tablet_id = tablet->tablet_id(),
439
0
                                      .rowset_id = rowset_id,
440
0
                                      .segment_id = row_loc.segment_id(),
441
0
                                      .slot_id = slots[x].id()};
442
0
            IteratorItem& iterator_item = iterator_map[iterator_key];
443
0
            if (iterator_item.segment == nullptr) {
444
                // hold the reference
445
0
                iterator_map[iterator_key].segment = segment;
446
0
            }
447
0
            segment = iterator_item.segment;
448
0
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(full_read_schema, &slots[x], row_id,
449
0
                                                            column, stats, iterator_item.iterator));
450
0
        }
451
0
    }
452
    // serialize block if not empty
453
0
    if (!result_block.is_empty_column()) {
454
0
        VLOG_DEBUG << "dump block:" << result_block.dump_data(0, 10)
455
0
                   << ", be_exec_version:" << request.be_exec_version();
456
0
        [[maybe_unused]] size_t compressed_size = 0;
457
0
        [[maybe_unused]] size_t uncompressed_size = 0;
458
0
        int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
459
0
        RETURN_IF_ERROR(result_block.serialize(be_exec_version, response->mutable_block(),
460
0
                                               &uncompressed_size, &compressed_size,
461
0
                                               segment_v2::CompressionTypePB::LZ4));
462
0
    }
463
464
0
    LOG(INFO) << "Query stats: "
465
0
              << fmt::format(
466
0
                         "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
467
0
                         "io_latency:{}ns, "
468
0
                         "uncompressed_bytes_read:{},"
469
0
                         "bytes_read:{},"
470
0
                         "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
471
0
                         "lookup_row_data_ms:{}",
472
0
                         stats.cached_pages_num, stats.total_pages_num, stats.compressed_bytes_read,
473
0
                         stats.io_ns, stats.uncompressed_bytes_read, stats.bytes_read,
474
0
                         acquire_tablet_ms, acquire_rowsets_ms, acquire_segments_ms,
475
0
                         lookup_row_data_ms);
476
0
    return Status::OK();
477
0
}
478
479
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequestV2& request,
480
0
                                          PMultiGetResponseV2* response) {
481
0
    if (request.request_block_descs_size()) {
482
0
        auto tquery_id = ((UniqueId)request.query_id()).to_thrift();
483
0
        std::vector<vectorized::Block> result_blocks(request.request_block_descs_size());
484
485
0
        OlapReaderStatistics stats;
486
0
        int64_t acquire_tablet_ms = 0;
487
0
        int64_t acquire_rowsets_ms = 0;
488
0
        int64_t acquire_segments_ms = 0;
489
0
        int64_t lookup_row_data_ms = 0;
490
491
0
        int64_t external_init_reader_ms = 0;
492
0
        int64_t external_get_block_ms = 0;
493
494
        // Add counters for different file mapping types
495
0
        std::unordered_map<FileMappingType, int64_t> file_type_counts;
496
497
0
        auto id_file_map =
498
0
                ExecEnv::GetInstance()->get_id_manager()->get_id_file_map(request.query_id());
499
        // if id_file_map is null, means the BE not have scan range, just return ok
500
0
        if (!id_file_map) {
501
            // padding empty block to response
502
0
            for (int i = 0; i < request.request_block_descs_size(); ++i) {
503
0
                response->add_blocks();
504
0
            }
505
0
            return Status::OK();
506
0
        }
507
508
0
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
509
0
            const auto& request_block_desc = request.request_block_descs(i);
510
0
            if (request_block_desc.row_id_size() >= 1) {
511
                // Since this block belongs to the same table, we only need to take the first type for judgment.
512
0
                auto first_file_id = request_block_desc.file_id(0);
513
0
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
514
0
                if (!first_file_mapping) {
515
0
                    return Status::InternalError(
516
0
                            "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
517
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
518
0
                            first_file_id);
519
0
                }
520
0
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
521
522
                // prepare slots to build block
523
0
                std::vector<SlotDescriptor> slots;
524
0
                slots.reserve(request_block_desc.slots_size());
525
0
                for (const auto& pslot : request_block_desc.slots()) {
526
0
                    slots.push_back(SlotDescriptor(pslot));
527
0
                }
528
                // prepare block char vector shrink for char type
529
0
                std::vector<size_t> char_type_idx;
530
0
                for (int j = 0; j < slots.size(); ++j) {
531
0
                    auto slot = slots[j];
532
0
                    if (_has_char_type(slot.type())) {
533
0
                        char_type_idx.push_back(j);
534
0
                    }
535
0
                }
536
537
0
                if (first_file_mapping->type == FileMappingType::INTERNAL) {
538
0
                    RETURN_IF_ERROR(read_batch_doris_format_row(
539
0
                            request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
540
0
                            stats, &acquire_tablet_ms, &acquire_rowsets_ms, &acquire_segments_ms,
541
0
                            &lookup_row_data_ms));
542
0
                } else {
543
0
                    RETURN_IF_ERROR(read_batch_external_row(
544
0
                            request_block_desc, id_file_map, slots, first_file_mapping, tquery_id,
545
0
                            result_blocks[i], &external_init_reader_ms, &external_get_block_ms));
546
0
                }
547
548
                // after read the block, shrink char type block
549
0
                result_blocks[i].shrink_char_type_column_suffix_zero(char_type_idx);
550
0
            }
551
552
0
            [[maybe_unused]] size_t compressed_size = 0;
553
0
            [[maybe_unused]] size_t uncompressed_size = 0;
554
0
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
555
0
            RETURN_IF_ERROR(result_blocks[i].serialize(
556
0
                    be_exec_version, response->add_blocks()->mutable_block(), &uncompressed_size,
557
0
                    &compressed_size, segment_v2::CompressionTypePB::LZ4));
558
0
        }
559
560
        // Build file type statistics string
561
0
        std::string file_type_stats;
562
0
        for (const auto& [type, count] : file_type_counts) {
563
0
            if (!file_type_stats.empty()) {
564
0
                file_type_stats += ", ";
565
0
            }
566
0
            file_type_stats += fmt::format("{}:{}", type, count);
567
0
        }
568
569
0
        LOG(INFO) << "Query stats: "
570
0
                  << fmt::format(
571
0
                             "Internal table:"
572
0
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
573
0
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
574
0
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
575
0
                             "lookup_row_data_ms:{}, file_types:[{}]; "
576
0
                             "External table : init_reader_ms:{}, get_block_ms:{}",
577
0
                             stats.cached_pages_num, stats.total_pages_num,
578
0
                             stats.compressed_bytes_read, stats.io_ns,
579
0
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
580
0
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
581
0
                             file_type_stats, external_init_reader_ms, external_get_block_ms);
582
0
    }
583
584
0
    if (request.has_gc_id_map() && request.gc_id_map()) {
585
0
        ExecEnv::GetInstance()->get_id_manager()->remove_id_file_map(request.query_id());
586
0
    }
587
588
0
    return Status::OK();
589
0
}
590
591
Status RowIdStorageReader::read_batch_doris_format_row(
592
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
593
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id,
594
        vectorized::Block& result_block, OlapReaderStatistics& stats, int64_t* acquire_tablet_ms,
595
0
        int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms) {
596
0
    if (result_block.is_empty_column()) [[likely]] {
597
0
        result_block = vectorized::Block(slots, request_block_desc.row_id_size());
598
0
    }
599
600
0
    TabletSchema full_read_schema;
601
0
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
602
0
        full_read_schema.append_column(TabletColumn(column_pb));
603
0
    }
604
0
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
605
0
    std::string row_store_buffer;
606
0
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
607
0
    if (request_block_desc.fetch_row_store()) {
608
0
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
609
0
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
610
0
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
611
0
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
612
0
        }
613
0
    }
614
615
0
    for (size_t j = 0; j < request_block_desc.row_id_size(); ++j) {
616
0
        auto file_id = request_block_desc.file_id(j);
617
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
618
0
        if (!file_mapping) {
619
0
            return Status::InternalError(
620
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
621
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
622
0
        }
623
624
0
        RETURN_IF_ERROR(read_doris_format_row(
625
0
                id_file_map, file_mapping, request_block_desc.row_id(j), slots, full_read_schema,
626
0
                row_store_read_struct, stats, acquire_tablet_ms, acquire_rowsets_ms,
627
0
                acquire_segments_ms, lookup_row_data_ms, iterator_map, result_block));
628
0
    }
629
0
    return Status::OK();
630
0
}
631
632
Status RowIdStorageReader::read_batch_external_row(const PRequestBlockDesc& request_block_desc,
633
                                                   std::shared_ptr<IdFileMap> id_file_map,
634
                                                   std::vector<SlotDescriptor>& slots,
635
                                                   std::shared_ptr<FileMapping> first_file_mapping,
636
                                                   const TUniqueId& query_id,
637
                                                   vectorized::Block& result_block,
638
0
                                                   int64_t* init_reader_ms, int64_t* get_block_ms) {
639
0
    TFileScanRangeParams rpc_scan_params;
640
0
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
641
0
    std::unordered_map<std::string, int> colname_to_slot_id;
642
0
    std::unique_ptr<RuntimeState> runtime_state = nullptr;
643
0
    std::unique_ptr<RuntimeProfile> runtime_profile;
644
0
    runtime_profile = std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
645
646
0
    std::unique_ptr<vectorized::FileScanner> vfile_scanner_ptr = nullptr;
647
648
0
    {
649
0
        auto& external_info = first_file_mapping->get_external_file_info();
650
0
        int plan_node_id = external_info.plan_node_id;
651
0
        const auto& first_scan_range_desc = external_info.scan_range_desc;
652
653
0
        auto query_ctx = ExecEnv::GetInstance()->fragment_mgr()->get_query_ctx(query_id);
654
0
        const auto* old_scan_params = &(query_ctx->file_scan_range_params_map[plan_node_id]);
655
0
        rpc_scan_params = *old_scan_params;
656
657
0
        rpc_scan_params.required_slots.clear();
658
0
        rpc_scan_params.column_idxs.clear();
659
0
        rpc_scan_params.slot_name_to_schema_pos.clear();
660
661
0
        std::set partition_name_set(first_scan_range_desc.columns_from_path_keys.begin(),
662
0
                                    first_scan_range_desc.columns_from_path_keys.end());
663
0
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
664
0
            auto& slot = slots[slot_idx];
665
0
            tuple_desc.add_slot(&slot);
666
0
            colname_to_slot_id.emplace(slot.col_name(), slot.id());
667
0
            TFileScanSlotInfo slot_info;
668
0
            slot_info.slot_id = slot.id();
669
0
            auto column_idx = request_block_desc.column_idxs(slot_idx);
670
0
            if (partition_name_set.contains(slot.col_name())) {
671
                //This is partition column.
672
0
                slot_info.is_file_slot = false;
673
0
            } else {
674
0
                rpc_scan_params.column_idxs.emplace_back(column_idx);
675
0
                slot_info.is_file_slot = true;
676
0
            }
677
0
            rpc_scan_params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
678
0
            rpc_scan_params.required_slots.emplace_back(slot_info);
679
0
            rpc_scan_params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
680
0
        }
681
682
0
        if (result_block.is_empty_column()) [[likely]] {
683
0
            result_block = vectorized::Block(slots, request_block_desc.row_id_size());
684
0
        }
685
686
0
        const auto& query_options = query_ctx->get_query_options();
687
0
        const auto& query_globals = query_ctx->get_query_globals();
688
689
        /*
690
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
691
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
692
         *
693
         * To ensure the same behavior as the scan stage, I get query_options query_globals from query_ctx, then create runtime_state
694
         * 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.
695
         */
696
0
        runtime_state = RuntimeState::create_unique(query_id, -1, query_options, query_globals,
697
0
                                                    ExecEnv::GetInstance(), query_ctx.get());
698
699
0
        vfile_scanner_ptr = vectorized::FileScanner::create_unique(
700
0
                runtime_state.get(), runtime_profile.get(), &rpc_scan_params, &colname_to_slot_id,
701
0
                &tuple_desc);
702
703
0
        RETURN_IF_ERROR(vfile_scanner_ptr->prepare_for_read_one_line(first_scan_range_desc));
704
0
    }
705
706
0
    for (size_t j = 0; j < request_block_desc.row_id_size(); ++j) {
707
0
        auto file_id = request_block_desc.file_id(j);
708
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
709
0
        if (!file_mapping) {
710
0
            return Status::InternalError(
711
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
712
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
713
0
        }
714
715
0
        auto& external_info = file_mapping->get_external_file_info();
716
0
        auto& scan_range_desc = external_info.scan_range_desc;
717
718
        // Clear to avoid reading iceberg position delete file...
719
0
        scan_range_desc.table_format_params.iceberg_params = TIcebergFileDesc {};
720
721
        // Clear to avoid reading hive transactional delete delta file...
722
0
        scan_range_desc.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
723
724
0
        RETURN_IF_ERROR(vfile_scanner_ptr->read_one_line_from_range(
725
0
                scan_range_desc, request_block_desc.row_id(j), &result_block, external_info,
726
0
                init_reader_ms, get_block_ms));
727
0
    }
728
0
    return Status::OK();
729
0
}
730
731
Status RowIdStorageReader::read_doris_format_row(
732
        const std::shared_ptr<IdFileMap>& id_file_map,
733
        const std::shared_ptr<FileMapping>& file_mapping, int64_t row_id,
734
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
735
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
736
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
737
        int64_t* lookup_row_data_ms,
738
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
739
0
        vectorized::Block& result_block) {
740
0
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
741
0
    BaseTabletSPtr tablet = scope_timer_run(
742
0
            [&]() {
743
0
                auto res = ExecEnv::get_tablet(tablet_id);
744
0
                return !res.has_value() ? nullptr
745
0
                                        : std::dynamic_pointer_cast<BaseTablet>(res.value());
746
0
            },
747
0
            acquire_tablet_ms);
748
0
    if (!tablet) {
749
0
        return Status::InternalError(
750
0
                "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
751
0
                "row_id: {}",
752
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
753
0
                row_id);
754
0
    }
755
756
0
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(
757
0
            scope_timer_run([&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
758
0
                            acquire_rowsets_ms));
759
0
    if (!rowset) {
760
0
        return Status::InternalError(
761
0
                "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
762
0
                "row_id: {}",
763
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
764
0
                row_id);
765
0
    }
766
767
0
    SegmentCacheHandle segment_cache;
768
0
    RETURN_IF_ERROR(scope_timer_run(
769
0
            [&]() {
770
0
                return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
771
0
            },
772
0
            acquire_segments_ms));
773
774
0
    auto it =
775
0
            std::find_if(segment_cache.get_segments().cbegin(), segment_cache.get_segments().cend(),
776
0
                         [segment_id](const segment_v2::SegmentSharedPtr& seg) {
777
0
                             return seg->id() == segment_id;
778
0
                         });
779
0
    if (it == segment_cache.get_segments().end()) {
780
0
        return Status::InternalError(
781
0
                "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
782
0
                "row_id: {}",
783
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
784
0
                row_id);
785
0
    }
786
0
    segment_v2::SegmentSharedPtr segment = *it;
787
788
    // if row_store_read_struct not empty, means the line we should read from row_store
789
0
    if (!row_store_read_struct.default_values.empty()) {
790
0
        CHECK(tablet->tablet_schema()->has_row_store_for_all_columns());
791
0
        RowLocation loc(rowset_id, segment->id(), row_id);
792
0
        row_store_read_struct.row_store_buffer.clear();
793
0
        RETURN_IF_ERROR(scope_timer_run(
794
0
                [&]() {
795
0
                    return tablet->lookup_row_data({}, loc, rowset, stats,
796
0
                                                   row_store_read_struct.row_store_buffer);
797
0
                },
798
0
                lookup_row_data_ms));
799
800
0
        RETURN_IF_ERROR(vectorized::JsonbSerializeUtil::jsonb_to_block(
801
0
                row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
802
0
                row_store_read_struct.row_store_buffer.size(), row_store_read_struct.col_uid_to_idx,
803
0
                result_block, row_store_read_struct.default_values, {}));
804
0
    } else {
805
0
        for (int x = 0; x < slots.size(); ++x) {
806
0
            vectorized::MutableColumnPtr column =
807
0
                    result_block.get_by_position(x).column->assume_mutable();
808
0
            IteratorKey iterator_key {.tablet_id = tablet_id,
809
0
                                      .rowset_id = rowset_id,
810
0
                                      .segment_id = segment_id,
811
0
                                      .slot_id = slots[x].id()};
812
0
            IteratorItem& iterator_item = iterator_map[iterator_key];
813
0
            if (iterator_item.segment == nullptr) {
814
0
                iterator_map[iterator_key].segment = segment;
815
0
            }
816
0
            segment = iterator_item.segment;
817
0
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(full_read_schema, &slots[x], row_id,
818
0
                                                            column, stats, iterator_item.iterator));
819
0
        }
820
0
    }
821
822
0
    return Status::OK();
823
0
}
824
825
} // namespace doris