Coverage Report

Created: 2026-10-17 00:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/exec/rowid_fetcher.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/rowid_fetcher.h"
19
20
#include <brpc/callback.h>
21
#include <butil/endpoint.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/data.pb.h>
24
#include <gen_cpp/internal_service.pb.h>
25
#include <gen_cpp/olap_file.pb.h>
26
#include <gen_cpp/types.pb.h>
27
#include <glog/logging.h>
28
#include <stddef.h>
29
#include <stdint.h>
30
31
#include <algorithm>
32
#include <cstdint>
33
#include <limits>
34
#include <memory>
35
#include <mutex>
36
#include <ostream>
37
#include <string>
38
#include <unordered_map>
39
#include <utility>
40
#include <vector>
41
42
#include "bthread/countdown_event.h"
43
#include "cloud/cloud_storage_engine.h"
44
#include "cloud/cloud_tablet.h"
45
#include "cloud/cloud_tablet_mgr.h"
46
#include "cloud/config.h"
47
#include "common/config.h"
48
#include "common/consts.h"
49
#include "common/exception.h"
50
#include "common/signal_handler.h"
51
#include "core/assert_cast.h"
52
#include "core/block/block.h" // Block
53
#include "core/column/column.h"
54
#include "core/column/column_nullable.h"
55
#include "core/column/column_string.h"
56
#include "core/data_type/data_type_struct.h"
57
#include "core/data_type_serde/data_type_serde.h"
58
#include "core/string_ref.h"
59
#include "core/types.h"
60
#include "exec/operator/file_scan_operator.h"
61
#include "exec/scan/file_scanner.h"
62
#include "exec/scan/file_scanner_v2.h"
63
#include "format/orc/vorc_reader.h"
64
#include "format/parquet/vparquet_reader.h"
65
#include "format_v2/table/lance_reader.h"
66
#include "io/io_common.h"
67
#include "runtime/descriptors.h"
68
#include "runtime/exec_env.h"      // ExecEnv
69
#include "runtime/fragment_mgr.h"  // FragmentMgr
70
#include "runtime/runtime_state.h" // RuntimeState
71
#include "runtime/workload_group/workload_group_manager.h"
72
#include "semaphore"
73
#include "storage/olap_common.h"
74
#include "storage/rowset/beta_rowset.h"
75
#include "storage/segment/column_reader.h"
76
#include "storage/storage_engine.h"
77
#include "storage/tablet/tablet_fwd.h"
78
#include "storage/tablet/tablet_schema.h"
79
#include "storage/tablet_info.h" // DorisNodesInfo
80
#include "storage/utils.h"
81
#include "util/brpc_client_cache.h" // BrpcClientCache
82
#include "util/defer_op.h"
83
#include "util/jsonb/serialize.h"
84
#include "util/pretty_printer.h"
85
86
namespace doris {
87
88
#include "common/compile_check_begin.h"
89
90
namespace {
91
92
void set_topn_lazy_materialization_file_cache_stats(
93
0
        const io::FileCacheStatistics& stats, PTopNLazyMaterializationFileCacheStats* pstats) {
94
0
    pstats->set_local_io_count(stats.num_local_io_total);
95
0
    pstats->set_local_io_bytes(stats.bytes_read_from_local);
96
0
    pstats->set_remote_io_count(stats.num_remote_io_total);
97
0
    pstats->set_remote_io_bytes(stats.bytes_read_from_remote);
98
0
    pstats->set_skip_cache_io_count(stats.num_skip_cache_io_total);
99
0
    pstats->set_write_cache_bytes(stats.bytes_write_into_cache);
100
0
    pstats->set_local_io_time(stats.local_io_timer);
101
0
    pstats->set_remote_io_time(stats.remote_io_timer);
102
0
    pstats->set_write_cache_io_time(stats.write_cache_io_timer);
103
0
}
104
105
} // namespace
106
107
0
Status RowIDFetcher::init() {
108
0
    DorisNodesInfo nodes_info;
109
0
    nodes_info.setNodes(_fetch_option.t_fetch_opt.nodes_info);
110
0
    for (auto [node_id, node_info] : nodes_info.nodes_info()) {
111
0
        auto client = ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
112
0
                node_info.host, node_info.brpc_port);
113
0
        if (!client) {
114
0
            LOG(WARNING) << "Get rpc stub failed, host=" << node_info.host
115
0
                         << ", port=" << node_info.brpc_port;
116
0
            return Status::InternalError("RowIDFetcher failed to init rpc client, host={}, port={}",
117
0
                                         node_info.host, node_info.brpc_port);
118
0
        }
119
0
        _stubs.push_back(client);
120
0
    }
121
0
    return Status::OK();
122
0
}
123
124
0
PMultiGetRequest RowIDFetcher::_init_fetch_request(const ColumnString& row_locs) const {
125
0
    PMultiGetRequest mget_req;
126
0
    _fetch_option.desc->to_protobuf(mget_req.mutable_desc());
127
0
    for (SlotDescriptor* slot : _fetch_option.desc->slots()) {
128
        // ignore rowid
129
0
        if (slot->col_name() == BeConsts::ROWID_COL) {
130
0
            continue;
131
0
        }
132
0
        slot->to_protobuf(mget_req.add_slots());
133
0
    }
134
0
    for (size_t i = 0; i < row_locs.size(); ++i) {
135
0
        PRowLocation row_loc;
136
0
        StringRef row_id_rep = row_locs.get_data_at(i);
137
        // TODO: When transferring data between machines with different byte orders (endianness),
138
        // not performing proper handling may lead to issues in parsing and exchanging the data.
139
0
        auto location = reinterpret_cast<const GlobalRowLoacation*>(row_id_rep.data);
140
0
        row_loc.set_tablet_id(location->tablet_id);
141
0
        row_loc.set_rowset_id(location->row_location.rowset_id.to_string());
142
0
        row_loc.set_segment_id(location->row_location.segment_id);
143
0
        row_loc.set_ordinal_id(location->row_location.row_id);
144
0
        *mget_req.add_row_locs() = std::move(row_loc);
145
0
    }
146
    // Set column desc
147
0
    for (const TColumn& tcolumn : _fetch_option.t_fetch_opt.column_desc) {
148
0
        TabletColumn column(tcolumn);
149
0
        column.to_schema_pb(mget_req.add_column_desc());
150
0
    }
151
0
    PUniqueId& query_id = *mget_req.mutable_query_id();
152
0
    query_id.set_hi(_fetch_option.runtime_state->query_id().hi);
153
0
    query_id.set_lo(_fetch_option.runtime_state->query_id().lo);
154
0
    mget_req.set_be_exec_version(_fetch_option.runtime_state->be_exec_version());
155
0
    mget_req.set_fetch_row_store(_fetch_option.t_fetch_opt.fetch_row_store);
156
0
    return mget_req;
157
0
}
158
159
Status RowIDFetcher::_merge_rpc_results(const PMultiGetRequest& request,
160
                                        const std::vector<PMultiGetResponse>& rsps,
161
                                        const std::vector<brpc::Controller>& cntls,
162
                                        Block* output_block,
163
0
                                        std::vector<PRowLocation>* rows_id) const {
164
0
    output_block->clear();
165
0
    for (const auto& cntl : cntls) {
166
0
        if (cntl.Failed()) {
167
0
            LOG(WARNING) << "Failed to fetch meet rpc error:" << cntl.ErrorText()
168
0
                         << ", host:" << cntl.remote_side();
169
0
            return Status::InternalError(cntl.ErrorText());
170
0
        }
171
0
    }
172
0
    DataTypeSerDeSPtrs serdes;
173
0
    std::unordered_map<uint32_t, uint32_t> col_uid_to_idx;
174
0
    std::vector<std::string> default_values;
175
0
    default_values.resize(_fetch_option.desc->slots().size());
176
0
    auto merge_function = [&](const PMultiGetResponse& resp) {
177
0
        Status st(Status::create(resp.status()));
178
0
        if (!st.ok()) {
179
0
            LOG(WARNING) << "Failed to fetch " << st.to_string();
180
0
            return st;
181
0
        }
182
0
        for (const PRowLocation& row_id : resp.row_locs()) {
183
0
            rows_id->push_back(row_id);
184
0
        }
185
        // Merge binary rows
186
0
        if (request.fetch_row_store()) {
187
0
            CHECK(resp.row_locs().size() == resp.binary_row_data_size());
188
0
            if (output_block->is_empty_column()) {
189
0
                *output_block = Block(_fetch_option.desc->slots(), 1);
190
0
            }
191
0
            if (serdes.empty() && col_uid_to_idx.empty()) {
192
0
                serdes = create_data_type_serdes(_fetch_option.desc->slots());
193
0
                for (int i = 0; i < _fetch_option.desc->slots().size(); ++i) {
194
0
                    col_uid_to_idx[_fetch_option.desc->slots()[i]->col_unique_id()] = i;
195
0
                    default_values[i] = _fetch_option.desc->slots()[i]->col_default_value();
196
0
                }
197
0
            }
198
0
            auto output_columns_guard = output_block->mutate_columns_scoped();
199
0
            MutableColumns& output_columns = output_columns_guard.mutable_columns();
200
0
            for (int i = 0; i < resp.binary_row_data_size(); ++i) {
201
0
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
202
0
                        serdes, resp.binary_row_data(i).data(), resp.binary_row_data(i).size(),
203
0
                        col_uid_to_idx, output_columns, default_values, {}));
204
0
            }
205
0
            return Status::OK();
206
0
        }
