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