Coverage Report

Created: 2026-10-29 13:21

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
// Groups all row_ids belonging to the same segment for batched reading.
382
// Position index tracks where each row_id originated in the original request,
383
// so results can be scattered back to the correct output positions.
384
struct DorisFormatReadBatch {
385
    std::shared_ptr<FileMapping> file_mapping;
386
    // (row_id, index_in_request) pairs for all rows in this segment.
387
    std::vector<std::pair<segment_v2::rowid_t, size_t>> row_ids_with_positions;
388
};
389
390
static void scatter_scan_blocks_to_result_block(
391
        const std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
392
0
        std::vector<Block>& scan_blocks, Block& result_block) {
393
0
    for (size_t column_id = 0; column_id < result_block.columns(); ++column_id) {
394
0
        auto column_guard = result_block.mutate_column_scoped(column_id);
395
0
        MutableColumnPtr& dst_col = column_guard.mutable_column();
396
0
        for (const auto& [pos_block, block_idx] : row_id_block_idx) {
397
0
            DCHECK(scan_blocks.size() > pos_block);
398
0
            DCHECK(scan_blocks[pos_block].columns() > column_id);
399
0
            const auto& src_col = *scan_blocks[pos_block].get_by_position(column_id).column;
400
0
            uint32_t scan_position = cast_set<uint32_t>(block_idx);
401
0
            dst_col->insert_indices_from(src_col, &scan_position, &scan_position + 1);
402
0
        }
403
0
    }
404
0
}
405
406
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequest& request,
407
2
                                          PMultiGetResponse* response) {
408
    // read from storage engine row id by row id
409
2
    OlapReaderStatistics stats;
410
2
    Block result_block;
411
2
    int64_t acquire_tablet_ms = 0;
412
2
    int64_t acquire_rowsets_ms = 0;
413
2
    int64_t acquire_segments_ms = 0;
414
2
    int64_t lookup_row_data_ms = 0;
415
416
    // init desc
417
2
    std::vector<SlotDescriptor> slots;
418
2
    slots.reserve(request.slots().size());
419
4
    for (const auto& pslot : request.slots()) {
420
4
        slots.push_back(SlotDescriptor(pslot));
421
4
    }
422
423
    // init read schema
424
2
    TabletSchema full_read_schema;
425
2
    for (const ColumnPB& column_pb : request.column_desc()) {
426
2
        full_read_schema.append_column(TabletColumn(column_pb));
427
2
    }
428
429
2
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
430
    // read row by row
431
8
    for (int i = 0; i < request.row_locs_size(); ++i) {
432
6
        const auto& row_loc = request.row_locs(i);
433
6
        MonotonicStopWatch watch;
434
6
        watch.start();
435
6
        BaseTabletSPtr tablet = scope_timer_run(
436
6
                [&]() {
437
6
                    auto res = ExecEnv::get_tablet(row_loc.tablet_id(), nullptr, true);
438
6
                    return !res.has_value() ? nullptr
439
6
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
440
6
                },
441
6
                &acquire_tablet_ms);
442
6
        RowsetId rowset_id;
443
6
        rowset_id.init(row_loc.rowset_id());
444
6
        if (!tablet) {
445
0
            continue;
446
0
        }
447
        // We ensured it's rowset is not released when init Tablet reader param, rowset->update_delayed_expired_timestamp();
448
6
        BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
449
6
                [&]() {
450
6
                    return ExecEnv::GetInstance()->storage_engine().get_quering_rowset(rowset_id);
451
6
                },
452
6
                &acquire_rowsets_ms));
453
6
        if (!rowset) {
454
0
            LOG(INFO) << "no such rowset " << rowset_id;
455
0
            continue;
456
0
        }
457
6
        size_t row_size = 0;
458
6
        Defer _defer([&]() {
459
6
            LOG_EVERY_N(INFO, 100)
460
1
                    << "multiget_data single_row, cost(us):" << watch.elapsed_time() / 1000
461
1
                    << ", row_size:" << row_size;
462
6
            *response->add_row_locs() = row_loc;
463
6
        });
464
        // TODO: supoort session variable enable_page_cache and disable_file_cache if necessary.
465
6
        SegmentCacheHandle segment_cache;
466
6
        RETURN_IF_ERROR(scope_timer_run(
467
6
                [&]() {
468
6
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
469
6
                },
470
6
                &acquire_segments_ms));
471
        // find segment
472
6
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
473
6
                               segment_cache.get_segments().cend(),
474
6
                               [&row_loc](const segment_v2::SegmentSharedPtr& seg) {
475
6
                                   return seg->id() == row_loc.segment_id();
476
6
                               });
477
6
        if (it == segment_cache.get_segments().end()) {
478
0
            continue;
479
0
        }
480
6
        segment_v2::SegmentSharedPtr segment = *it;
481
6
        GlobalRowLoacation row_location(row_loc.tablet_id(), rowset->rowset_id(),
482
6
                                        cast_set<uint32_t>(row_loc.segment_id()),
483
6
                                        cast_set<uint32_t>(row_loc.ordinal_id()));
484
        // fetch by row store, more effcient way
485
6
        if (request.fetch_row_store()) {
486
0
            if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
487
0
                return Status::InternalError("Tablet {} does not have row store for all columns",
488
0
                                             tablet->tablet_id());
489
0
            }
490
0
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_loc.ordinal_id()));
491
0
            std::string* value = response->add_binary_row_data();
492
0
            RETURN_IF_ERROR(scope_timer_run(
493
0
                    [&]() { return tablet->lookup_row_data({}, loc, rowset, stats, *value); },
494
0
                    &lookup_row_data_ms));
495
0
            row_size = value->size();
496
0
            continue;
497
0
        }
498
499
        // fetch by column store
500
6
        if (result_block.is_empty_column()) {
501
2
            result_block = Block(slots, request.row_locs().size());
502
2
        }
503
6
        VLOG_DEBUG << "Read row location "
504
0
                   << fmt::format("{}, {}, {}, {}", row_location.tablet_id,
505
0
                                  row_location.row_location.rowset_id.to_string(),
506
0
                                  row_location.row_location.segment_id,
507
0
                                  row_location.row_location.row_id);
508
18
        for (int x = 0; x < slots.size(); ++x) {
509
12
            std::vector<segment_v2::rowid_t> row_ids {
510
12
                    static_cast<segment_v2::rowid_t>(row_loc.ordinal_id())};
511
            // The scoped mutation republishes a potentially replaced V2 column when the reader
512
            // transfers ownership of its first assembled batch.
513
12
            auto column_guard = result_block.mutate_column_scoped(x);
514
12
            MutableColumnPtr& column = column_guard.mutable_column();
515
12
            IteratorKey iterator_key {.tablet_id = tablet->tablet_id(),
516
12
                                      .rowset_id = rowset_id,
517
12
                                      .segment_id = row_loc.segment_id(),
518
12
                                      .slot_id = slots[x].id()};
519
12
            IteratorItem& iterator_item = iterator_map[iterator_key];
520
12
            if (iterator_item.segment == nullptr) {
521
                // hold the reference
522
4
                iterator_map[iterator_key].segment = segment;
523
4
                iterator_item.storage_read_options.stats = &stats;
524
4
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
525
4
            }
526
12
            segment = iterator_item.segment;
527
12
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
528
12
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
529
12
                    full_read_schema, &slots[x], row_ids, column,
530
12
                    iterator_item.storage_read_options, iterator_item.iterator));
531
12
        }
532
6
    }
533
    // serialize block if not empty
534
2
    if (!result_block.is_empty_column()) {
535
2
        VLOG_DEBUG << "dump block:" << result_block.dump_data(0, 10)
536
0
                   << ", be_exec_version:" << request.be_exec_version();
537
2
        [[maybe_unused]] size_t compressed_size = 0;
538
2
        [[maybe_unused]] size_t uncompressed_size = 0;
539
2
        [[maybe_unused]] int64_t compress_time = 0;
540
2
        int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
541
2
        RETURN_IF_ERROR(result_block.serialize(be_exec_version, response->mutable_block(),
542
2
                                               &uncompressed_size, &compressed_size, &compress_time,
543
2
                                               segment_v2::CompressionTypePB::LZ4));
544
2
    }
545
546
2
    LOG(INFO) << "Query stats: "
547
2
              << fmt::format(
548
2
                         "query_id:{}, "
549
2
                         "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
550
2
                         "io_latency:{}ns, "
551
2
                         "uncompressed_bytes_read:{},"
552
2
                         "bytes_read:{},"
553
2
                         "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
554
2
                         "lookup_row_data_ms:{}",
555
2
                         print_id(request.query_id()), stats.cached_pages_num,
556
2
                         stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
557
2
                         stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
558
2
                         acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms);