207
        // Merge partial blocks
208
0
        Block partial_block;
209
0
        [[maybe_unused]] size_t uncompressed_size = 0;
210
0
        [[maybe_unused]] int64_t uncompressed_time = 0;
211
212
0
        RETURN_IF_ERROR(
213
0
                partial_block.deserialize(resp.block(), &uncompressed_size, &uncompressed_time));
214
0
        if (partial_block.is_empty_column()) {
215
0
            return Status::OK();
216
0
        }
217
0
        CHECK(resp.row_locs().size() == partial_block.rows());
218
0
        if (output_block->is_empty_column()) {
219
0
            output_block->swap(partial_block);
220
0
        } else if (partial_block.columns() != output_block->columns()) {
221
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
222
0
                    "Merge block not match, self:[{}], input:[{}], ", output_block->dump_types(),
223
0
                    partial_block.dump_types());
224
0
        } else {
225
0
            for (int i = 0; i < output_block->columns(); ++i) {
226
0
                auto column_guard = output_block->mutate_column_scoped(i);
227
0
                MutableColumnPtr& column = column_guard.mutable_column();
228
0
                column->insert_range_from(
229
0
                        *partial_block.get_by_position(i).column->convert_to_full_column_if_const(),
230
0
                        0, partial_block.rows());
231
0
            }
232
0
        }
233
0
        return Status::OK();
234
0
    };
235
236
0
    for (const auto& resp : rsps) {
237
0
        RETURN_IF_ERROR(merge_function(resp));
238
0
    }
239
0
    return Status::OK();
240
0
}
241
242
0
Status RowIDFetcher::fetch(const ColumnPtr& column_row_ids, Block* res_block) {
243
0
    CHECK(!_stubs.empty());
244
0
    PMultiGetRequest mget_req = _init_fetch_request(
245
0
            assert_cast<const ColumnString&>(*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(cast_set<int>(_stubs.size()));
249
0
    for (size_t i = 0; i < _stubs.size(); ++i) {
250
0
        cntls[i].set_timeout_ms(_fetch_option.runtime_state->execution_timeout() * 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,
270
0
                               cast_set<uint32_t>(rows_locs[i].segment_id()),
271
0
                               cast_set<uint32_t>(rows_locs[i].ordinal_id()));
272
0
        positions[grl] = i;
273
0
    };
274
    // TODO remove this warning code
275
0
    if (positions.size() < rows_locs.size()) {
276
0
        LOG(WARNING) << "cwntains duplicated row entry";
277
0
    }
278
0
    IColumn::Permutation permutation;
279
0
    permutation.reserve(column_row_ids->size());
280
0
    for (size_t i = 0; i < column_row_ids->size(); ++i) {
281
0
        auto location =
282
0
                reinterpret_cast<const GlobalRowLoacation*>(column_row_ids->get_data_at(i).data);
283
0
        permutation.push_back(positions[*location]);
284
0
    }
285
0
    for (size_t i = 0; i < res_block->columns(); ++i) {
286
0
        res_block->get_by_position(i).column =
287
0
                res_block->get_by_position(i).column->permute(permutation, permutation.size());
288
0
    }
289
    // Check row consistency
290
0
    RETURN_IF_CATCH_EXCEPTION(res_block->check_number_of_rows());
291
0
    VLOG_DEBUG << "dump block:" << res_block->dump_data(0, 10);
292
0
    return Status::OK();
293
0
}
294
295
struct IteratorKey {
296
    int64_t tablet_id;
297
    RowsetId rowset_id;
298
    uint64_t segment_id;
299
    int slot_id;
300
301
    // unordered map std::equal_to
302
12
    bool operator==(const IteratorKey& rhs) const {
303
12
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
304
12
               segment_id == rhs.segment_id && slot_id == rhs.slot_id;
305
12
    }
306
};
307
308
struct SegKey {
309
    int64_t tablet_id;
310
    RowsetId rowset_id;
311
    uint64_t segment_id;
312
313
    // unordered map std::equal_to
314
0
    bool operator==(const SegKey& rhs) const {
315
0
        return tablet_id == rhs.tablet_id && rowset_id == rhs.rowset_id &&
316
0
               segment_id == rhs.segment_id;
317
0
    }
318
};
319
320
struct HashOfSegKey {
321
0
    size_t operator()(const SegKey& key) const {
322
0
        size_t seed = 0;
323
0
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
324
0
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
325
0
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
326
0
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
327
0
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
328
0
        return seed;
329
0
    }
330
};
331
332
struct HashOfIteratorKey {
333
16
    size_t operator()(const IteratorKey& key) const {
334
16
        size_t seed = 0;
335
16
        seed = HashUtil::hash64(&key.tablet_id, sizeof(key.tablet_id), seed);
336
16
        seed = HashUtil::hash64(&key.rowset_id.hi, sizeof(key.rowset_id.hi), seed);
337
16
        seed = HashUtil::hash64(&key.rowset_id.mi, sizeof(key.rowset_id.mi), seed);
338
16
        seed = HashUtil::hash64(&key.rowset_id.lo, sizeof(key.rowset_id.lo), seed);
339
16
        seed = HashUtil::hash64(&key.segment_id, sizeof(key.segment_id), seed);
340
16
        seed = HashUtil::hash64(&key.slot_id, sizeof(key.slot_id), seed);
341
16
        return seed;
342
16
    }
343
};
344
345
struct IteratorItem {
346
    std::unique_ptr<ColumnIterator> iterator;
347
    SegmentSharedPtr segment;
348
    // for holding the reference of storage read options to avoid use after release
349
    StorageReadOptions storage_read_options;
350
};
351
352
static void set_slot_access_paths(const SlotDescriptor& slot, const TabletSchema& schema,
353
12
                                  StorageReadOptions& storage_read_options) {
354
12
    int32_t unique_id = slot.col_unique_id();
355
12
    const int field_index =
356
12
            unique_id >= 0 ? schema.field_index(unique_id) : schema.field_index(slot.col_name());
357
12
    if (field_index >= 0) {
358
12
        const auto& column = schema.column(field_index);
359
12
        unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
360
12
    }
361
12
    if (unique_id < 0) {
362
0
        return;
363
0
    }
364
365
12
    if (!slot.all_access_paths().empty()) {
366
0
        storage_read_options.all_access_paths[unique_id] = slot.all_access_paths();
367
0
    }
368
369
12
    if (!slot.predicate_access_paths().empty()) {
370
0
        storage_read_options.predicate_access_paths[unique_id] = slot.predicate_access_paths();
371
0
    }
372
12
}
373
374
struct SegItem {
375
    BaseTabletSPtr tablet;
376
    BetaRowsetSharedPtr rowset;
377
    // for holding the reference of segment to avoid use after release
378
    SegmentSharedPtr segment;
379
};
380
381
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequest& request,
382
2
                                          PMultiGetResponse* response) {
383
    // read from storage engine row id by row id
384
2
    OlapReaderStatistics stats;
385
2
    Block result_block;
386
2
    int64_t acquire_tablet_ms = 0;
387
2
    int64_t acquire_rowsets_ms = 0;
388
2
    int64_t acquire_segments_ms = 0;
389
2
    int64_t lookup_row_data_ms = 0;
390
391
    // init desc
392
2
    std::vector<SlotDescriptor> slots;
393
2
    slots.reserve(request.slots().size());
394
4
    for (const auto& pslot : request.slots()) {
395
4
        slots.push_back(SlotDescriptor(pslot));
396
4
    }
397
398
    // init read schema
399
2
    TabletSchema full_read_schema;
400
2
    for (const ColumnPB& column_pb : request.column_desc()) {
401
2
        full_read_schema.append_column(TabletColumn(column_pb));
402
2
    }
403
404
2
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
405
    // read row by row
406
8
    for (int i = 0; i < request.row_locs_size(); ++i) {
407
6
        const auto& row_loc = request.row_locs(i);
408
6
        MonotonicStopWatch watch;
409
6
        watch.start();
410
6
        BaseTabletSPtr tablet = scope_timer_run(
411
6
                [&]() {
412
6
                    auto res = ExecEnv::get_tablet(row_loc.tablet_id(), nullptr, true);
413
6
                    return !res.has_value() ? nullptr
414
6
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
415
6
                },
416
6
                &acquire_tablet_ms);
417
6
        RowsetId rowset_id;
418
6
        rowset_id.init(row_loc.rowset_id());
419
6
        if (!tablet) {
420
0
            continue;
421
0
        }
422
        // We ensured it's rowset is not released when init Tablet reader param, rowset->update_delayed_expired_timestamp();
423
6
        BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
424
6
                [&]() {
425
6
                    return ExecEnv::GetInstance()->storage_engine().get_quering_rowset(rowset_id);
426
6
                },
427
6
                &acquire_rowsets_ms));
428
6
        if (!rowset) {
429
0
            LOG(INFO) << "no such rowset " << rowset_id;
430
0
            continue;
431
0
        }
432
6
        size_t row_size = 0;
433
6
        Defer _defer([&]() {
434
6
            LOG_EVERY_N(INFO, 100)
435
1
                    << "multiget_data single_row, cost(us):" << watch.elapsed_time() / 1000
436
1
                    << ", row_size:" << row_size;
437
6
            *response->add_row_locs() = row_loc;
438
6
        });
439
        // TODO: supoort session variable enable_page_cache and disable_file_cache if necessary.
440
6
        SegmentCacheHandle segment_cache;
441
6
        RETURN_IF_ERROR(scope_timer_run(
442
6
                [&]() {
443
6
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
444
6
                },
445
6
                &acquire_segments_ms));
446
        // find segment
447
6
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
448
6
                               segment_cache.get_segments().cend(),
449
6
                               [&row_loc](const segment_v2::SegmentSharedPtr& seg) {
450
6
                                   return seg->id() == row_loc.segment_id();
451
6
                               });
