Coverage Report

Created: 2025-05-19 15:53

/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
                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());
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
0
        if (!id_file_map) {
500
0
            return Status::InternalError("Backend:{} id_file_map is null, query_id: {}",
501
0
                                         BackendOptions::get_localhost(), print_id(tquery_id));
502
0
        }
503
504
0
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
505
0
            const auto& request_block_desc = request.request_block_descs(i);
506
0
            if (request_block_desc.row_id_size() >= 1) {
507
                // Since this block belongs to the same table, we only need to take the first type for judgment.
508
0
                auto first_file_id = request_block_desc.file_id(0);
509
0
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
510
0
                if (!first_file_mapping) {
511
0
                    return Status::InternalError(
512
0
                            "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
513
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
514
0
                            first_file_id);
515
0
                }
516
0
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
517
518
                // prepare slots to build block
519
0
                std::vector<SlotDescriptor> slots;
520
0
                slots.reserve(request_block_desc.slots_size());
521
0
                for (const auto& pslot : request_block_desc.slots()) {
522
0
                    slots.push_back(SlotDescriptor(pslot));
523
0
                }
524
                // prepare block char vector shrink for char type
525
0
                std::vector<size_t> char_type_idx;
526
0
                for (int j = 0; j < slots.size(); ++j) {
527
0
                    auto slot = slots[j];
528
0
                    if (_has_char_type(slot.type())) {
529
0
                        char_type_idx.push_back(j);
530
0
                    }
531
0
                }
532
533
0
                if (first_file_mapping->type == FileMappingType::INTERNAL) {
534
0
                    RETURN_IF_ERROR(read_batch_doris_format_row(
535
0
                            request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
536
0
                            stats, &acquire_tablet_ms, &acquire_rowsets_ms, &acquire_segments_ms,
537
0
                            &lookup_row_data_ms));
538
0
                } else {
539
0
                    RETURN_IF_ERROR(read_batch_external_row(
540
0
                            request_block_desc, id_file_map, slots, first_file_mapping, tquery_id,
541
0
                            result_blocks[i], &external_init_reader_ms, &external_get_block_ms));
542
0
                }
543
544
                // after read the block, shrink char type block
545
0
                result_blocks[i].shrink_char_type_column_suffix_zero(char_type_idx);
546
0
            }
547
548
0
            [[maybe_unused]] size_t compressed_size = 0;
549
0
            [[maybe_unused]] size_t uncompressed_size = 0;
550
0
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
551
0
            RETURN_IF_ERROR(result_blocks[i].serialize(
552
0
                    be_exec_version, response->add_blocks()->mutable_block(), &uncompressed_size,
553
0
                    &compressed_size, segment_v2::CompressionTypePB::LZ4));
554
0
        }
555
556
        // Build file type statistics string
557
0
        std::string file_type_stats;
558
0
        for (const auto& [type, count] : file_type_counts) {
559
0
            if (!file_type_stats.empty()) {
560
0
                file_type_stats += ", ";
561
0
            }
562
0
            file_type_stats += fmt::format("{}:{}", type, count);
563
0
        }
564
565
0
        LOG(INFO) << "Query stats: "
566
0
                  << fmt::format(
567
0
                             "Internal table:"
568
0
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
569
0
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
570
0
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
571
0
                             "lookup_row_data_ms:{}, file_types:[{}]; "
572
0
                             "External table : init_reader_ms:{}, get_block_ms:{}",
573
0
                             stats.cached_pages_num, stats.total_pages_num,
574
0
                             stats.compressed_bytes_read, stats.io_ns,
575
0
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
576
0
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
577
0
                             file_type_stats, external_init_reader_ms, external_get_block_ms);
578
0
    }
579
580
0
    if (request.has_gc_id_map() && request.gc_id_map()) {
581
0
        ExecEnv::GetInstance()->get_id_manager()->remove_id_file_map(request.query_id());
582
0
    }
583
584
0
    return Status::OK();
585
0
}
586
587
Status RowIdStorageReader::read_batch_doris_format_row(
588
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
589
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id,
590
        vectorized::Block& result_block, OlapReaderStatistics& stats, int64_t* acquire_tablet_ms,
591
0
        int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms) {
592
0
    if (result_block.is_empty_column()) [[likely]] {
593
0
        result_block = vectorized::Block(slots, request_block_desc.row_id_size());
594
0
    }
595
596
0
    TabletSchema full_read_schema;
597
0
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
598
0
        full_read_schema.append_column(TabletColumn(column_pb));
599
0
    }
600
0
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
601
0
    std::string row_store_buffer;
602
0
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
603
0
    if (request_block_desc.fetch_row_store()) {
604
0
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
605
0
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
606
0
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
607
0
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
608
0
        }
609
0
    }