559
2
    return Status::OK();
560
2
}
561
562
void RowIdStorageReader::read_by_rowids_for_rpc(const PMultiGetRequestV2& request,
563
1
                                                PMultiGetResponseV2* response) {
564
1
    Status st = Status::OK();
565
1
    ASSIGN_STATUS_IF_CATCH_EXCEPTION(st = read_by_rowids(request, response), st);
566
1
    st.to_protobuf(response->mutable_status());
567
1
}
568
569
Status RowIdStorageReader::read_by_rowids(const PMultiGetRequestV2& request,
570
1
                                          PMultiGetResponseV2* response) {
571
1
    if (request.request_block_descs_size()) {
572
1
        auto tquery_id = ((UniqueId)request.query_id()).to_thrift();
573
        // todo: use mutableBlock instead of block
574
1
        std::vector<Block> result_blocks(request.request_block_descs_size());
575
576
1
        OlapReaderStatistics stats;
577
1
        int64_t acquire_tablet_ms = 0;
578
1
        int64_t acquire_rowsets_ms = 0;
579
1
        int64_t acquire_segments_ms = 0;
580
1
        int64_t lookup_row_data_ms = 0;
581
582
1
        int64_t external_init_reader_avg_ms = 0;
583
1
        int64_t external_get_block_avg_ms = 0;
584
1
        size_t external_scan_range_cnt = 0;
585
586
1
        const auto file_cache_miss_policy =
587
1
                request.file_cache_remote_only_on_miss()
588
1
                        ? io::FileCacheMissPolicy::REMOTE_ONLY_ON_MISS
589
1
                        : io::FileCacheMissPolicy::READ_THROUGH_AND_WRITE_BACK;
590
591
        // Add counters for different file mapping types
592
1
        std::unordered_map<FileMappingType, int64_t> file_type_counts;
593
594
1
        auto id_file_map =
595
1
                ExecEnv::GetInstance()->get_id_manager()->get_id_file_map(request.query_id());
596
        // if id_file_map is null, means the BE not have scan range, just return ok
597
1
        if (!id_file_map) {
598
            // padding empty block to response
599
0
            LOG(INFO) << "id_file_map not found for query_id: " << print_id(request.query_id());
600
0
            for (int i = 0; i < request.request_block_descs_size(); ++i) {
601
0
                response->add_blocks();
602
0
            }
603
0
            return Status::OK();
604
0
        }
605
606
1
        for (int i = 0; i < request.request_block_descs_size(); ++i) {
607
1
            const auto& request_block_desc = request.request_block_descs(i);
608
1
            PMultiGetBlockV2* pblock = response->add_blocks();
609
1
            if (request_block_desc.row_id_size() >= 1) {
610
1
                if (request_block_desc.file_id_size() != request_block_desc.row_id_size()) {
611
0
                    return Status::InvalidArgument(
612
0
                            "Row-id fetch has mismatched file_id and row_id counts: "
613
0
                            "file_ids={}, row_ids={}",
614
0
                            request_block_desc.file_id_size(), request_block_desc.row_id_size());
615
0
                }
616
1
                const auto row_location_version = request_block_desc.row_location_version();
617
1
                switch (row_location_version) {
618
1
                case static_cast<uint32_t>(ROW_VERSION::FILE_LOCAL_ROW_ID):
619
1
                case static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID):
620
1
                    break;
621
0
                default:
622
0
                    return Status::NotSupported("unsupported row location version in fetch: {}",
623
0
                                                row_location_version);
624
1
                }
625
                // Rows in this request block belong to the same relation. The first mapping is
626
                // sufficient to select the internal/external fetch path; individual file IDs
627
                // are still used below to group the actual reads.
628
1
                const auto first_file_id = request_block_desc.file_id(0);
629
1
                auto first_file_mapping = id_file_map->get_file_mapping(first_file_id);
630
1
                if (!first_file_mapping) {
631
0
                    return Status::InternalError(
632
0
                            "Backend:{} file mapping not found, query_id: {}, file_id: {}",
633
0
                            BackendOptions::get_localhost(), print_id(request.query_id()),
634
0
                            first_file_id);
635
0
                }
636
1
                if (first_file_mapping->type != FileMappingType::EXTERNAL &&
637
1
                    row_location_version ==
638
1
                            static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID)) {
639
0
                    return Status::InvalidArgument(
640
0
                            "Lance dataset row IDs require an external file mapping");
641
0
                }
642
1
                file_type_counts[first_file_mapping->type] += request_block_desc.row_id_size();
643
644
                // prepare slots to build block
645
1
                std::vector<SlotDescriptor> slots;
646
1
                slots.reserve(request_block_desc.slots_size());
647
1
                for (const auto& pslot : request_block_desc.slots()) {
648
1
                    slots.push_back(SlotDescriptor(pslot));
649
1
                }
650
1
                try {
651
1
                    if (first_file_mapping->type == FileMappingType::INTERNAL) {
652
0
                        RETURN_IF_ERROR(read_batch_doris_format_row(
653
0
                                request_block_desc, id_file_map, slots, tquery_id, result_blocks[i],
654
0
                                stats, &acquire_tablet_ms, &acquire_rowsets_ms,
655
0
                                &acquire_segments_ms, &lookup_row_data_ms, file_cache_miss_policy));
656
1
                    } else {
657
1
                        RETURN_IF_ERROR(read_batch_external_row(
658
1
                                request.wg_id(), request_block_desc, id_file_map, slots,
659
1
                                first_file_mapping, tquery_id, result_blocks[i],
660
1
                                pblock->mutable_profile(), &external_init_reader_avg_ms,
661
1
                                &external_get_block_avg_ms, &external_scan_range_cnt));
662
1
                    }
663
1
                } catch (const Exception& e) {
664
0
                    return Status::Error<false>(e.code(), "Row id fetch failed because {}",
665
0
                                                e.what());
666
0
                }
667
1
            }
668
669
0
            [[maybe_unused]] size_t compressed_size = 0;
670
0
            [[maybe_unused]] size_t uncompressed_size = 0;
671
0
            [[maybe_unused]] int64_t compress_time = 0;
672
0
            int be_exec_version = request.has_be_exec_version() ? request.be_exec_version() : 0;
673
0
            RETURN_IF_ERROR(result_blocks[i].serialize(
674
0
                    be_exec_version, pblock->mutable_block(), &uncompressed_size, &compressed_size,
675
0
                    &compress_time, segment_v2::CompressionTypePB::LZ4));
676
0
        }
677
678
        // Build file type statistics string
679
0
        std::string file_type_stats;
680
0
        for (const auto& [type, count] : file_type_counts) {
681
0
            if (!file_type_stats.empty()) {
682
0
                file_type_stats += ", ";
683
0
            }
684
0
            file_type_stats += fmt::format("{}:{}", type, count);
685
0
        }
686
687
0
        LOG(INFO) << "Query stats: "
688
0
                  << fmt::format(
689
0
                             "query_id:{}, "
690
0
                             "Internal table:"
691
0
                             "hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
692
0
                             "io_latency:{}ns, uncompressed_bytes_read:{}, bytes_read:{}, "
693
0
                             "acquire_tablet_ms:{}, acquire_rowsets_ms:{}, acquire_segments_ms:{}, "
694
0
                             "lookup_row_data_ms:{}, file_types:[{}]; "
695
0
                             "External table : init_reader_ms:{}, get_block_ms:{}, "
696
0
                             "external_scan_range_cnt:{}",
697
0
                             print_id(request.query_id()), stats.cached_pages_num,
698
0
                             stats.total_pages_num, stats.compressed_bytes_read, stats.io_ns,
699
0
                             stats.uncompressed_bytes_read, stats.bytes_read, acquire_tablet_ms,
700
0
                             acquire_rowsets_ms, acquire_segments_ms, lookup_row_data_ms,
701
0
                             file_type_stats, external_init_reader_avg_ms,
702
0
                             external_get_block_avg_ms, external_scan_range_cnt);
703
0
        set_topn_lazy_materialization_file_cache_stats(
704
0
                stats.file_cache_stats,
705
0
                response->mutable_topn_lazy_materialization_file_cache_stats());
706
0
    }
707
708
0
    if (request.has_gc_id_map() && request.gc_id_map()) {
709
0
        ExecEnv::GetInstance()->get_id_manager()->remove_id_file_map(request.query_id());
710
0
    }
711
712
0
    return Status::OK();