452
6
        if (it == segment_cache.get_segments().end()) {
453
0
            continue;
454
0
        }
455
6
        segment_v2::SegmentSharedPtr segment = *it;
456
6
        GlobalRowLoacation row_location(row_loc.tablet_id(), rowset->rowset_id(),
457
6
                                        cast_set<uint32_t>(row_loc.segment_id()),
458
6
                                        cast_set<uint32_t>(row_loc.ordinal_id()));
459
        // fetch by row store, more effcient way
460
6
        if (request.fetch_row_store()) {
461
0
            if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
462
0
                return Status::InternalError("Tablet {} does not have row store for all columns",
463
0
                                             tablet->tablet_id());
464
0
            }
465
0
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_loc.ordinal_id()));
466
0
            std::string* value = response->add_binary_row_data();
467
0
            RETURN_IF_ERROR(scope_timer_run(
468
0
                    [&]() { return tablet->lookup_row_data({}, loc, rowset, stats, *value); },
469
0
                    &lookup_row_data_ms));
470
0
            row_size = value->size();
471
0
            continue;
472
0
        }
473
474
        // fetch by column store
475
6
        if (result_block.is_empty_column()) {
476
2
            result_block = Block(slots, request.row_locs().size());
477
2
        }
478
6
        VLOG_DEBUG << "Read row location "
479
0
                   << fmt::format("{}, {}, {}, {}", row_location.tablet_id,
480
0
                                  row_location.row_location.rowset_id.to_string(),
481
0
                                  row_location.row_location.segment_id,
482
0
                                  row_location.row_location.row_id);
483
18
        for (int x = 0; x < slots.size(); ++x) {
484
12
            auto row_id = static_cast<segment_v2::rowid_t>(row_loc.ordinal_id());
485
            // The scoped mutation republishes a potentially replaced V2 column when the reader
486
            // transfers ownership of its first assembled batch.
487
12
            auto column_guard = result_block.mutate_column_scoped(x);
488
12
            MutableColumnPtr& column = column_guard.mutable_column();
489
12
            IteratorKey iterator_key {.tablet_id = tablet->tablet_id(),
490
12
                                      .rowset_id = rowset_id,
491
12
                                      .segment_id = row_loc.segment_id(),
492
12
                                      .slot_id = slots[x].id()};
493
12
            IteratorItem& iterator_item = iterator_map[iterator_key];
494
12
            if (iterator_item.segment == nullptr) {
495
                // hold the reference
496
4
                iterator_map[iterator_key].segment = segment;
497
4
                iterator_item.storage_read_options.stats = &stats;
498
4
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
499
4
            }
500
12
            segment = iterator_item.segment;
501
12
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
502
12
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
503
12
                    full_read_schema, &slots[x], row_id, column, iterator_item.storage_read_options,
504
12
                    iterator_item.iterator));
505
12
        }
506
6
    }
507
    // serialize block if not empty
508
2
    if (!result_block.is_empty_column()) {
509
2
        VLOG_DEBUG << "dump block:" << result_block.dump_data(0, 10)
510
0
                   << ", be_exec_version:" << request.be_exec_version();
511
2
        [[maybe_unused]] size_t compressed_size = 0;
512
2
        [[maybe_unused]] size_t uncompressed_size = 0;
513
2
        [[maybe_unused]] int64_t compress_time = 0;
514
2
        int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
515
2
        RETURN_IF_ERROR(result_block.serialize(be_exec_version, response->mutable_block(),
516
2
                                               &uncompressed_size, &compressed_size, &compress_time,
517
2
                                               segment_v2::CompressionTypePB::LZ4));
518
2
    }
519
520
2
    LOG(INFO) << "Query stats: "
521
2
              << fmt::format(
522
2
                         "query_id:{}, "
523
2
                         "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
524
2
                         "io_latency:{}ns, "
525
2
                         "uncompressed_bytes_read:{},"
526
2
                         "bytes_read:{},"
527
2
                         "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
528
2
                         "lookup_row_data_ms:{}",
529
2
                         print_id(request.query_id()), stats.cached_pages_num,
530
2
                         stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
531
2
                         stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
532
2
                         acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms);
533
2
    return Status::OK();
534
2
}
535
536
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequestV2& request,
537
0
                                          PMultiGetResponseV2* response) {
538
0
    if (request.request_block_descs_size()) {
539
0
        auto tquery_id = ((UniqueId)request.query_id()).to_thrift();
540
        // todo: use mutableBlock instead of block
541
0
        std::vector<Block> result_blocks(request.request_block_descs_size());
542
543
0
        OlapReaderStatistics stats;
544
0
        int64_t acquire_tablet_ms = 0;
545
0
        int64_t acquire_rowsets_ms = 0;
546
0
        int64_t acquire_segments_ms = 0;
547
0
        int64_t lookup_row_data_ms = 0;
548
549
0
        int64_t external_init_reader_avg_ms = 0;
550
0
        int64_t external_get_block_avg_ms = 0;
551
0
        size_t external_scan_range_cnt = 0;
552
553
0
        const auto file_cache_miss_policy =
554
0
                request.file_cache_remote_only_on_miss()
555
0
                        ? io::FileCacheMissPolicy::REMOTE_ONLY_ON_MISS
556
0
                        : io::FileCacheMissPolicy::READ_THROUGH_AND_WRITE_BACK;
557
558
        // Add counters for different file mapping types
559
0
        std::unordered_map<FileMappingType, int64_t> file_type_counts;
560
561
0
        auto id_file_map =
562
0
                ExecEnv::GetInstance()->get_id_manager()->get_id_file_map(request.query_id());
563
        // if id_file_map is null, means the BE not have scan range, just return ok
564
0
        if (!id_file_map) {
565
            // padding empty block to response
566
0
            LOG(INFO) << "id_file_map not found for query_id: " << print_id(request.query_id());
567
0
            for (int i = 0; i < request.request_block_descs_size(); ++i) {
568
0
                response->add_blocks();
569
0
            }
570
0
            return Status::OK();
571
0
        }
572
573
0
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
574
0
            const auto& request_block_desc = request.request_block_descs(i);
575
0
            PMultiGetBlockV2* pblock = response->add_blocks();
576
0
            if (request_block_desc.row_id_size() >= 1) {
577
0
                if (request_block_desc.file_id_size() != request_block_desc.row_id_size()) {
578
0
                    return Status::InvalidArgument(
579
0
                            "Row-id fetch has mismatched file_id and row_id counts: "
580
0
                            "file_ids={}, row_ids={}",
581
0
                            request_block_desc.file_id_size(), request_block_desc.row_id_size());
582
0
                }
583
0
                const auto row_location_version = request_block_desc.row_location_version();
584
0
                switch (row_location_version) {
585
0
                case static_cast<uint32_t>(ROW_VERSION::FILE_LOCAL_ROW_ID):
586
0
                case static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID):
587
0
                    break;
588
0
                default:
589
0
                    return Status::NotSupported("unsupported row location version in fetch: {}",
590
0
                                                row_location_version);
591
0
                }
592
                // Rows in this request block belong to the same relation. The first mapping is
593
                // sufficient to select the internal/external fetch path; individual file IDs
594
                // are still used below to group the actual reads.
595
0
                const auto first_file_id = request_block_desc.file_id(0);
596
0
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
597
0
                if (!first_file_mapping) {
598
0
                    return Status::InternalError(
599
0
                            "Backend:{} file mapping not found, query_id: {}, file_id: {}",
600
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
601
0
                            first_file_id);
602
0
                }
603
0
                if (first_file_mapping->type != FileMappingType::EXTERNAL &&
604
0
                    row_location_version ==
605
0
                            static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID)) {
606
0
                    return Status::InvalidArgument(
607
0
                            "Lance dataset row IDs require an external file mapping");
608
0
                }
609
0
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
610
611
                // prepare slots to build block
612
0
                std::vector<SlotDescriptor> slots;
613
0
                slots.reserve(request_block_desc.slots_size());
614
0
                for (const auto& pslot : request_block_desc.slots()) {
615
0
                    slots.push_back(SlotDescriptor(pslot));
616
0
                }
617
0
                try {
618
0
                    if (first_file_mapping->type == FileMappingType::INTERNAL) {
619
0
                        RETURN_IF_ERROR(read_batch_doris_format_row(
620
0
                                request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
621
0
                                stats, &acquire_tablet_ms, &acquire_rowsets_ms,
622
0
                                &acquire_segments_ms, &lookup_row_data_ms, file_cache_miss_policy));
623
0
                    } else {
624
0
                        RETURN_IF_ERROR(read_batch_external_row(
625
0
                                request.wg_id(), request_block_desc, id_file_map, slots,
626
0
                                first_file_mapping, tquery_id, result_blocks[i],
627
0
                                pblock->mutable_profile(), &external_init_reader_avg_ms,
628
0
                                &external_get_block_avg_ms, &external_scan_range_cnt));
629
0
                    }
630
0
                } catch (const Exception& e) {
631
0
                    return Status::Error<false>(e.code(), "Row id fetch failed because {}",
632
0
                                                e.what());
633
0
                }
634
0
            }