610
611
0
    for (size_t j = 0; j < request_block_desc.row_id_size(); ++j) {
612
0
        auto file_id = request_block_desc.file_id(j);
613
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
614
0
        if (!file_mapping) {
615
0
            return Status::InternalError(
616
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
617
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
618
0
        }
619
620
0
        RETURN_IF_ERROR(read_doris_format_row(
621
0
                id_file_map, file_mapping, request_block_desc.row_id(j), slots, full_read_schema,
622
0
                row_store_read_struct, stats, acquire_tablet_ms, acquire_rowsets_ms,
623
0
                acquire_segments_ms, lookup_row_data_ms, iterator_map, result_block));
624
0
    }
625
0
    return Status::OK();
626
0
}
627
628
Status RowIdStorageReader::read_batch_external_row(const PRequestBlockDesc& request_block_desc,
629
                                                   std::shared_ptr<IdFileMap> id_file_map,
630
                                                   std::vector<SlotDescriptor>& slots,
631
                                                   std::shared_ptr<FileMapping> first_file_mapping,
632
                                                   const TUniqueId& query_id,
633
                                                   vectorized::Block& result_block,
634
0
                                                   int64_t* init_reader_ms, int64_t* get_block_ms) {
635
0
    TFileScanRangeParams rpc_scan_params;
636
0
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
637
0
    std::unordered_map<std::string, int> colname_to_slot_id;
638
0
    std::unique_ptr<RuntimeState> runtime_state = nullptr;
639
0
    std::unique_ptr<RuntimeProfile> runtime_profile;
640
0
    runtime_profile = std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
641
642
0
    std::unique_ptr<vectorized::FileScanner> vfile_scanner_ptr = nullptr;
643
644
0
    {
645
0
        auto& external_info = first_file_mapping->get_external_file_info();
646
0
        int plan_node_id = external_info.plan_node_id;
647
0
        const auto& first_scan_range_desc = external_info.scan_range_desc;
648
649
0
        auto query_ctx = ExecEnv::GetInstance()->fragment_mgr()->get_query_ctx(query_id);
650
0
        const auto* old_scan_params = &(query_ctx->file_scan_range_params_map[plan_node_id]);
651
0
        rpc_scan_params = *old_scan_params;
652
653
0
        rpc_scan_params.required_slots.clear();
654
0
        rpc_scan_params.column_idxs.clear();
655
0
        rpc_scan_params.slot_name_to_schema_pos.clear();
656
657
0
        std::set partition_name_set(first_scan_range_desc.columns_from_path_keys.begin(),
658
0
                                    first_scan_range_desc.columns_from_path_keys.end());
659
0
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
660
0
            auto& slot = slots[slot_idx];
661
0
            tuple_desc.add_slot(&slot);
662
0
            colname_to_slot_id.emplace(slot.col_name(), slot.id());
663
0
            TFileScanSlotInfo slot_info;
664
0
            slot_info.slot_id = slot.id();
665
0
            auto column_idx = request_block_desc.column_idxs(slot_idx);
666
0
            if (partition_name_set.contains(slot.col_name())) {
667
                //This is partition column.
668
0
                slot_info.is_file_slot = false;
669
0
            } else {
670
0
                rpc_scan_params.column_idxs.emplace_back(column_idx);
671
0
                slot_info.is_file_slot = true;
672
0
            }
673
0
            rpc_scan_params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
674
0
            rpc_scan_params.required_slots.emplace_back(slot_info);
675
0
            rpc_scan_params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
676
0
        }
677
678
0
        if (result_block.is_empty_column()) [[likely]] {
679
0
            result_block = vectorized::Block(slots, request_block_desc.row_id_size());
680
0
        }
681
682
0
        const auto& query_options = query_ctx->get_query_options();
683
0
        const auto& query_globals = query_ctx->get_query_globals();
684
685
        /*
686
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
687
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
688
         *
689
         * To ensure the same behavior as the scan stage, I get query_options query_globals from query_ctx, then create runtime_state
690
         * 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.
691
         */
692
0
        runtime_state = RuntimeState::create_unique(query_id, -1, query_options, query_globals,
693
0
                                                    ExecEnv::GetInstance(), query_ctx.get());
694
695
0
        vfile_scanner_ptr = vectorized::FileScanner::create_unique(
696
0
                runtime_state.get(), runtime_profile.get(), &rpc_scan_params, &colname_to_slot_id,
697
0
                &tuple_desc);
698
699
0
        RETURN_IF_ERROR(vfile_scanner_ptr->prepare_for_read_one_line(first_scan_range_desc));
700
0
    }