713
1
}
714
715
Status RowIdStorageReader::read_batch_doris_format_row(
716
        const PRequestBlockDesc& request_block_desc, std::shared_ptr<IdFileMap> id_file_map,
717
        std::vector<SlotDescriptor>& slots, const TUniqueId& query_id, Block& result_block,
718
        OlapReaderStatistics& stats, int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms,
719
        int64_t* acquire_segments_ms, int64_t* lookup_row_data_ms,
720
0
        io::FileCacheMissPolicy file_cache_miss_policy) {
721
0
    if (result_block.is_empty_column()) [[likely]] {
722
0
        result_block = Block(slots, request_block_desc.row_id_size());
723
0
    }
724
0
    TabletSchema full_read_schema;
725
0
    for (const ColumnPB& column_pb : request_block_desc.column_descs()) {
726
0
        full_read_schema.append_column(TabletColumn(column_pb));
727
0
    }
728
729
0
    std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey> iterator_map;
730
0
    std::unordered_map<SegKey, SegItem, HashOfSegKey> seg_map;
731
0
    std::string row_store_buffer;
732
0
    RowStoreReadStruct row_store_read_struct(row_store_buffer);
733
0
    if (request_block_desc.fetch_row_store()) {
734
0
        for (int i = 0; i < request_block_desc.slots_size(); ++i) {
735
0
            row_store_read_struct.serdes.emplace_back(slots[i].get_data_type_ptr()->get_serde());
736
0
            row_store_read_struct.col_uid_to_idx[slots[i].col_unique_id()] = i;
737
0
            row_store_read_struct.default_values.emplace_back(slots[i].col_default_value());
738
0
        }
739
0
    }
740
741
    // Phase 1: Group all row_ids by their (tablet_id, rowset_id, segment_id) key.
742
    // Unlike the old code which only batched adjacent rows with the same file_id,
743
    // this merges non-contiguous same-segment requests into a single batch,
744
    // maximizing the number of rows read per seek_and_read_by_rowid call.
745
0
    std::vector<DorisFormatReadBatch> scan_batches;
746
0
    std::unordered_map<SegKey, size_t, HashOfSegKey> batch_idx_by_seg;
747
    // (batch_idx, position_in_batch) for each row in the original request.
748
0
    std::vector<std::pair<size_t, size_t>> row_id_block_idx(request_block_desc.row_id_size());
749
0
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
750
0
        auto file_id = request_block_desc.file_id(j);
751
0
        const auto row_id = request_block_desc.row_id(j);
752
0
        if (row_id > std::numeric_limits<uint32_t>::max()) {
753
0
            return Status::InvalidArgument("internal row id exceeds uint32 range: {}", row_id);
754
0
        }
755
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
756
0
        if (!file_mapping) {
757
0
            return Status::InternalError(
758
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
759
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
760
0
        }
761
762
        // Derive segment key and group by it — rows from the same segment are batched together
763
        // even if they are interleaved with rows from other segments in the request.
764
0
        auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
765
0
        SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
766
0
        auto [it, inserted] = batch_idx_by_seg.emplace(seg_key, scan_batches.size());
767
0
        if (inserted) {
768
            // First time seeing this segment, create a new batch for it.
769
0
            scan_batches.emplace_back();
770
0
            scan_batches.back().file_mapping = file_mapping;
771
0
        }
772
        // Record (row_id, original_request_index) for later sorting and scattering.
773
0
        scan_batches[it->second].row_ids_with_positions.emplace_back(static_cast<uint32_t>(row_id),
774
0
                                                                     j);
775
0
    }
776
777
    // Phase 2: For each segment, sort row_ids ascending (required by ColumnIterator),
778
    // deduplicate, then read all rows in a single batch call.
779
0
    std::vector<Block> scan_blocks(scan_batches.size());
780
0
    for (size_t batch_idx = 0; batch_idx < scan_batches.size(); ++batch_idx) {
781
0
        auto& scan_batch = scan_batches[batch_idx];
782
0
        auto& row_ids_with_positions = scan_batch.row_ids_with_positions;
783
0
        std::sort(row_ids_with_positions.begin(), row_ids_with_positions.end(),
784
0
                  [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; });
785
786
        // Column iterators read rowids monotonically. Deduplicate consecutive identical row_ids
787
        // (different file_ids may map to the same row), then scatter rows back to their original
788
        // request positions.
789
0
        std::vector<uint32_t> row_ids;
790
0
        row_ids.reserve(row_ids_with_positions.size());
791
792
        // Also builds the scatter map: row_id_block_idx[original_request_idx] ->
793
        // (batch_idx, deduplicated_position_in_batch).
794
0
        for (const auto& [row_id, result_idx] : row_ids_with_positions) {
795
0
            if (row_ids.empty() || row_ids.back() != row_id) {
796
0
                row_ids.emplace_back(row_id);
797
0
            }
798
0
            row_id_block_idx[result_idx] = std::make_pair(batch_idx, row_ids.size() - 1);
799
0
        }
800
801
0
        scan_blocks[batch_idx] = Block(slots, row_ids.size());
802
0
        RETURN_IF_ERROR(read_doris_format_row(
803
0
                id_file_map, scan_batch.file_mapping, row_ids, slots, full_read_schema,
804
0
                row_store_read_struct, stats, acquire_tablet_ms, acquire_rowsets_ms,
805
0
                acquire_segments_ms, lookup_row_data_ms, seg_map, iterator_map,
806
0
                file_cache_miss_policy, scan_blocks[batch_idx]));
807
0
    }
808
809
0
    scatter_scan_blocks_to_result_block(row_id_block_idx, scan_blocks, result_block);
810
811
0
    return Status::OK();
812
0
}
813
814
const std::string RowIdStorageReader::ScannersRunningTimeProfile = "ScannersRunningTime";
815
const std::string RowIdStorageReader::InitReaderAvgTimeProfile = "InitReaderAvgTime";
816
const std::string RowIdStorageReader::GetBlockAvgTimeProfile = "GetBlockAvgTime";
817
const std::string RowIdStorageReader::FileReadLinesProfile = "FileReadLines";
818
const std::string RowIdStorageReader::LanceDatasetOpenTimeProfile = "LanceDatasetOpenTime";
819
const std::string RowIdStorageReader::LanceRowIdTakeReadTimeProfile = "LanceRowIdTakeReadTime";
820
const std::string RowIdStorageReader::LanceArrowToDorisBlockTimeProfile =
821
        "LanceArrowToDorisBlockTime";
822
const std::string RowIdStorageReader::LanceRowIdFetchTotalTimeProfile = "LanceRowIdFetchTotalTime";
823
const std::map<std::string, TUnit::type> RowIdStorageReader::LanceFetchCountersProfile = {
824
        {"LanceRowIdFetchRows", TUnit::UNIT},
825
        {"LanceRowIdFetchCalls", TUnit::UNIT},
826
        {"LanceDataCacheBytesReadFromCache", TUnit::BYTES},
827
        {"LanceDataCacheBytesReadFromRemote", TUnit::BYTES},
828
};
829
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOCount =
830
        "TopNLazyMaterializationSecondPhaseLocalIOCount";
831
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOBytes =
832
        "TopNLazyMaterializationSecondPhaseLocalIOBytes";
833
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOCount =
834
        "TopNLazyMaterializationSecondPhaseRemoteIOCount";
835
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOBytes =
836
        "TopNLazyMaterializationSecondPhaseRemoteIOBytes";
837
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSkipCacheIOCount =
838
        "TopNLazyMaterializationSecondPhaseSkipCacheIOCount";
839
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheBytes =
840
        "TopNLazyMaterializationSecondPhaseWriteCacheBytes";
841
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseLocalIOTime =
842
        "TopNLazyMaterializationSecondPhaseLocalIOTime";
843
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRemoteIOTime =
844
        "TopNLazyMaterializationSecondPhaseRemoteIOTime";
845
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseWriteCacheIOTime =
846
        "TopNLazyMaterializationSecondPhaseWriteCacheIOTime";
847
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseRowsRead =
848
        "TopNLazyMaterializationSecondPhaseRowsRead";
849
const std::string RowIdStorageReader::TopNLazyMaterializationSecondPhaseSegmentsRead =
850
        "TopNLazyMaterializationSecondPhaseSegmentsRead";