635
636
0
            [[maybe_unused]] size_t compressed_size = 0;
637
0
            [[maybe_unused]] size_t uncompressed_size = 0;
638
0
            [[maybe_unused]] int64_t compress_time = 0;
639
0
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
640
0
            RETURN_IF_ERROR(result_blocks[i].serialize(
641
0
                    be_exec_version, pblock->mutable_block(), &uncompressed_size, &compressed_size,
642
0
                    &compress_time, segment_v2::CompressionTypePB::LZ4));
643
0
        }
644
645
        // Build file type statistics string
646
0
        std::string file_type_stats;
647
0
        for (const auto& [type, count] : file_type_counts) {
648
0
            if (!file_type_stats.empty()) {
649
0
                file_type_stats += ", ";
650
0
            }
651
0
            file_type_stats += fmt::format("{}:{}", type, count);
652
0
        }
653
654
0
        LOG(INFO) << "Query stats: "
655
0
                  << fmt::format(
656
0
                             "query_id:{}, "
657
0
                             "Internal table:"
658
0
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
659
0
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
660
0
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
661
0
                             "lookup_row_data_ms:{}, file_types:[{}]; "
662
0
                             "External table : init_reader_ms:{}, get_block_ms:{}, "
663
0
                             "external_scan_range_cnt:{}",
664
0
                             print_id(request.query_id()), stats.cached_pages_num,
665
0
                             stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
666
0
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
667
0
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
668
0
                             file_type_stats, external_init_reader_avg_ms,
669
0
                             external_get_block_avg_ms, external_scan_range_cnt);
670
0
        set_topn_lazy_materialization_file_cache_stats(
671
0
                stats.file_cache_stats,
672
0
                response->mutable_topn_lazy_materialization_file_cache_stats());
673
0
    }
674
675
0
    if (request.has_gc_id_map() && request.gc_id_map()) {
676
0
        ExecEnv::GetInstance()->get_id_manager()->remove_id_file_map(request.query_id());
677
0
    }
678
679
0
    return Status::OK();
680
0
}
681
682
Status RowIdStorageReader::read_batch_doris_format_row(
683
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
684
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id, Block& result_block,
685
        OlapReaderStatistics& stats, int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms,
686
        int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms,
687
0
        io::FileCacheMissPolicy file_cache_miss_policy) {
688
0
    if (result_block.is_empty_column()) [[likely]] {
689
0
        result_block = Block(slots, request_block_desc.row_id_size());
690
0
    }
691
0
    TabletSchema full_read_schema;
692
0
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
693
0
        full_read_schema.append_column(TabletColumn(column_pb));
694
0
    }
695
696
0
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
697
0
    std::unordered_map<SegKey, SegItem, HashOfSegKey> seg_map;
698
0
    std::string row_store_buffer;
699
0
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
700
0
    if (request_block_desc.fetch_row_store()) {
701
0
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
702
0
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
703
0
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
704
0
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
705
0
        }
706
0
    }
707
708
0
    std::vector<uint32_t> row_ids;
709
0
    int k = 1;
710
0
    auto max_k = 0;
711
0
    for (int j = 0; j < request_block_desc.row_id_size();) {
712
0
        auto file_id = request_block_desc.file_id(j);
713
0
        const auto row_id = request_block_desc.row_id(j);
714
0
        if (row_id > std::numeric_limits<uint32_t>::max()) {
715
0
            return Status::InvalidArgument("internal row id exceeds uint32 range: {}", row_id);
716
0
        }
717
0
        row_ids.emplace_back(static_cast<uint32_t>(row_id));
718
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
719
0
        if (!file_mapping) {
720
0
            return Status::InternalError(
721
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
722
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
723
0
        }
724
0
        for (k = 1; j + k < request_block_desc.row_id_size(); ++k) {
725
0
            if (request_block_desc.file_id(j + k) == file_id) {
726
0
                const auto next_row_id = request_block_desc.row_id(j + k);
727
0
                if (next_row_id > std::numeric_limits<uint32_t>::max()) {
728
0
                    return Status::InvalidArgument("internal row id exceeds uint32 range: {}",
729
0
                                                   next_row_id);
730
0
                }
731
0
                row_ids.emplace_back(static_cast<uint32_t>(next_row_id));
732
0
            } else {
733
0
                break;
734
0
            }
735
0
        }
736
737
0
        RETURN_IF_ERROR(read_doris_format_row(
738
0
                id_file_map, file_mapping, row_ids, slots, full_read_schema, row_store_read_struct,
739
0
                stats, acquire_tablet_ms, acquire_rowsets_ms, acquire_segments_ms,
740
0
                lookup_row_data_ms, seg_map, iterator_map, file_cache_miss_policy, result_block));
741
742
0
        j += k;
743
0
        max_k = std::max(max_k, k);
744
0
        row_ids.clear();
745
0
    }
746
747
0
    return Status::OK();
748
0
}
749
750
const std::string RowIdStorageReader::ScannersRunningTimeProfile = "ScannersRunningTime";
751
const std::string RowIdStorageReader::InitReaderAvgTimeProfile = "InitReaderAvgTime";
752
const std::string RowIdStorageReader::GetBlockAvgTimeProfile = "GetBlockAvgTime";
753
const std::string RowIdStorageReader::FileReadLinesProfile = "FileReadLines";
754
const std::string RowIdStorageReader::LanceDatasetOpenTimeProfile = "LanceDatasetOpenTime";
755
const std::string RowIdStorageReader::LanceRowIdTakeReadTimeProfile = "LanceRowIdTakeReadTime";
756
const std::string RowIdStorageReader::LanceArrowToDorisBlockTimeProfile =
757
        "LanceArrowToDorisBlockTime";
758
const std::string RowIdStorageReader::LanceRowIdFetchTotalTimeProfile = "LanceRowIdFetchTotalTime";
759
const std::map<std::string, TUnit::type> RowIdStorageReader::LanceFetchCountersProfile = {
760
        {"LanceRowIdFetchRows", TUnit::UNIT},
761
        {"LanceRowIdFetchCalls", TUnit::UNIT},
762
        {"LanceDataCacheBytesReadFromCache", TUnit::BYTES},
763
        {"LanceDataCacheBytesReadFromRemote", TUnit::BYTES},
764
};
765
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOCount =
766
        "TopNLazyMaterializationSecondPhaseLocalIOCount";
767
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOBytes =
768
        "TopNLazyMaterializationSecondPhaseLocalIOBytes";
769
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOCount =
770
        "TopNLazyMaterializationSecondPhaseRemoteIOCount";
771
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOBytes =
772
        "TopNLazyMaterializationSecondPhaseRemoteIOBytes";
773
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSkipCacheIOCount =
774
        "TopNLazyMaterializationSecondPhaseSkipCacheIOCount";
775
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheBytes =
776
        "TopNLazyMaterializationSecondPhaseWriteCacheBytes";
777
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOTime =
778
        "TopNLazyMaterializationSecondPhaseLocalIOTime";
779
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOTime =
780
        "TopNLazyMaterializationSecondPhaseRemoteIOTime";
781
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheIOTime =
782
        "TopNLazyMaterializationSecondPhaseWriteCacheIOTime";
783
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRowsRead =
784
        "TopNLazyMaterializationSecondPhaseRowsRead";
785
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSegmentsRead =
786
        "TopNLazyMaterializationSecondPhaseSegmentsRead";