701
702
0
    for (size_t j = 0; j < request_block_desc.row_id_size(); ++j) {
703
0
        auto file_id = request_block_desc.file_id(j);
704
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
705
0
        if (!file_mapping) {
706
0
            return Status::InternalError(
707
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
708
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
709
0
        }
710
711
0
        auto& external_info = file_mapping->get_external_file_info();
712
0
        auto& scan_range_desc = external_info.scan_range_desc;
713
714
        // Clear to avoid reading iceberg position delete file...
715
0
        scan_range_desc.table_format_params.iceberg_params = TIcebergFileDesc {};
716
717
        // Clear to avoid reading hive transactional delete delta file...
718
0
        scan_range_desc.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
719
720
0
        RETURN_IF_ERROR(vfile_scanner_ptr->read_one_line_from_range(
721
0
                scan_range_desc, request_block_desc.row_id(j), &result_block, external_info,
722
0
                init_reader_ms, get_block_ms));
723
0
    }
724
0
    return Status::OK();
725
0
}
726
727
Status RowIdStorageReader::read_doris_format_row(
728
        const std::shared_ptr<IdFileMap>& id_file_map,
729
        const std::shared_ptr<FileMapping>& file_mapping, int64_t row_id,
730
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
731
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
732
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
733
        int64_t* lookup_row_data_ms,
734
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
735
0
        vectorized::Block& result_block) {
736
0
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
737
0
    BaseTabletSPtr tablet = scope_timer_run(
738
0
            [&]() {
739
0
                auto res = ExecEnv::get_tablet(tablet_id);
740
0
                return !res.has_value() ? nullptr
741
0
                                        : std::dynamic_pointer_cast<BaseTablet>(res.value());
742
0
            },
743
0
            acquire_tablet_ms);
744
0
    if (!tablet) {
745
0
        return Status::InternalError(
746
0
                "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
747
0
                "row_id: {}",
748
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
749
0
                row_id);
750
0
    }
751
752
0
    BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(
753
0
            scope_timer_run([&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
754
0
                            acquire_rowsets_ms));
755
0
    if (!rowset) {
756
0
        return Status::InternalError(
757
0
                "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
758
0
                "row_id: {}",
759
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
760
0
                row_id);
761
0
    }
762
763
0
    SegmentCacheHandle segment_cache;
764
0
    RETURN_IF_ERROR(scope_timer_run(
765
0
            [&]() {
766
0
                return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
767
0
            },
768
0
            acquire_segments_ms));
769
770
0
    auto it =
771
0
            std::find_if(segment_cache.get_segments().cbegin(), segment_cache.get_segments().cend(),
772
0
                         [segment_id](const segment_v2::SegmentSharedPtr& seg) {
773
0
                             return seg->id() == segment_id;
774
0
                         });
775
0
    if (it == segment_cache.get_segments().end()) {
776
0
        return Status::InternalError(
777
0
                "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
778
0
                "row_id: {}",
779
0
                BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
780
0
                row_id);
781
0
    }
782
0
    segment_v2::SegmentSharedPtr segment = *it;
783
784
    // if row_store_read_struct not empty, means the line we should read from row_store
785
0
    if (!row_store_read_struct.default_values.empty()) {
786
0
        CHECK(tablet->tablet_schema()->has_row_store_for_all_columns());
787
0
        RowLocation loc(rowset_id, segment->id(), row_id);
788
0
        row_store_read_struct.row_store_buffer.clear();
789
0
        RETURN_IF_ERROR(scope_timer_run(
790
0
                [&]() {
791
0
                    return tablet->lookup_row_data({}, loc, rowset, stats,
792
0
                                                   row_store_read_struct.row_store_buffer);
793
0
                },
794
0
                lookup_row_data_ms));
795
796
0
        vectorized::JsonbSerializeUtil::jsonb_to_block(
797
0
                row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
798
0
                row_store_read_struct.row_store_buffer.size(), row_store_read_struct.col_uid_to_idx,
799
0
                result_block, row_store_read_struct.default_values, {});
800
0
    } else {
801
0
        for (int x = 0; x < slots.size(); ++x) {
802
0
            vectorized::MutableColumnPtr column =
803
0
                    result_block.get_by_position(x).column->assume_mutable();
804
0
            IteratorKey iterator_key {.tablet_id = tablet_id,
805
0
                                      .rowset_id = rowset_id,
806
0
                                      .segment_id = segment_id,
807
0
                                      .slot_id = slots[x].id()};
808
0
            IteratorItem& iterator_item = iterator_map[iterator_key];
809
0
            if (iterator_item.segment == nullptr) {
810
0
                iterator_map[iterator_key].segment = segment;
811
0
            }
812
0
            segment = iterator_item.segment;
813
0
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(full_read_schema, &slots[x], row_id,
814
0
                                                            column, stats, iterator_item.iterator));
815
0
        }
816
0
    }
817
818
0
    return Status::OK();
819
0
}
820
821
} // namespace doris