Coverage Report

Created: 2026-08-17 20:27

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