851
852
bool RowIdStorageReader::should_use_file_scanner_v2(const TQueryOptions& query_options,
853
                                                    const TFileScanRangeParams& scan_params,
854
40
                                                    const TFileRangeDesc& range) {
855
40
    const auto format_type =
856
40
            range.__isset.format_type ? range.format_type : scan_params.format_type;
857
    // Phase two inherits the query options, including the Thrift presence bit. Reuse phase one's
858
    // policy so disabling V2 (or an older payload omitting the option) also keeps row fetches on V1.
859
40
    return FileScanLocalState::should_use_file_scanner_v2(query_options, false, scan_params) &&
860
40
           (format_type == TFileFormatType::FORMAT_PARQUET ||
861
15
            format_type == TFileFormatType::FORMAT_ORC) &&
862
40
           FileScannerV2::is_supported(scan_params, range);
863
40
}
864
865
1
TFileRangeDesc RowIdStorageReader::build_external_fetch_range(const TFileRangeDesc& source_range) {
866
    // Rows were selected after delete filtering. Preserve the original path and row lineage
867
    // needed by virtual columns, and do not mutate the FileMapping shared by other fetches.
868
1
    auto range = source_range;
869
1
    range.table_format_params.iceberg_params.__set_delete_files({});
870
1
    range.table_format_params.transactional_hive_params = TTransactionalHiveDesc {};
871
1
    return range;
872
1
}
873
874
TFileScanRangeParams RowIdStorageReader::build_external_scan_params(
875
        const TFileScanRangeParams& source_params, const TFileRangeDesc& range,
876
        const std::vector<SlotDescriptor>& scan_slots,
877
10
        const std::vector<uint32_t>& scan_column_idxs) {
878
10
    DORIS_CHECK(scan_slots.size() == scan_column_idxs.size());
879
10
    auto params = source_params;
880
10
    params.required_slots.clear();
881
10
    params.column_idxs.clear();
882
10
    params.slot_name_to_schema_pos.clear();
883
10
    const std::set partition_names(range.columns_from_path_keys.begin(),
884
10
                                   range.columns_from_path_keys.end());
885
36
    for (size_t slot_idx = 0; slot_idx < scan_slots.size(); ++slot_idx) {
886
26
        const auto& slot = scan_slots[slot_idx];
887
26
        const auto column_idx = scan_column_idxs[slot_idx];
888
26
        TFileScanSlotInfo slot_info;
889
26
        slot_info.__set_slot_id(slot.id());
890
        // Hive V2 checks the Thrift presence bit before trusting is_file_slot. Without it,
891
        // partition columns consume physical file indexes and invalidate the rebuilt projection.
892
26
        bool is_file_slot = !partition_names.contains(slot.col_name());
893
26
        if (source_params.__isset.column_name_to_category) {
894
            // Lazy metadata slots may be absent from phase one's required_slots and have new
895
            // slot IDs here. The pinned schema's name map preserves their original categories.
896
10
            const auto it = source_params.column_name_to_category.find(slot.col_name());
897
10
            const auto category = it != source_params.column_name_to_category.end()
898
10
                                          ? it->second
899
10
                                          : TColumnCategory::REGULAR;
900
10
            slot_info.__set_category(category);
901
10
            is_file_slot =
902
10
                    category == TColumnCategory::REGULAR || category == TColumnCategory::GENERATED;
903
10
        }
904
26
        slot_info.__set_is_file_slot(is_file_slot);
905
26
        if (is_file_slot) {
906
17
            params.column_idxs.emplace_back(column_idx);
907
17
        }
908
26
        params.default_value_of_src_slot.emplace(slot.id(), TExpr {});
909
26
        params.required_slots.emplace_back(slot_info);
910
26
        params.slot_name_to_schema_pos.emplace(slot.col_name(), column_idx);
911
26
    }
912
10
    return params;
913
10
}
914
915
Status RowIdStorageReader::read_lance_rows_by_row_ids(
916
        const TFileRangeDesc& scan_range_desc, const std::vector<uint64_t>& row_ids,
917
        const std::vector<SlotDescriptor>& slots, RuntimeState* runtime_state,
918
        RuntimeProfile* runtime_profile, const TFileScanRangeParams& scan_params, Block* block,
919
0
        RowIdStorageReader::ExternalFetchStatistics* fetch_statistics) {
920
    // Unlike Parquet/ORC, a Lance row ID is a native uint64 ID in a fixed dataset snapshot,
921
    // rather than a row ordinal interpreted by a reader for one physical file range. Phase-two
922
    // fetch therefore opens that dataset snapshot and uses dataset-level take_rows directly. It
923
    // does not create a FileScanner or rescan the fragment split that produced the row ID.
924
0
    std::vector<format::ColumnDefinition> projected_columns;
925
0
    projected_columns.reserve(slots.size());
926
0
    for (const auto& slot : slots) {
927
0
        format::ColumnDefinition column;
928
0
        column.identifier = Field::create_field<TYPE_STRING>(slot.col_name());
929
0
        column.name = slot.col_name();
930
0
        column.type = slot.get_data_type_ptr();
931
0
        projected_columns.emplace_back(std::move(column));
932
0
    }
933
934
0
    format::lance::LanceTableReader reader;
935
0
    auto lance_scan_params = scan_params;
936
0
    RETURN_IF_ERROR(scope_timer_run(
937
0
            [&]() {
938
0
                return reader.init({
939
0
                        .projected_columns = projected_columns,
940
0
                        .conjuncts = {},
941
0
                        .format = format::FileFormat::LANCE,
942
0
                        .scan_params = &lance_scan_params,
943
0
                        .io_ctx = nullptr,
944
0
                        .runtime_state = runtime_state,
945
0
                        .scanner_profile = runtime_profile,
946
0
                });
947
0
            },
948
0
            &fetch_statistics->init_reader_ms));
949
0
    RETURN_IF_ERROR(scope_timer_run(
950
0
            [&]() { return reader.read_by_row_ids(scan_range_desc, row_ids, block); },
951
0
            &fetch_statistics->get_block_ms));
952
0
    RETURN_IF_ERROR(reader.close());
953
954
0
    const auto collect_lance_fetch_time = [&](const std::string& timer_name) {
955
0
        if (const auto* counter = runtime_profile->get_counter(timer_name); counter != nullptr) {
956
0
            fetch_statistics->lance_fetch_times_ns.emplace(timer_name, counter->value());
957
0
        }
958
0
    };
959
0
    collect_lance_fetch_time(LanceDatasetOpenTimeProfile);
960
0
    collect_lance_fetch_time(LanceRowIdTakeReadTimeProfile);
961
0
    collect_lance_fetch_time(LanceArrowToDorisBlockTimeProfile);
962
0
    collect_lance_fetch_time(LanceRowIdFetchTotalTimeProfile);
963
    // close() publishes dataset-handle cache statistics; collect after it and preserve the
964
    // units across the RPC instead of formatting byte/count values as nanoseconds.
965
0
    for (const auto& [name, unit] : LanceFetchCountersProfile) {
966
0
        if (const auto* counter = runtime_profile->get_counter(name); counter != nullptr) {
967
0
            fetch_statistics->lance_fetch_counters.emplace(name, counter->value());
968
0
        }
969
0
    }
970
0
    return Status::OK();
971
0
}
972
973
Status RowIdStorageReader::read_external_row_from_file_mapping(
974
        size_t idx, const std::multimap<uint64_t, size_t>& row_ids,
975
        const std::shared_ptr<FileMapping>& file_mapping,
976
        const std::vector<SlotDescriptor>& scan_slots, const TUniqueId& query_id,
977
        const std::shared_ptr<RuntimeState>& runtime_state, std::vector<Block>& scan_blocks,
978
        std::vector<std::pair<size_t, size_t>>& row_id_block_idx,
979
        std::vector<RowIdStorageReader::ExternalFetchStatistics>& fetch_statistics,
980
        const TFileScanRangeParams& rpc_scan_params,
981
        const std::unordered_map<std::string, int>& colname_to_slot_id,
982
0
        std::counting_semaphore<>& semaphore, TupleDescriptor& tuple_desc) {
983
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
984
0
    signal::set_signal_task_id(query_id);
985
986
    // Release the concurrency permit on every exit path (including error returns
987
    // and exceptions). Completion accounting and status publishing are owned by
988
    // the caller, so the status is always published before the waiter is woken.
989
0
    Defer defer([&] { semaphore.release(); });
990
991
0
    std::vector<uint64_t> read_ids;
992
    // Generate an ordered, deduplicated list with the help of the multimap ordering.
993
0
    for (const auto& [row_id, result_block_idx] : row_ids) {
994
0
        if (read_ids.empty() || read_ids.back() != row_id) {
995
0
            read_ids.emplace_back(row_id);
996
0
        }
997
0
        row_id_block_idx[result_block_idx] = std::make_pair(idx, read_ids.size() - 1);
998
0
    }
999
1000
0
    scan_blocks[idx] = Block(scan_slots, read_ids.size());
1001
1002
0
    auto& external_info = file_mapping->get_external_file_info();
1003
0
    auto scan_range_desc = build_external_fetch_range(external_info.scan_range_desc);
1004
1005
0
    std::unique_ptr<RuntimeProfile> sub_runtime_profile =
1006
0
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
1007
0
    const auto format_type = scan_range_desc.__isset.format_type ? scan_range_desc.format_type
1008
0
                                                                 : rpc_scan_params.format_type;
1009
0
    if (format_type == TFileFormatType::FORMAT_LANCE) {
1010
0
        RETURN_IF_ERROR(read_lance_rows_by_row_ids(scan_range_desc, read_ids, scan_slots,
1011
0
                                                   runtime_state.get(), sub_runtime_profile.get(),
1012
0
                                                   rpc_scan_params, &scan_blocks[idx],
1013
0
                                                   &fetch_statistics[idx]));
1014
0
    } else {
1015
        // Parquet/ORC IDs remain signed physical file positions; Lance keeps native uint64 IDs.
1016
0
        std::list<int64_t> legacy_read_ids;
1017
0
        for (const auto row_id : read_ids) {
1018
0
            if (row_id > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
1019
0
                return Status::InvalidArgument("legacy external row id exceeds int64 range: {}",
1020
0
                                               row_id);
1021
0
            }
1022
0
            legacy_read_ids.emplace_back(static_cast<int64_t>(row_id));
1023
0
        }
1024
0
        if (should_use_file_scanner_v2(runtime_state->query_options(), rpc_scan_params,
1025
0
                                       scan_range_desc)) {
1026
0
            auto file_scanner = FileScannerV2::create_unique(
1027
0
                    runtime_state.get(), sub_runtime_profile.get(), &rpc_scan_params,
1028
0
                    &colname_to_slot_id, &tuple_desc);
1029
0
            RETURN_IF_ERROR(file_scanner->read_by_rows(
1030
0
                    scan_range_desc, legacy_read_ids, &scan_blocks[idx],
1031
0
                    &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
1032
0
        } else {
1033
            // Keep phase two on V1 whenever the rollout policy or table format requires it.
1034
0
            std::unique_ptr<FileScanner> file_scanner =
1035
0
                    FileScanner::create_unique(runtime_state.get(), sub_runtime_profile.get(),
1036
0
                                               &rpc_scan_params, &colname_to_slot_id, &tuple_desc);
1037
1038
0
            RETURN_IF_ERROR(file_scanner->prepare_for_read_lines(scan_range_desc));
1039
0
            RETURN_IF_ERROR(file_scanner->read_lines_from_range(
1040
0
                    scan_range_desc, legacy_read_ids, &scan_blocks[idx], external_info,
1041
0
                    &fetch_statistics[idx].init_reader_ms, &fetch_statistics[idx].get_block_ms));
1042
0
        }
1043
0
    }
1044
1045
0
    if (scan_blocks[idx].rows() != read_ids.size()) {
1046
0
        return Status::InternalError(
1047
0
                "Row id fetch scan row count mismatch, "
1048
0
                "query_id={}, path={}, expected_rows={}, actual_rows={}",
1049
0
                print_id(query_id), scan_range_desc.path, read_ids.size(), scan_blocks[idx].rows());
1050
0
    }
1051
0
    for (size_t column_id = 0; column_id < scan_blocks[idx].columns(); ++column_id) {
1052
0
        const auto& column = scan_blocks[idx].get_by_position(column_id);
1053
0
        if (column.column->size() != read_ids.size()) {
1054
0
            return Status::InternalError(
1055
0
                    "Row id fetch scan column row count mismatch, "
1056
0
                    "query_id={}, path={}, column={}, expected_rows={}, actual_rows={}",
1057
0
                    print_id(query_id), scan_range_desc.path, column.name, read_ids.size(),
1058
0
                    column.column->size());
1059
0
        }
1060
0
    }
1061
1062
0
    auto file_read_bytes_counter =
1063
0
            sub_runtime_profile->get_counter(FileScannerV2::FileReadBytesProfile);
1064
1065
0
    if (file_read_bytes_counter != nullptr) {
1066
0
        fetch_statistics[idx].file_read_bytes = PrettyPrinter::print(
1067
0
                file_read_bytes_counter->value(), file_read_bytes_counter->type());
1068
0
    }
1069
1070
0
    auto file_read_times_counter =
1071
0
            sub_runtime_profile->get_counter(FileScannerV2::FileReadTimeProfile);
1072
0
    if (file_read_times_counter != nullptr) {
1073
0
        fetch_statistics[idx].file_read_times = PrettyPrinter::print(
1074
0
                file_read_times_counter->value(), file_read_times_counter->type());
1075
0
    }
1076
1077
0
    return Status::OK();
1078
0
}
1079
1080
24
std::string RowIdStorageReader::source_column_key(const SlotDescriptor& slot, uint32_t column_idx) {
1081
24
    fmt::memory_buffer key;
1082
    // Length-prefix each component so distinct sequences cannot alias, e.g.
1083
    // paths ["a", "b"] -> "1:a1:b" while ["a:b"] -> "3:a:b".
1084
164
    auto append = [&key](std::string_view component) {
1085
164
        fmt::format_to(key, "{}:", component.size());
1086
164
        key.append(component.data(), component.data() + component.size());
1087
164
    };
1088
24
    append(slot.col_name());
1089
24
    append(std::to_string(column_idx));
1090
24
    append(std::to_string(slot.col_unique_id()));
1091
24
    append(std::to_string(slot.column_paths().size()));
1092
24
    for (const auto& path : slot.column_paths()) {
1093
12
        append(path);
1094
12
    }
1095
24
    append(std::to_string(slot.all_access_paths().size()));
1096
    // Encode each optional sub-path's presence bit separately from its element
1097
    // count so an absent path ("0") never aliases a present-but-empty path
1098
    // ("1" + size "0").
1099
24
    auto append_optional_path = [&append](bool is_set, const std::vector<std::string>& items) {
1100
14
        append(is_set ? "1" : "0");
1101
14
        if (is_set) {
1102
6
            append(std::to_string(items.size()));
1103
6
            for (const auto& item : items) {
1104
5
                append(item);
1105
5
            }
1106
6
        }
1107
14
    };
1108
24
    for (const auto& path : slot.all_access_paths()) {
1109
7
        append(fmt::format("{}", path.type));
1110
7
        append_optional_path(path.__isset.data_access_path, path.data_access_path.path);
1111
7
        append_optional_path(path.__isset.meta_access_path, path.meta_access_path.path);
1112
7
    }
1113
24
    return fmt::to_string(key);
1114
24
}
1115
1116
Status RowIdStorageReader::submit_external_scan_tasks(
1117
        ScannerScheduler* scheduler, std::counting_semaphore<>& semaphore, size_t task_count,
1118
        const std::function<std::string(size_t)>& make_task_id,
1119
3
        const std::function<Status(size_t)>& run_task) {
1120
    // `completed_count` is a plain counter guarded by `mtx`; the same mutex guards
1121
    // the wait predicate below, so a worker can never notify between the waiter's
1122
    // predicate check and its wait.
1123
3
    AtomicStatus scan_status;
1124
3
    std::condition_variable cv;
1125
3
    std::mutex mtx;
1126
3
    size_t completed_count = 0;
1127
1128
    // Only tasks the scheduler actually accepted are waited for. If a submission
1129
    // fails we stop submitting, but still wait for the already-accepted tasks so
1130
    // their workers cannot outlive the locals they capture by reference.
1131
3
    size_t submitted_count = 0;
1132
12
    for (size_t idx = 0; idx < task_count; ++idx) {
1133
9
        semaphore.acquire();
1134
9
        auto run_one_task = [&, idx]() -> bool {
1135
9
            Status task_status = Status::OK();
1136
            // Publish the status before the completion signal wakes the waiter, on every
1137
            // path. A scanner that throws would otherwise leave scan_status OK while this
1138
            // Defer still counts the task as finished, and the caller would report success
1139
            // over a half-filled result block.
1140
9
            Defer complete([&] {
1141
9
                scan_status.update(task_status);
1142
9
                std::lock_guard<std::mutex> lock(mtx);
1143
9
                ++completed_count;
1144
9
                cv.notify_one();
1145
9
            });
1146
9
            ASSIGN_STATUS_IF_CATCH_EXCEPTION(task_status = run_task(idx), task_status);
1147
9
            return true;
1148
9
        };
1149
9
        Status submit_st = scheduler->submit_scan_task(
1150
9
                SimplifiedScanTask(run_one_task, nullptr, nullptr), make_task_id(idx));
1151
9
        if (!submit_st.ok()) {
1152
0
            scan_status.update(submit_st);
1153
0
            semaphore.release();
1154
0
            break;
1155
0
        }
1156
9
        ++submitted_count;
1157
9
    }
1158
1159
3
    {
1160
3
        std::unique_lock<std::mutex> lock(mtx);
1161
3
        cv.wait(lock, [&] { return completed_count == submitted_count; });
1162
3
    }
1163
3
    return scan_status.ok() ? Status::OK() : scan_status.status();
1164
3
}
1165
1166
Status RowIdStorageReader::read_batch_external_row(
1167
        const uint64_t workload_group_id, const PRequestBlockDesc& request_block_desc,
1168
        std::shared_ptr<IdFileMap> id_file_map, std::vector<SlotDescriptor>& slots,
1169
        std::shared_ptr<FileMapping> first_file_mapping, const TUniqueId& query_id,
1170
        Block& result_block, PRuntimeProfileTree* pprofile, int64_t* init_reader_avg_ms,
1171
0
        int64_t* get_block_avg_ms, size_t* scan_range_cnt) {
1172
0
    TFileScanRangeParams rpc_scan_params;
1173
0
    TupleDescriptor tuple_desc(request_block_desc.desc(), false);
1174
0
    std::unordered_map<std::string, int> colname_to_slot_id;
1175
0
    std::shared_ptr<RuntimeState> runtime_state = nullptr;
1176
0
    std::vector<SlotDescriptor> scan_slots;
1177
0
    std::vector<size_t> result_column_to_scan_column;
1178
0
    std::vector<uint32_t> scan_column_idxs;
1179
1180
0
    int max_file_scanners = 0;
1181
0
    {
1182
0
        if (result_block.is_empty_column()) [[likely]] {
1183
0
            result_block = Block(slots, request_block_desc.row_id_size());
1184
0
        }
1185
0
        if (request_block_desc.column_idxs_size() != slots.size()) {
1186
0
            return Status::InternalError(
1187
0
                    "Row id fetch request has mismatched slots and column indexes, "
1188
0
                    "query_id={}, slots={}, column_idxs={}",
1189
0
                    print_id(query_id), slots.size(), request_block_desc.column_idxs_size());
1190
0
        }
1191
1192
0
        auto& external_info = first_file_mapping->get_external_file_info();
1193
0
        int plan_node_id = external_info.plan_node_id;
1194
0
        const auto& first_scan_range_desc = external_info.scan_range_desc;
1195
1196
0
        const auto& external_scan_params = id_file_map->get_external_scan_params();
1197
0
        const auto scan_params = external_scan_params.find(plan_node_id);
1198
0
        if (scan_params == external_scan_params.end()) {
1199
0
            return Status::InternalError("External scan params not found for plan node id {}",
1200
0
                                         plan_node_id);
1201
0
        }
1202
0
        rpc_scan_params = scan_params->second;
1203
0
        if (request_block_desc.row_location_version() ==
1204
0
            static_cast<uint32_t>(ROW_VERSION::LANCE_DATASET_ROW_ID)) {
1205
0
            const auto format_type = first_scan_range_desc.__isset.format_type
1206
0
                                             ? first_scan_range_desc.format_type
1207
0
                                             : rpc_scan_params.format_type;
1208
0
            if (format_type != TFileFormatType::FORMAT_LANCE) {
1209
0
                return Status::InvalidArgument(
1210
0
                        "Lance dataset row IDs cannot be fetched with file format {}",
1211
0
                        static_cast<int>(format_type));
1212
0
            }
1213
0
        }
1214
1215
0
        std::unordered_map<std::string, size_t> source_column_to_scan_idx;
1216
1217
0
        result_column_to_scan_column.reserve(slots.size());
1218
0
        scan_slots.reserve(slots.size());
1219
0
        scan_column_idxs.reserve(slots.size());
1220
0
        for (auto slot_idx = 0; slot_idx < slots.size(); ++slot_idx) {
1221
0
            const auto& slot = slots[slot_idx];
1222
0
            const auto column_idx = request_block_desc.column_idxs(slot_idx);
1223
0
            const auto key = source_column_key(slot, column_idx);
1224
0
            auto [it, inserted] =
1225
0
                    source_column_to_scan_idx.emplace(key, source_column_to_scan_idx.size());
1226
0
            result_column_to_scan_column.emplace_back(it->second);
1227
0
            if (inserted) {
1228
0
                scan_slots.emplace_back(slot);
1229
0
                scan_column_idxs.emplace_back(column_idx);
1230
0
            }
1231
0
        }
1232
1233
0
        for (auto& slot : scan_slots) {
1234
0
            tuple_desc.add_slot(&slot);
1235
0
            colname_to_slot_id[slot.col_name()] = slot.id();
1236
0
        }
1237
0
        rpc_scan_params = build_external_scan_params(rpc_scan_params, first_scan_range_desc,
1238
0
                                                     scan_slots, scan_column_idxs);
1239
1240
0
        const auto& query_options = id_file_map->get_query_options();
1241
0
        const auto& query_globals = id_file_map->get_query_globals();
1242
        /*
1243
         * The scan stage needs the information in query_options to generate different behaviors according to the specific variables:
1244
         *  query_options.hive_parquet_use_column_names, query_options.truncate_char_or_varchar_columns,query_globals.time_zone ...
1245
         *
1246
         * To ensure the same behavior as the scan stage, I get query_options query_globals from id_file_map, then create runtime_state
1247
         * 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.
1248
         */
1249
0
        runtime_state = RuntimeState::create_shared(
1250
0
                query_id, -1, query_options, query_globals, ExecEnv::GetInstance(),
1251
0
                ExecEnv::GetInstance()->rowid_storage_reader_tracker());
1252
1253
0
        max_file_scanners = id_file_map->get_max_file_scanners();
1254
0
    }
1255
1256
    // Hash(TFileRangeDesc) => { all the rows that need to be read and their positions in the result block. } +  file mapping
1257
    // The multimap retains duplicate row IDs because the same source row can appear more than once
1258
    // in the materialized result.
1259
0
    std::map<std::string, std::pair<std::multimap<uint64_t, size_t>, std::shared_ptr<FileMapping>>>
1260
0
            scan_rows;
1261
1262
    // Block corresponding to the order of `scan_rows` map.
1263
0
    std::vector<Block> scan_blocks;
1264
1265
    // row_id (Indexing of vectors) => < In which block, which line in the block >
1266
0
    std::vector<std::pair<size_t, size_t>> row_id_block_idx;
1267
1268
    // Count the time/bytes it takes to read each TFileRangeDesc. (for profile)
1269
0
    std::vector<ExternalFetchStatistics> fetch_statistics;
1270
1271
0
    auto hash_file_range = [&rpc_scan_params](const ExternalFileMappingInfo& external_info) {
1272
0
        const auto& file_range_desc = external_info.scan_range_desc;
1273
0
        const auto format_type = file_range_desc.__isset.format_type ? file_range_desc.format_type
1274
0
                                                                     : rpc_scan_params.format_type;
1275
0
        if (format_type == TFileFormatType::FORMAT_LANCE) {
1276
            // Parquet and ORC row IDs are offsets within a physical file range, so their fetch
1277
            // path must keep each path/start_offset pair separate. Lance row IDs instead belong
1278
            // to a fixed dataset snapshot. Although phase one registers one file mapping per
1279
            // fragment split, phase two uses dataset-level take_rows and can fetch row IDs from
1280
            // all of those fragments together. Group the mappings by scan node, snapshot, and
1281
            // dataset URI; the plan node keeps independent scans of the same snapshot isolated.
1282
0
            const auto& lance_params = file_range_desc.table_format_params.lance_params;
1283
0
            return fmt::format("lance:{}:{}:{}", external_info.plan_node_id, lance_params.version,
1284
0
                               lance_params.dataset_uri);
1285
0
        }
1286
0
        std::string value;
1287
0
        value.resize(file_range_desc.path.size() + sizeof(file_range_desc.start_offset));
1288
0
        auto* ptr = value.data();
1289
1290
0
        memcpy(ptr, &file_range_desc.start_offset, sizeof(file_range_desc.start_offset));
1291
0
        ptr += sizeof(file_range_desc.start_offset);
1292
0
        memcpy(ptr, file_range_desc.path.data(), file_range_desc.path.size());
1293
0
        return value;
1294
0
    };
1295
1296
0
    for (int j = 0; j < request_block_desc.row_id_size(); ++j) {
1297
0
        auto file_id = request_block_desc.file_id(j);
1298
0
        auto file_mapping = id_file_map->get_file_mapping(file_id);
1299
0
        if (!file_mapping) {
1300
0
            return Status::InternalError(
1301
0
                    "Backend:{} file_mapping not found, query_id: {}, file_id: {}",
1302
0
                    BackendOptions::get_localhost(), print_id(query_id), file_id);
1303
0
        }
1304
1305
0
        const auto& external_info = file_mapping->get_external_file_info();
1306
0
        const auto& scan_range_hash = hash_file_range(external_info);
1307
0
        if (scan_rows.contains(scan_range_hash)) {
1308
0
            scan_rows.at(scan_range_hash).first.emplace(request_block_desc.row_id(j), j);
1309
0
        } else {
1310
0
            std::multimap<uint64_t, size_t> rows {{request_block_desc.row_id(j), j}};
1311
0
            scan_rows.emplace(scan_range_hash, std::make_pair(std::move(rows), file_mapping));
1312
0
        }
1313
0
    }
1314
1315
0
    scan_blocks.resize(scan_rows.size());
1316
0
    row_id_block_idx.resize(request_block_desc.row_id_size());
1317
0
    fetch_statistics.resize(scan_rows.size());
1318
1319
    // Get the workload group for subsequent scan task submission.
1320
0
    std::vector<uint64_t> workload_group_ids;
1321
0
    workload_group_ids.emplace_back(workload_group_id);
1322
0
    auto wg = ExecEnv::GetInstance()->workload_group_mgr()->get_group(workload_group_ids);
1323
0
    doris::TaskScheduler* exec_sched = nullptr;
1324
0
    ScannerScheduler* scan_sched = nullptr;
1325
0
    ScannerScheduler* remote_scan_sched = nullptr;
1326
0
    wg->get_query_scheduler(&exec_sched, &scan_sched, &remote_scan_sched);
1327
0
    DCHECK(remote_scan_sched);
1328
1329
0
    int64_t scan_running_time = 0;
1330
0
    RETURN_IF_ERROR(scope_timer_run(
1331
0
            [&]() -> Status {
1332
                //semaphore: Limit the number of scan tasks submitted at one time
1333
0
                std::counting_semaphore semaphore {max_file_scanners};
1334
1335
0
                std::vector<
1336
0
                        std::pair<std::multimap<uint64_t, size_t>, std::shared_ptr<FileMapping>>>
1337
0
                        scan_info_list;
1338
0
                scan_info_list.reserve(scan_rows.size());
1339
0
                for (const auto& [_, scan_info] : scan_rows) {
1340
0
                    scan_info_list.emplace_back(scan_info);
1341
0
                }
1342
1343
0
                return submit_external_scan_tasks(
1344
0
                        remote_scan_sched, semaphore, scan_rows.size(),
1345
0
                        [&](size_t idx) {
1346
0
                            return fmt::format("{}-read_batch_external_row-{}", print_id(query_id),
1347
0
                                               idx);
1348
0
                        },
1349
0
                        [&](size_t idx) -> Status {
1350
0
                            const auto& [row_ids, file_mapping] = scan_info_list[idx];
1351
0
                            return read_external_row_from_file_mapping(
1352
0
                                    idx, row_ids, file_mapping, scan_slots, query_id, runtime_state,
1353
0
                                    scan_blocks, row_id_block_idx, fetch_statistics,
1354
0
                                    rpc_scan_params, colname_to_slot_id, semaphore, tuple_desc);
1355
0
                        });
1356
0
            },
1357
0
            &scan_running_time));
1358
1359
    // Insert the read data into result_block. Use insert_indices_from() instead of
1360
    // scatter_scan_blocks_to_result_block()/insert_from_multi_column(), because
1361
    // scan_blocks may have fewer columns than result_block when duplicate physical columns
1362
    // are deduplicated, and insert_from_multi_column() cannot handle ColumnString
1363
    // cross-type (32/64) copies safely.
1364
0
    const size_t result_column_count = result_block.columns();
1365
0
    for (size_t column_id = 0; column_id < result_column_count; column_id++) {
1366
0
        auto dst_col_guard = result_block.mutate_column_scoped(column_id);
1367
0
        MutableColumnPtr& dst_col = dst_col_guard.mutable_column();
1368
1369
0
        bool dst_is_nullable = dst_col->is_nullable();
1370
0
        std::vector<ColumnPtr> nullable_src_columns(scan_blocks.size());
1371
0
        auto scan_column_id = result_column_to_scan_column[column_id];
1372
0
        for (const auto& [pos_block, block_idx] : row_id_block_idx) {
1373
0
            DCHECK_GT(scan_blocks.size(), pos_block);
1374
0
            DCHECK_GT(scan_blocks[pos_block].columns(), scan_column_id);
1375
0
            const auto& src_column_ptr =
1376
0
                    scan_blocks[pos_block].get_by_position(scan_column_id).column;
1377
0
            const auto* src_col = src_column_ptr.get();
1378
0
            if (dst_is_nullable && !src_col->is_nullable()) {
1379
0
                if (!nullable_src_columns[pos_block]) {
1380
0
                    nullable_src_columns[pos_block] = make_nullable(src_column_ptr);
1381
0
                }
1382
0
                src_col = nullable_src_columns[pos_block].get();
1383
0
            }
1384
0
            if (block_idx >= src_col->size()) {
1385
0
                return Status::InternalError(
1386
0
                        "Row id fetch source index out of range, query_id={}, column={}, "
1387
0
                        "source_block={}, source_rows={}, row_index={}",
1388
0
                        print_id(query_id), result_block.get_by_position(column_id).name, pos_block,
1389
0
                        src_col->size(), block_idx);
1390
0
            }
1391
0
            uint32_t scan_position = cast_set<uint32_t>(block_idx);
1392
0
            dst_col->insert_indices_from(*src_col, &scan_position, &scan_position + 1);
1393
0
        }
1394
0
    }
1395
1396
    // Statistical runtime profile information.
1397
0
    std::unique_ptr<RuntimeProfile> runtime_profile =
1398
0
            std::make_unique<RuntimeProfile>("ExternalRowIDFetcher");
1399
0
    {
1400
0
        runtime_profile->add_info_string(ScannersRunningTimeProfile,
1401
0
                                         std::to_string(scan_running_time) + "ms");
1402
0
        fmt::memory_buffer file_read_lines_buffer;
1403
0
        format_to(file_read_lines_buffer, "[");
1404
0
        fmt::memory_buffer file_read_bytes_buffer;
1405
0
        format_to(file_read_bytes_buffer, "[");
1406
0
        fmt::memory_buffer file_read_times_buffer;
1407
0
        format_to(file_read_times_buffer, "[");
1408
1409
0
        std::map<std::string, int64_t> lance_fetch_times_ns;
1410
0
        std::map<std::string, int64_t> lance_fetch_counters;
1411
0
        size_t idx = 0;
1412
0
        for (const auto& [_, scan_info] : scan_rows) {
1413
0
            format_to(file_read_lines_buffer, "{}, ", scan_info.first.size());
1414
0
            *init_reader_avg_ms += fetch_statistics[idx].init_reader_ms;
1415
0
            *get_block_avg_ms += fetch_statistics[idx].get_block_ms;
1416
0
            format_to(file_read_bytes_buffer, "{}, ", fetch_statistics[idx].file_read_bytes);
1417
0
            format_to(file_read_times_buffer, "{}, ", fetch_statistics[idx].file_read_times);
1418
0
            for (const auto& [time_name, time_value] : fetch_statistics[idx].lance_fetch_times_ns) {
1419
0
                lance_fetch_times_ns[time_name] += time_value;
1420
0
            }
1421
0
            for (const auto& [name, value] : fetch_statistics[idx].lance_fetch_counters) {
1422
0
                lance_fetch_counters[name] += value;
1423
0
            }
1424
0
            idx++;
1425
0
        }
1426
1427
0
        format_to(file_read_lines_buffer, "]");
1428
0
        format_to(file_read_bytes_buffer, "]");
1429
0
        format_to(file_read_times_buffer, "]");
1430
1431
0
        *init_reader_avg_ms /= fetch_statistics.size();
1432
0
        *get_block_avg_ms /= fetch_statistics.size();
1433
0
        runtime_profile->add_info_string(InitReaderAvgTimeProfile,
1434
0
                                         std::to_string(*init_reader_avg_ms) + "ms");
1435
0
        runtime_profile->add_info_string(GetBlockAvgTimeProfile,
1436
0
                                         std::to_string(*get_block_avg_ms) + "ms");
1437
0
        runtime_profile->add_info_string(FileReadLinesProfile,
1438
0
                                         fmt::to_string(file_read_lines_buffer));
1439
0
        runtime_profile->add_info_string(FileScannerV2::FileReadBytesProfile,
1440
0
                                         fmt::to_string(file_read_bytes_buffer));
1441
0
        runtime_profile->add_info_string(FileScannerV2::FileReadTimeProfile,
1442
0
                                         fmt::to_string(file_read_times_buffer));
1443
0
        for (const auto& [name, value] : lance_fetch_counters) {
1444
0
            runtime_profile->add_info_string(
1445
0
                    name, PrettyPrinter::print(value, LanceFetchCountersProfile.at(name)));
1446
0
        }
1447
0
        for (const auto& [time_name, time_value] : lance_fetch_times_ns) {
1448
0
            runtime_profile->add_info_string(time_name,
1449
0
                                             PrettyPrinter::print(time_value, TUnit::TIME_NS));
1450
0
        }
1451
0
    }
1452
1453
0
    runtime_profile->to_proto(pprofile, 2);
1454
1455
0
    *scan_range_cnt = scan_rows.size();
1456
1457
0
    return Status::OK();
1458
0
}
1459
1460
Status RowIdStorageReader::read_doris_format_row(
1461
        const std::shared_ptr<IdFileMap>& id_file_map,
1462
        const std::shared_ptr<FileMapping>& file_mapping, const std::vector<uint32_t>& row_ids,
1463
        std::vector<SlotDescriptor>& slots, const TabletSchema& full_read_schema,
1464
        RowStoreReadStruct& row_store_read_struct, OlapReaderStatistics& stats,
1465
        int64_t* acquire_tablet_ms, int64_t* acquire_rowsets_ms, int64_t* acquire_segments_ms,
1466
        int64_t* lookup_row_data_ms, std::unordered_map<SegKey, SegItem, HashOfSegKey>& seg_map,
1467
        std::unordered_map<IteratorKey, IteratorItem, HashOfIteratorKey>& iterator_map,
1468
0
        io::FileCacheMissPolicy file_cache_miss_policy, Block& result_block) {
1469
0
    auto [tablet_id, rowset_id, segment_id] = file_mapping->get_doris_format_info();
1470
0
    SegKey seg_key {.tablet_id = tablet_id, .rowset_id = rowset_id, .segment_id = segment_id};
1471
1472
0
    BaseTabletSPtr tablet;
1473
0
    BetaRowsetSharedPtr rowset;
1474
0
    SegmentSharedPtr segment;
1475
0
    if (seg_map.find(seg_key) == seg_map.end()) {
1476
0
        tablet = scope_timer_run(
1477
0
                [&]() {
1478
0
                    auto res = ExecEnv::get_tablet(tablet_id);
1479
0
                    return !res.has_value() ? nullptr
1480
0
                                            : std::dynamic_pointer_cast<BaseTablet>(res.value());
1481
0
                },
1482
0
                acquire_tablet_ms);
1483
0
        if (!tablet) {
1484
0
            return Status::InternalError(
1485
0
                    "Backend:{} tablet not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1486
0
                    "row_id: {}",
1487
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1488
0
                    row_ids[0]);
1489
0
        }
1490
1491
0
        rowset = std::static_pointer_cast<BetaRowset>(scope_timer_run(
1492
0
                [&]() { return id_file_map->get_temp_rowset(tablet_id, rowset_id); },
1493
0
                acquire_rowsets_ms));
1494
0
        if (!rowset) {
1495
0
            return Status::InternalError(
1496
0
                    "Backend:{} rowset_id not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1497
0
                    "row_id: {}",
1498
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1499
0
                    row_ids[0]);
1500
0
        }
1501
1502
0
        SegmentCacheHandle segment_cache;
1503
0
        RETURN_IF_ERROR(scope_timer_run(
1504
0
                [&]() {
1505
0
                    return SegmentLoader::instance()->load_segments(rowset, &segment_cache, true);
1506
0
                },
1507
0
                acquire_segments_ms));
1508
1509
0
        auto it = std::find_if(segment_cache.get_segments().cbegin(),
1510
0
                               segment_cache.get_segments().cend(),
1511
0
                               [segment_id](const segment_v2::SegmentSharedPtr& seg) {
1512
0
                                   return seg->id() == segment_id;
1513
0
                               });
1514
0
        if (it == segment_cache.get_segments().end()) {
1515
0
            return Status::InternalError(
1516
0
                    "Backend:{} segment not found, tablet_id: {}, rowset_id: {}, segment_id: {}, "
1517
0
                    "row_id: {}",
1518
0
                    BackendOptions::get_localhost(), tablet_id, rowset_id.to_string(), segment_id,
1519
0
                    row_ids[0]);
1520
0
        }
1521
0
        segment = *it;
1522
0
        seg_map[seg_key] = SegItem {.tablet = tablet, .rowset = rowset, .segment = segment};
1523
0
    } else {
1524
0
        auto& seg_item = seg_map[seg_key];
1525
0
        tablet = seg_item.tablet;
1526
0
        rowset = seg_item.rowset;
1527
0
        segment = seg_item.segment;
1528
0
    }
1529
1530
    // if row_store_read_struct not empty, means the line we should read from row_store
1531
0
    if (!row_store_read_struct.default_values.empty()) {
1532
0
        if (!tablet->tablet_schema()->has_row_store_for_all_columns()) {
1533
0
            return Status::InternalError("Tablet {} does not have row store for all columns",
1534
0
                                         tablet->tablet_id());
1535
0
        }
1536
0
        auto result_columns_guard = result_block.mutate_columns_scoped();
1537
0
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
1538
0
        io::IOContext io_ctx;
1539
0
        io_ctx.reader_type = ReaderType::READER_QUERY;
1540
0
        io_ctx.file_cache_stats = &stats.file_cache_stats;
1541
0
        io_ctx.file_cache_miss_policy = file_cache_miss_policy;
1542
0
        for (auto row_id : row_ids) {
1543
0
            RowLocation loc(rowset_id, segment->id(), cast_set<uint32_t>(row_id));
1544
0
            row_store_read_struct.row_store_buffer.clear();
1545
0
            RETURN_IF_ERROR(scope_timer_run(
1546
0
                    [&]() {
1547
0
                        return tablet->lookup_row_data({}, loc, rowset, stats,
1548
0
                                                       row_store_read_struct.row_store_buffer,
1549
0
                                                       false, &io_ctx);
1550
0
                    },
1551
0
                    lookup_row_data_ms));
1552
1553
0
            RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
1554
0
                    row_store_read_struct.serdes, row_store_read_struct.row_store_buffer.data(),
1555
0
                    row_store_read_struct.row_store_buffer.size(),
1556
0
                    row_store_read_struct.col_uid_to_idx, result_columns,
1557
0
                    row_store_read_struct.default_values, {}));
1558
0
        }
1559
0
    } else {
1560
0
        for (int x = 0; x < slots.size(); ++x) {
1561
0
            auto column_guard = result_block.mutate_column_scoped(x);
1562
0
            MutableColumnPtr& column = column_guard.mutable_column();
1563
0
            IteratorKey iterator_key {.tablet_id = tablet_id,
1564
0
                                      .rowset_id = rowset_id,
1565
0
                                      .segment_id = segment_id,
1566
0
                                      .slot_id = slots[x].id()};
1567
0
            IteratorItem& iterator_item = iterator_map[iterator_key];
1568
0
            if (iterator_item.segment == nullptr) {
1569
0
                iterator_map[iterator_key].segment = segment;
1570
0
                iterator_item.storage_read_options.stats = &stats;
1571
0
                iterator_item.storage_read_options.io_ctx.reader_type = ReaderType::READER_QUERY;
1572
0
                iterator_item.storage_read_options.io_ctx.file_cache_miss_policy =
1573
0
                        file_cache_miss_policy;
1574
0
            }
1575
0
            set_slot_access_paths(slots[x], full_read_schema, iterator_item.storage_read_options);
1576
0
            RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
1577
0
                    full_read_schema, &slots[x], row_ids, column,
1578
0
                    iterator_item.storage_read_options, iterator_item.iterator));
1579
0
        }
1580
0
    }
1581
0
    return Status::OK();
1582
0
}
1583
1584
#include "common/compile_check_end.h"
1585
1586
} // namespace doris