787
788
bool RowIdStorageReader::should_use_file_scanner_v2(const TQueryOptions& query_options,
789
                                                    const TFileScanRangeParams& scan_params,
790
40
                                                    const TFileRangeDesc& range) {
791
40
    const auto format_type =
792
40
            range.__isset.format_type ? range.format_type : scan_params.format_type;
793
    // Phase two inherits the query options, including the Thrift presence bit. Reuse phase one's
794
    // policy so disabling V2 (or an older payload omitting the option) also keeps row fetches on V1.
795
40
    return FileScanLocalState::should_use_file_scanner_v2(query_options, false, scan_params) &&
796
40
           (format_type == TFileFormatType::FORMAT_PARQUET ||
797
15
            format_type == TFileFormatType::FORMAT_ORC) &&
798
40
           FileScannerV2::is_supported(scan_params, range);
799
40
}
800
801
1
TFileRangeDesc RowIdStorageReader::build_external_fetch_range(const TFileRangeDesc& source_range) {
802
    // Rows were selected after delete filtering. Preserve the original path and row lineage
803
    // needed by virtual columns, and do not mutate the FileMapping shared by other fetches.
804
1
    auto range = source_range;
805
1
    range.table_format_params.iceberg_params.__set_delete_files({});
806
1
    range.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
807
1
    return range;
808
1
}
809
810
TFileScanRangeParams RowIdStorageReader::build_external_scan_params(
811
        const TFileScanRangeParams& source_params, const TFileRangeDesc& range,
812
        const std::vector<SlotDescriptor>& scan_slots,
813
10
        const std::vector<uint32_t>& scan_column_idxs) {
814
10
    DORIS_CHECK(scan_slots.size() == scan_column_idxs.size());
815
10
    auto params = source_params;
816
10
    params.required_slots.clear();
817
10
    params.column_idxs.clear();
818
10
    params.slot_name_to_schema_pos.clear();
819
10
    const std::set partition_names(range.columns_from_path_keys.begin(),
820
10
                                   range.columns_from_path_keys.end());
821
36
    for (size_t slot_idx = 0; slot_idx < scan_slots.size(); ++slot_idx) {
822
26
        const auto& slot = scan_slots[slot_idx];
823
26
        const auto column_idx = scan_column_idxs[slot_idx];
824
26
        TFileScanSlotInfo slot_info;
825
26
        slot_info.__set_slot_id(slot.id());
826
        // Hive V2 checks the Thrift presence bit before trusting is_file_slot. Without it,
827
        // partition columns consume physical file indexes and invalidate the rebuilt projection.
828
26
        bool is_file_slot = !partition_names.contains(slot.col_name());
829
26
        if (source_params.__isset.column_name_to_category) {
830
            // Lazy metadata slots may be absent from phase one's required_slots and have new
831
            // slot IDs here. The pinned schema's name map preserves their original categories.
832
10
            const auto it = source_params.column_name_to_category.find(slot.col_name());
833
10
            const auto category = it != source_params.column_name_to_category.end()
834
10
                                          ? it->second
835
10
                                          : TColumnCategory::REGULAR;
836
10
            slot_info.__set_category(category);
837
10
            is_file_slot =
838
10
                    category == TColumnCategory::REGULAR || category == TColumnCategory::GENERATED;
839
10
        }
840
26
        slot_info.__set_is_file_slot(is_file_slot);
841
26
        if (is_file_slot) {
842
17
            params.column_idxs.emplace_back(column_idx);
843
17
        }
844
26
        params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
845
26
        params.required_slots.emplace_back(slot_info);
846
26
        params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
847
26
    }
848
10
    return params;
849
10
}
850
851
Status RowIdStorageReader::read_lance_rows_by_row_ids(
852
        const TFileRangeDesc& scan_range_desc, const std::vector<uint64_t>& row_ids,
853
        const std::vector<SlotDescriptor>& slots, RuntimeState* runtime_state,
854
        RuntimeProfile* runtime_profile, const TFileScanRangeParams& scan_params, Block* block,
855
0
        RowIdStorageReader::ExternalFetchStatistics* fetch_statistics) {
856
    // Unlike Parquet/ORC, a Lance row ID is a native uint64 ID in a fixed dataset snapshot,
857
    // rather than a row ordinal interpreted by a reader for one physical file range. Phase-two
858
    // fetch therefore opens that dataset snapshot and uses dataset-level take_rows directly. It
859
    // does not create a FileScanner or rescan the fragment split that produced the row ID.
860
0
    std::vector<format::ColumnDefinition> projected_columns;
861
0
    projected_columns.reserve(slots.size());
862
0
    for (const auto& slot : slots) {
863
0
        format::ColumnDefinition column;
864
0
        column.identifier = Field::create_field<TYPE_STRING>(slot.col_name());
865
0
        column.name = slot.col_name();
866
0
        column.type = slot.get_data_type_ptr();
867
0
        projected_columns.emplace_back(std::move(column));
868
0
    }
869
870
0
    format::lance::LanceTableReader reader;
871
0
    auto lance_scan_params = scan_params;
872
0
    RETURN_IF_ERROR(scope_timer_run(
873
0
            [&]() {
874
0
                return reader.init({
875
0
                        .projected_columns = projected_columns,
876
0
                        .conjuncts = {},
877
0
                        .format = format::FileFormat::LANCE,
878
0
                        .scan_params = &lance_scan_params,
879
0
                        .io_ctx = nullptr,
880
0
                        .runtime_state = runtime_state,
881
0
                        .scanner_profile = runtime_profile,
882
0
                });
883
0
            },
884
0
            &fetch_statistics->init_reader_ms));
885
0
    RETURN_IF_ERROR(scope_timer_run(
886
0
            [&]() { return reader.read_by_row_ids(scan_range_desc, row_ids, block); },
887
0
            &fetch_statistics->get_block_ms));
888
0
    RETURN_IF_ERROR(reader.close());
889
890
0
    const auto collect_lance_fetch_time = [&](const std::string& timer_name) {
891
0
        if (const auto* counter = runtime_profile->get_counter(timer_name); counter != nullptr) {
892
0
            fetch_statistics->lance_fetch_times_ns.emplace(timer_name, counter->value());
893
0
        }
894
0
    };
895
0
    collect_lance_fetch_time(LanceDatasetOpenTimeProfile);
896
0
    collect_lance_fetch_time(LanceRowIdTakeReadTimeProfile);
897
0
    collect_lance_fetch_time(LanceArrowToDorisBlockTimeProfile);
898
0
    collect_lance_fetch_time(LanceRowIdFetchTotalTimeProfile);
899
    // close() publishes dataset-handle cache statistics; collect after it and preserve the
900
    // units across the RPC instead of formatting byte/count values as nanoseconds.
901
0
    for (const auto& [name, unit] : LanceFetchCountersProfile) {
902
0
        if (const auto* counter = runtime_profile->get_counter(name); counter != nullptr) {
903
0
            fetch_statistics->lance_fetch_counters.emplace(name, counter->value());
904
0
        }
905
0
    }
906
0
    return Status::OK();
907
0
}
908
909
Status RowIdStorageReader::read_external_row_from_file_mapping(
910
        size_t idx, const std::multimap<uint64_t, size_t>& row_ids,
911
        const std::shared_ptr<FileMapping>& file_mapping,
912
        const std::vector<SlotDescriptor>& scan_slots, const TUniqueId& query_id,
913
        const std::shared_ptr<RuntimeState>& runtime_state, std::vector<Block>& scan_blocks,
914
        std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
915
        std::vector<RowIdStorageReader::ExternalFetchStatistics>& fetch_statistics,
916
        const TFileScanRangeParams& rpc_scan_params,
917
        const std::unordered_map<std::string, int>& colname_to_slot_id,
918
0
        std::counting_semaphore<>& semaphore, TupleDescriptor& tuple_desc) {
919
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
920
0
    signal::set_signal_task_id(query_id);
921
922
    // Release the concurrency permit on every exit path (including error returns
923
    // and exceptions). Completion accounting and status publishing are owned by
924
    // the caller, so the status is always published before the waiter is woken.
925
0
    Defer defer([&] { semaphore.release(); });
926
927
0
    std::vector<uint64_t> read_ids;
928
    // Generate an ordered, deduplicated list with the help of the multimap ordering.
929
0
    for (const auto& [row_id, result_block_idx] : row_ids) {
930
0
        if (read_ids.empty() || read_ids.back() != row_id) {
931
0
            read_ids.emplace_back(row_id);
932
0
        }
933
0
        row_id_block_idx[result_block_idx] = std::make_pair(idx, read_ids.size() - 1);
934
0
    }
935
936
0
    scan_blocks[idx] = Block(scan_slots, read_ids.size());
937
938
0
    auto& external_info = file_mapping->get_external_file_info();
939
0
    auto scan_range_desc = build_external_fetch_range(external_info.scan_range_desc);
940
941
0
    std::unique_ptr<RuntimeProfile> sub_runtime_profile =
942
0
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
943
0
    const auto format_type = scan_range_desc.__isset.format_type ? scan_range_desc.format_type
944
0
                                                                 : rpc_scan_params.format_type;
945
0
    if (format_type == TFileFormatType::FORMAT_LANCE) {
946
0
        RETURN_IF_ERROR(read_lance_rows_by_row_ids(scan_range_desc, read_ids, scan_slots,
947
0
                                                   runtime_state.get(), sub_runtime_profile.get(),
948
0
                                                   rpc_scan_params, &scan_blocks[idx],
949
0
                                                   &fetch_statistics[idx]));
950
0
    } else {
951
        // Parquet/ORC IDs remain signed physical file positions; Lance keeps native uint64 IDs.
952
0
        std::list<int64_t> legacy_read_ids;
953
0
        for (const auto row_id : read_ids) {
954
0
            if (row_id > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
955
0
                return Status::InvalidArgument("legacy external row id exceeds int64 range: {}",
956
0
                                               row_id);
957
0
            }
958
0
            legacy_read_ids.emplace_back(static_cast<int64_t>(row_id));
959
0
        }
960
0
        if (should_use_file_scanner_v2(runtime_state->query_options(), rpc_scan_params,
961
0
                                       scan_range_desc)) {
962
0
            auto file_scanner = FileScannerV2::create_unique(
963
0
                    runtime_state.get(), sub_runtime_profile.get(), &rpc_scan_params,
964
0
                    &colname_to_slot_id, &tuple_desc);
965
0
            RETURN_IF_ERROR(file_scanner->read_by_rows(
966
0
                    scan_range_desc, legacy_read_ids, &scan_blocks[idx],
967
0
                    &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
968
0
        } else {
969
            // Keep phase two on V1 whenever the rollout policy or table format requires it.
970
0
            std::unique_ptr<FileScanner> file_scanner =
971
0
                    FileScanner::create_unique(runtime_state.get(), sub_runtime_profile.get(),
972
0
                                               &rpc_scan_params, &colname_to_slot_id, &tuple_desc);
973
974
0
            RETURN_IF_ERROR(file_scanner->prepare_for_read_lines(scan_range_desc));
975
0
            RETURN_IF_ERROR(file_scanner->read_lines_from_range(
976
0
                    scan_range_desc, legacy_read_ids, &scan_blocks[idx], external_info,
977
0
                    &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
978
0
        }
979
0
    }
980
981
0
    if (scan_blocks[idx].rows() != read_ids.size()) {
982
0
        return Status::InternalError(
983
0
                "Row id fetch scan row count mismatch, "
984
0
                "query_id={}, path={}, expected_rows={}, actual_rows={}",
985
0
                print_id(query_id), scan_range_desc.path, read_ids.size(), scan_blocks[idx].rows());
986
0
    }
987
0
    for (size_t column_id = 0; column_id < scan_blocks[idx].columns(); ++column_id) {
988
0
        const auto& column = scan_blocks[idx].get_by_position(column_id);
989
0
        if (column.column->size() != read_ids.size()) {
990
0
            return Status::InternalError(
991
0
                    "Row id fetch scan column row count mismatch, "
992
0
                    "query_id={}, path={}, column={}, expected_rows={}, actual_rows={}",
993
0
                    print_id(query_id), scan_range_desc.path, column.name, read_ids.size(),
994
0
                    column.column->size());
995
0
        }
996
0
    }
997
998
0
    auto file_read_bytes_counter =
999
0
            sub_runtime_profile->get_counter(FileScannerV2::FileReadBytesProfile);
1000
1001
0
    if (file_read_bytes_counter != nullptr) {
1002
0
        fetch_statistics[idx].file_read_bytes = PrettyPrinter::print(
1003
0
                file_read_bytes_counter->value(), file_read_bytes_counter->type());
1004
0
    }
1005
1006
0
    auto file_read_times_counter =
1007
0
            sub_runtime_profile->get_counter(FileScannerV2::FileReadTimeProfile);
1008
0
    if (file_read_times_counter != nullptr) {
1009
0
        fetch_statistics[idx].file_read_times = PrettyPrinter::print(
1010
0
                file_read_times_counter->value(), file_read_times_counter->type());
1011
0
    }
1012
1013
0
    return Status::OK();
1014
0
}
1015
1016
24
std::string RowIdStorageReader::source_column_key(const SlotDescriptor& slot, uint32_t column_idx) {
1017
24
    fmt::memory_buffer key;
1018
    // Length-prefix each component so distinct sequences cannot alias, e.g.
1019
    // paths ["a", "b"] -> "1:a1:b" while ["a:b"] -> "3:a:b".
1020
164
    auto append = [&key](std::string_view component) {
1021
164
        fmt::format_to(key, "{}:", component.size());
1022
164
        key.append(component.data(), component.data() + component.size());
1023
164
    };
1024
24
    append(slot.col_name());
1025
24
    append(std::to_string(column_idx));
1026
24
    append(std::to_string(slot.col_unique_id()));
1027
24
    append(std::to_string(slot.column_paths().size()));
1028
24
    for (const auto& path : slot.column_paths()) {
1029
12
        append(path);
1030
12
    }
1031
24
    append(std::to_string(slot.all_access_paths().size()));
1032
    // Encode each optional sub-path's presence bit separately from its element
1033
    // count so an absent path ("0") never aliases a present-but-empty path
1034
    // ("1" + size "0").
1035
24
    auto append_optional_path = [&append](bool is_set, const std::vector<std::string>& items) {
1036
14
        append(is_set ? "1" : "0");
1037
14
        if (is_set) {
1038
6
            append(std::to_string(items.size()));
1039
6
            for (const auto& item : items) {
1040
5
                append(item);
1041
5
            }
1042
6
        }
1043
14
    };
1044
24
    for (const auto& path : slot.all_access_paths()) {
1045
7
        append(fmt::format("{}", path.type));
1046
7
        append_optional_path(path.__isset.data_access_path, path.data_access_path.path);
1047
7
        append_optional_path(path.__isset.meta_access_path, path.meta_access_path.path);
1048
7
    }
1049
24
    return fmt::to_string(key);
1050
24
}
1051
1052
Status RowIdStorageReader::submit_external_scan_tasks(
1053
        ScannerScheduler* scheduler, std::counting_semaphore<>& semaphore, size_t task_count,
1054
        const std::function<std::string(size_t)>& make_task_id,
1055
3
        const std::function<Status(size_t)>& run_task) {
1056
    // `completed_count` is a plain counter guarded by `mtx`; the same mutex guards
1057
    // the wait predicate below, so a worker can never notify between the waiter's
1058
    // predicate check and its wait.
1059
3
    AtomicStatus scan_status;
1060
3
    std::condition_variable cv;
1061
3
    std::mutex mtx;
1062
3
    size_t completed_count = 0;
1063
1064
    // Only tasks the scheduler actually accepted are waited for. If a submission
1065
    // fails we stop submitting, but still wait for the already-accepted tasks so
1066
    // their workers cannot outlive the locals they capture by reference.
1067
3
    size_t submitted_count = 0;
1068
12
    for (size_t idx = 0; idx < task_count; ++idx) {
1069
9
        semaphore.acquire();
1070
9
        auto run_one_task = [&, idx]() -> bool {
1071
9
            Status task_status = Status::OK();
1072
            // Publish the status before the completion signal wakes the waiter, on every
1073
            // path. A scanner that throws would otherwise leave scan_status OK while this
1074
            // Defer still counts the task as finished, and the caller would report success
1075
            // over a half-filled result block.
1076
9
            Defer complete([&] {
1077
9
                scan_status.update(task_status);
1078
9
                std::lock_guard<std::mutex> lock(mtx);
1079
9
                ++completed_count;
1080
9
                cv.notify_one();
1081
9
            });
1082
9
            ASSIGN_STATUS_IF_CATCH_EXCEPTION(task_status = run_task(idx), task_status);
1083
9
            return true;
1084
9
        };
1085
9
        Status submit_st = scheduler->submit_scan_task(
1086
9
                SimplifiedScanTask(run_one_task, nullptr, nullptr), make_task_id(idx));
1087
9
        if (!submit_st.ok()) {
1088
0
            scan_status.update(submit_st);
1089
0
            semaphore.release();
1090
0
            break;
1091
0
        }
1092
9
        ++submitted_count;
1093
9
    }
1094
1095
3
    {
1096
3
        std::unique_lock<std::mutex> lock(mtx);
1097
3
        cv.wait(lock, [&] { return completed_count == submitted_count; });
1098
3
    }
1099
3
    return scan_status.ok() ? Status::OK() : scan_status.status();
1100
3
}
1101
1102
Status RowIdStorageReader::read_batch_external_row(
1103
        const uint64_t workload_group_id, const PRequestBlockDesc& request_block_desc,
1104
        std::shared_ptr<IdFileMap> id_file_map, std::vector<SlotDescriptor>& slots,
1105
        std::shared_ptr<FileMapping> first_file_mapping, const TUniqueId& query_id,
1106
        Block& result_block, PRuntimeProfileTree* pprofile, int64_t* init_reader_avg_ms,
1107
0
        int64_t* get_block_avg_ms, size_t* scan_range_cnt) {
1108
0
    TFileScanRangeParams rpc_scan_params;
1109
0
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
1110
0
    std::unordered_map<std::string, int> colname_to_slot_id;
1111
0
    std::shared_ptr<RuntimeState> runtime_state = nullptr;
1112
0
    std::vector<SlotDescriptor> scan_slots;
1113
0
    std::vector<size_t> result_column_to_scan_column;
1114
0
    std::vector<uint32_t> scan_column_idxs;
1115
1116
0
    int max_file_scanners = 0;
1117
0
    {
1118
0
        if (result_block.is_empty_column()) [[likely]] {
1119
0
            result_block = Block(slots, request_block_desc.row_id_size());
1120
0
        }
1121
0
        if (request_block_desc.column_idxs_size() != slots.size()) {
1122
0
            return Status::InternalError(
1123
0
                    "Row id fetch request has mismatched slots and column indexes, "
1124
0
                    "query_id={}, slots={}, column_idxs={}",
1125
0
                    print_id(query_id), slots.size(), request_block_desc.column_idxs_size());
1126
0
        }
1127
1128
0
        auto& external_info = first_file_mapping->get_external_file_info();
1129
0
        int plan_node_id = external_info.plan_node_id;
1130
0
        const auto& first_scan_range_desc = external_info.scan_range_desc;
1131
1132
0
        const auto& external_scan_params = id_file_map->get_external_scan_params();
1133
0
        const auto scan_params = external_scan_params.find(plan_node_id);
1134
0
        if (scan_params == external_scan_params.end()) {
1135
0
            return Status::InternalError("External scan params not found for plan node id {}",
1136
0
                                         plan_node_id);
1137
0
        }
1138
0
        rpc_scan_params = scan_params->second;
1139
0
        if (request_block_desc.row_location_version() ==
1140
0
            static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID)) {
1141
0
            const auto format_type = first_scan_range_desc.__isset.format_type
1142
0
                                             ? first_scan_range_desc.format_type
1143
0
                                             : rpc_scan_params.format_type;
1144
0
            if (format_type != TFileFormatType::FORMAT_LANCE) {
1145
0
                return Status::InvalidArgument(
1146
0
                        "Lance dataset row IDs cannot be fetched with file format {}",
1147
0
                        static_cast<int>(format_type));
1148
0
            }
1149
0
        }
1150
1151
0
        std::unordered_map<std::string, size_t> source_column_to_scan_idx;
1152
1153
0
        result_column_to_scan_column.reserve(slots.size());
1154
0
        scan_slots.reserve(slots.size());
1155
0
        scan_column_idxs.reserve(slots.size());
1156
0
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
1157
0
            const auto& slot = slots[slot_idx];
1158
0
            const auto column_idx = request_block_desc.column_idxs(slot_idx);
1159
0
            const auto key = source_column_key(slot, column_idx);
1160
0
            auto [it, inserted] =
1161
0
                    source_column_to_scan_idx.emplace(key, source_column_to_scan_idx.size());
1162
0
            result_column_to_scan_column.emplace_back(it->second);
1163
0
            if (inserted) {
1164
0
                scan_slots.emplace_back(slot);
1165
0
                scan_column_idxs.emplace_back(column_idx);
1166
0
            }
1167
0
        }
1168
1169
0
        for (auto& slot : scan_slots) {
1170
0
            tuple_desc.add_slot(&slot);
1171
0
            colname_to_slot_id[slot.col_name()] = slot.id();
1172
0
        }
1173
0
        rpc_scan_params = build_external_scan_params(rpc_scan_params, first_scan_range_desc,
1174
0
                                                     scan_slots, scan_column_idxs);
1175
1176
0
        const auto& query_options = id_file_map->get_query_options();
1177
0
        const auto& query_globals = id_file_map->get_query_globals();
1178
        /*
1179
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
1180
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
1181
         *
1182
         * To ensure the same behavior as the scan stage, I get query_options query_globals from id_file_map, then create runtime_state
1183
         * 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.
1184
         */
1185
0
        runtime_state = RuntimeState::create_shared(
1186
0
                query_id, -1, query_options, query_globals, ExecEnv::GetInstance(),
1187
0
                ExecEnv::GetInstance()->rowid_storage_reader_tracker());
1188
1189
0
        max_file_scanners = id_file_map->get_max_file_scanners();
1190
0
    }
1191
1192
    // Hash(TFileRangeDesc) => { all the rows that need to be read and their positions in the result block. } +  file mapping
1193
    // The multimap retains duplicate row IDs because the same source row can appear more than once
1194
    // in the materialized result.
1195
0
    std::map<std::string, std::pair<std::multimap<uint64_t, size_t>, std::shared_ptr<FileMapping>>>
1196
0
            scan_rows;
1197
1198
    // Block corresponding to the order of `scan_rows` map.
1199
0
    std::vector<Block> scan_blocks;
1200
1201
    // row_id (Indexing of vectors) => < In which block, which line in the block >
1202
0
    std::vector<std::pair<size_t, size_t>> row_id_block_idx;
1203
1204
    // Count the time/bytes it takes to read each TFileRangeDesc. (for profile)
1205
0
    std::vector<ExternalFetchStatistics> fetch_statistics;
1206
1207
0
    auto hash_file_range = [&rpc_scan_params](const ExternalFileMappingInfo& external_info) {
1208
0
        const auto& file_range_desc = external_info.scan_range_desc;
1209
0
        const auto format_type = file_range_desc.__isset.format_type ? file_range_desc.format_type
1210
0
                                                                     : rpc_scan_params.format_type;
1211
0
        if (format_type == TFileFormatType::FORMAT_LANCE) {
1212
            // Parquet and ORC row IDs are offsets within a physical file range, so their fetch
1213
            // path must keep each path/start_offset pair separate. Lance row IDs instead belong
1214
            // to a fixed dataset snapshot. Although phase one registers one file mapping per
1215
            // fragment split, phase two uses dataset-level take_rows and can fetch row IDs from
1216
            // all of those fragments together. Group the mappings by scan node, snapshot, and
1217
            // dataset URI; the plan node keeps independent scans of the same snapshot isolated.
1218
0
            const auto& lance_params = file_range_desc.table_format_params.lance_params;
1219
0
            return fmt::format("lance:{}:{}:{}", external_info.plan_node_id, lance_params.version,
1220
0
                               lance_params.dataset_uri);
1221
0
        }
1222
0
        std::string value;
1223
0
        value.resize(file_range_desc.path.size() + sizeof(file_range_desc.start_offset));
1224
0
        auto* ptr = value.data();
1225
1226
0
        memcpy(ptr, &file_range_desc.start_offset, sizeof(file_range_desc.start_offset));
1227
0
        ptr += sizeof(file_range_desc.start_offset);
1228
0
        memcpy(ptr, file_range_desc.path.data(), file_range_desc.path.size());
1229
0
        return value;
1230
0
    };
1231
1232
0
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
1233
0
        auto file_id = request_block_desc.file_id(j);
1234
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
1235
0
        if (!file_mapping) {
1236
0
            return Status::InternalError(
1237
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
1238
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
1239
0
        }
1240
1241
0
        const auto& external_info = file_mapping->get_external_file_info();
1242
0
        const auto& scan_range_hash = hash_file_range(external_info);
1243
0
        if (scan_rows.contains(scan_range_hash)) {
1244
0
            scan_rows.at(scan_range_hash).first.emplace(request_block_desc.row_id(j), j);
1245
0
        } else {
1246
0
            std::multimap<uint64_t, size_t> rows {{request_block_desc.row_id(j), j}};
1247
0
            scan_rows.emplace(scan_range_hash, std::make_pair(std::move(rows), file_mapping));
1248
0
        }
1249
0
    }
1250
1251
0
    scan_blocks.resize(scan_rows.size());
1252
0
    row_id_block_idx.resize(request_block_desc.row_id_size());
1253
0
    fetch_statistics.resize(scan_rows.size());
1254
1255
    // Get the workload group for subsequent scan task submission.
1256
0
    std::vector<uint64_t> workload_group_ids;
1257
0
    workload_group_ids.emplace_back(workload_group_id);
1258
0
    auto wg = ExecEnv::GetInstance()->workload_group_mgr()->get_group(workload_group_ids);
1259
0
    doris::TaskScheduler* exec_sched = nullptr;
1260
0
    ScannerScheduler* scan_sched = nullptr;
1261
0
    ScannerScheduler* remote_scan_sched = nullptr;
1262
0
    wg->get_query_scheduler(&exec_sched, &scan_sched, &remote_scan_sched);
1263
0
    DCHECK(remote_scan_sched);
1264
1265
0
    int64_t scan_running_time = 0;
1266
0
    RETURN_IF_ERROR(scope_timer_run(
1267
0
            [&]() -> Status {
1268
                //semaphore: Limit the number of scan tasks submitted at one time
1269
0
                std::counting_semaphore semaphore {max_file_scanners};
1270
1271
0
                std::vector<
1272
0
                        std::pair<std::multimap<uint64_t, size_t>, std::shared_ptr<FileMapping>>>
1273
0
                        scan_info_list;
1274
0
                scan_info_list.reserve(scan_rows.size());
1275
0
                for (const auto& [_, scan_info] : scan_rows) {
1276
0
                    scan_info_list.emplace_back(scan_info);
1277
0
                }
1278
1279
0
                return submit_external_scan_tasks(
1280
0
                        remote_scan_sched, semaphore, scan_rows.size(),
1281
0
                        [&](size_t idx) {
1282
0
                            return fmt::format("{}-read_batch_external_row-{}", print_id(query_id),
1283
0
                                               idx);
1284
0
                        },
1285
0
                        [&](size_t idx) -> Status {
1286
0
                            const auto& [row_ids, file_mapping] = scan_info_list[idx];
1287
0
                            return read_external_row_from_file_mapping(
1288
0
                                    idx, row_ids, file_mapping, scan_slots, query_id, runtime_state,
1289
0
                                    scan_blocks, row_id_block_idx, fetch_statistics,
1290
0
                                    rpc_scan_params, colname_to_slot_id, semaphore, tuple_desc);
1291
0
                        });
1292
0
            },
1293
0
            &scan_running_time));
1294
1295
    // Insert the read data into result_block. Use insert_indices_from() instead of
1296
    // scatter_scan_blocks_to_result_block()/insert_from_multi_column(), because
1297
    // scan_blocks may have fewer columns than result_block when duplicate physical columns
1298
    // are deduplicated, and insert_from_multi_column() cannot handle ColumnString
1299
    // cross-type (32/64) copies safely.
1300
0
    const size_t result_column_count = result_block.columns();
1301
0
    for (size_t column_id = 0; column_id < result_column_count; column_id++) {
1302
0
        auto dst_col_guard = result_block.mutate_column_scoped(column_id);
1303
0
        MutableColumnPtr& dst_col = dst_col_guard.mutable_column();
1304
1305
0
        bool dst_is_nullable = dst_col->is_nullable();
1306
0
        std::vector<ColumnPtr> nullable_src_columns(scan_blocks.size());
1307
0
        auto scan_column_id = result_column_to_scan_column[column_id];
1308
0
        for (const auto& [pos_block, block_idx] : row_id_block_idx) {
1309
0
            DCHECK_GT(scan_blocks.size(), pos_block);
1310
0
            DCHECK_GT(scan_blocks[pos_block].columns(), scan_column_id);
1311
0
            const auto& src_column_ptr =
1312
0
                    scan_blocks[pos_block].get_by_position(scan_column_id).column;
1313
0
            const auto* src_col = src_column_ptr.get();
1314
0
            if (dst_is_nullable && !src_col->is_nullable()) {
1315
0
                if (!nullable_src_columns[pos_block]) {
1316
0
                    nullable_src_columns[pos_block] = make_nullable(src_column_ptr);
1317
0
                }
1318
0
                src_col = nullable_src_columns[pos_block].get();
1319
0
            }
1320
0
            if (block_idx >= src_col->size()) {
1321
0
                return Status::InternalError(
1322
0
                        "Row id fetch source index out of range, query_id={}, column={}, "
1323
0
                        "source_block={}, source_rows={}, row_index={}",
1324
0
                        print_id(query_id), result_block.get_by_position(column_id).name, pos_block,
1325
0
                        src_col->size(), block_idx);
1326
0
            }
1327
0
            uint32_t scan_position = cast_set<uint32_t>(block_idx);
1328
0
            dst_col->insert_indices_from(*src_col, &scan_position, &scan_position + 1);
1329
0
        }
1330
0
    }
1331
1332
    // Statistical runtime profile information.
1333
0
    std::unique_ptr<RuntimeProfile> runtime_profile =
1334
0
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
1335
0
    {
1336
0
        runtime_profile->add_info_string(ScannersRunningTimeProfile,
1337
0
                                         std::to_string(scan_running_time) + "ms");
1338
0
        fmt::memory_buffer file_read_lines_buffer;
1339
0
        format_to(file_read_lines_buffer, "[");
1340
0
        fmt::memory_buffer file_read_bytes_buffer;
1341
0
        format_to(file_read_bytes_buffer, "[");
1342
0
        fmt::memory_buffer file_read_times_buffer;
1343
0
        format_to(file_read_times_buffer, "[");
1344
1345
0
        std::map<std::string, int64_t> lance_fetch_times_ns;
1346
0
        std::map<std::string, int64_t> lance_fetch_counters;
1347
0
        size_t idx = 0;
1348
0
        for (const auto& [_, scan_info] : scan_rows) {
1349
0
            format_to(file_read_lines_buffer, "{}, ", scan_info.first.size());
1350
0
            *init_reader_avg_ms += fetch_statistics[idx].init_reader_ms;
1351
0
            *get_block_avg_ms += fetch_statistics[idx].get_block_ms;
1352
0
            format_to(file_read_bytes_buffer, "{}, ", fetch_statistics[idx].file_read_bytes);
1353
0
            format_to(file_read_times_buffer, "{}, ", fetch_statistics[idx].file_read_times);
1354
0
            for (const auto& [time_name, time_value] : fetch_statistics[idx].lance_fetch_times_ns) {
1355
0
                lance_fetch_times_ns[time_name] += time_value;
1356
0
            }
1357
0
            for (const auto& [name, value] : fetch_statistics[idx].lance_fetch_counters) {
1358
0
                lance_fetch_counters[name] += value;
1359
0
            }
1360
0
            idx++;
1361
0
        }
1362
1363
0
        format_to(file_read_lines_buffer, "]");
1364
0
        format_to(file_read_bytes_buffer, "]");
1365
0
        format_to(file_read_times_buffer, "]");
1366
1367
0
        *init_reader_avg_ms /= fetch_statistics.size();
1368
0
        *get_block_avg_ms /= fetch_statistics.size();
1369
0
        runtime_profile->add_info_string(InitReaderAvgTimeProfile,
1370
0
                                         std::to_string(*init_reader_avg_ms) + "ms");
1371
0
        runtime_profile->add_info_string(GetBlockAvgTimeProfile,
1372
0
                                         std::to_string(*get_block_avg_ms) + "ms");
1373
0
        runtime_profile->add_info_string(FileReadLinesProfile,
1374
0
                                         fmt::to_string(file_read_lines_buffer));
1375
0
        runtime_profile->add_info_string(FileScannerV2::FileReadBytesProfile,
1376
0
                                         fmt::to_string(file_read_bytes_buffer));
1377
0
        runtime_profile->add_info_string(FileScannerV2::FileReadTimeProfile,
1378
0
                                         fmt::to_string(file_read_times_buffer));
1379
0
        for (const auto& [name, value] : lance_fetch_counters) {
1380
0
            runtime_profile->add_info_string(
1381
0
                    name, PrettyPrinter::print(value, LanceFetchCountersProfile.at(name)));
1382
0
        }
1383
0
        for (const auto& [time_name, time_value] : lance_fetch_times_ns) {
1384
0
            runtime_profile->add_info_string(time_name,
1385
0
                                             PrettyPrinter::print(time_value, TUnit::TIME_NS));
1386
0
        }
1387
0
    }
1388
1389
0
    runtime_profile->to_proto(pprofile, 2);
1390
1391
0
    *scan_range_cnt = scan_rows.size();
1392
1393
0
    return Status::OK();
1394
0
}
1395
1396
Status RowIdStorageReader::read_doris_format_row(
1397
        const std::shared_ptr<IdFileMap>& id_file_map,
1398
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<uint32_t>& row_ids,
1399
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
1400
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
1401
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
1402
        int64_t* lookup_row_data_ms, std::unordered_map<SegKey, SegItem, HashOfSegKey>& seg_map,
1403
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
1404
0
        io::FileCacheMissPolicy file_cache_miss_policy, Block& result_block) {
1405
0
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
1406
0
    SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
1407
1408
0
    BaseTabletSPtr tablet;
1409
0
    BetaRowsetSharedPtr rowset;
1410
0
    SegmentSharedPtr segment;
1411
0
    if (seg_map.find(seg_key) == seg_map.end()) {
1412
0
        tablet = scope_timer_run(
1413
0
                [&]() {
1414
0
                    auto res = ExecEnv::get_tablet(tablet_id);
1415
0
                    return !res.has_value() ? nullptr
1416
0
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
1417
0
                },
1418
0
                acquire_tablet_ms);
1419
0
        if (!tablet) {
1420
0
            return Status::InternalError(
1421
0
                    "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1422
0
                    "row_id: {}",
1423
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1424
0
                    row_ids[0]);
1425
0
        }
1426
1427
0
        rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
1428
0
                [&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
1429
0
                acquire_rowsets_ms));
1430
0
        if (!rowset) {
1431
0
            return Status::InternalError(
1432
0
                    "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1433
0
                    "row_id: {}",
1434
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1435
0
                    row_ids[0]);
1436
0
        }
1437
1438
0
        SegmentCacheHandle segment_cache;
1439
0
        RETURN_IF_ERROR(scope_timer_run(
1440
0
                [&]() {
1441
0
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
1442
0
                },
1443
0
                acquire_segments_ms));
1444
1445
0
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
1446
0
                               segment_cache.get_segments().cend(),
1447
0
                               [segment_id](const segment_v2::SegmentSharedPtr& seg) {
1448
0
                                   return seg->id() == segment_id;
1449
0
                               });
1450
0
        if (it == segment_cache.get_segments().end()) {
1451
0
            return Status::InternalError(
1452
0
                    "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1453
0
                    "row_id: {}",
1454
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1455
0
                    row_ids[0]);
1456
0
        }
1457
0
        segment = *it;
1458
0
        seg_map[seg_key] = SegItem {.tablet = tablet, .rowset = rowset, .segment = segment};
1459
0
    } else {
1460
0
        auto& seg_item = seg_map[seg_key];
1461
0
        tablet = seg_item.tablet;
1462
0
        rowset = seg_item.rowset;
1463
0
        segment = seg_item.segment;
1464
0
    }
1465
1466
    // if row_store_read_struct not empty, means the line we should read from row_store
1467
0
    if (!row_store_read_struct.default_values.empty()) {
1468
0
        if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
1469
0
            return Status::InternalError("Tablet {} does not have row store for all columns",
1470
0
                                         tablet->tablet_id());
1471
0
        }
1472
0
        auto result_columns_guard = result_block.mutate_columns_scoped();
1473
0
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
1474
0
        io::IOContext io_ctx;
1475
0
        io_ctx.reader_type = ReaderType::READER_QUERY;
1476
0
        io_ctx.file_cache_stats = &stats.file_cache_stats;
1477
0
        io_ctx.file_cache_miss_policy = file_cache_miss_policy;
1478
0
        for (auto row_id : row_ids) {
1479
0
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_id));
1480
0
            row_store_read_struct.row_store_buffer.clear();
1481
0
            RETURN_IF_ERROR(scope_timer_run(
1482
0
                    [&]() {
1483
0
                        return tablet->lookup_row_data({}, loc, rowset, stats,
1484
0
                                                       row_store_read_struct.row_store_buffer,
1485
0
                                                       false, &io_ctx);
1486
0
                    },
1487
0
                    lookup_row_data_ms));
1488
1489
0
            RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
1490
0
                    row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
1491
0
                    row_store_read_struct.row_store_buffer.size(),
1492
0
                    row_store_read_struct.col_uid_to_idx, result_columns,
1493
0
                    row_store_read_struct.default_values, {}));
1494
0
        }
1495
0
    } else {
1496
0
        for (int x = 0; x < slots.size(); ++x) {
1497
0
            auto column_guard = result_block.mutate_column_scoped(x);
1498
0
            MutableColumnPtr& column = column_guard.mutable_column();
1499
0
            IteratorKey iterator_key {.tablet_id = tablet_id,
1500
0
                                      .rowset_id = rowset_id,
1501
0
                                      .segment_id = segment_id,
1502
0
                                      .slot_id = slots[x].id()};
1503
0
            IteratorItem& iterator_item = iterator_map[iterator_key];
1504
0
            if (iterator_item.segment == nullptr) {
1505
0
                iterator_map[iterator_key].segment = segment;
1506
0
                iterator_item.storage_read_options.stats = &stats;
1507
0
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
1508
0
                iterator_item.storage_read_options.io_ctx.file_cache_miss_policy =
1509
0
                        file_cache_miss_policy;
1510
0
            }
1511
0
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
1512
0
            for (auto row_id : row_ids) {
1513
0
                RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
1514
0
                        full_read_schema, &slots[x], row_id, column,
1515
0
                        iterator_item.storage_read_options, iterator_item.iterator));
1516
0
            }
1517
0
        }
1518
0
    }
1519
0
    return Status::OK();
1520
0
}
1521
1522
#include "common/compile_check_end.h"
1523
1524
} // namespace doris