Coverage Report

Created: 2026-10-27 19:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/point_query_executor.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 "service/point_query_executor.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/Exprs_types.h>
23
#include <gen_cpp/PaloInternalService_types.h>
24
#include <gen_cpp/internal_service.pb.h>
25
#include <glog/logging.h>
26
#include <google/protobuf/extension_set.h>
27
#include <stdlib.h>
28
29
#include <memory>
30
#include <sstream>
31
#include <unordered_map>
32
#include <vector>
33
34
#include "cloud/cloud_tablet.h"
35
#include "cloud/config.h"
36
#include "common/cast_set.h"
37
#include "common/consts.h"
38
#include "common/status.h"
39
#include "core/data_type/data_type_factory.hpp"
40
#include "core/data_type_serde/data_type_serde.h"
41
#include "exec/sink/writer/vmysql_result_writer.h"
42
#include "exprs/vexpr.h"
43
#include "exprs/vexpr_context.h"
44
#include "exprs/vexpr_fwd.h"
45
#include "exprs/vslot_ref.h"
46
#include "io/cache/remote_scan_cache_write_limiter.h"
47
#include "io/fs/read_ahead_metrics.h"
48
#include "io/io_common.h"
49
#include "runtime/descriptors.h"
50
#include "runtime/exec_env.h"
51
#include "runtime/result_block_buffer.h"
52
#include "runtime/runtime_profile.h"
53
#include "runtime/runtime_state.h"
54
#include "runtime/thread_context.h"
55
#include "storage/row_cursor.h"
56
#include "storage/rowset/beta_rowset.h"
57
#include "storage/rowset/rowset_fwd.h"
58
#include "storage/schema.h"
59
#include "storage/segment/column_reader.h"
60
#include "storage/segment/rowid_read_ahead.h"
61
#include "storage/segment/segment_read_ahead.h"
62
#include "storage/tablet/tablet_schema.h"
63
#include "storage/utils.h"
64
#include "util/defer_op.h"
65
#include "util/jsonb/serialize.h"
66
#include "util/lru_cache.h"
67
#include "util/simd/bits.h"
68
#include "util/thrift_util.h"
69
70
namespace doris {
71
72
class PointQueryResultBlockBuffer final : public MySQLResultBlockBuffer {
73
public:
74
4
    PointQueryResultBlockBuffer(RuntimeState* state) : MySQLResultBlockBuffer(state) {}
75
4
    ~PointQueryResultBlockBuffer() override = default;
76
4
    std::shared_ptr<TFetchDataResult> get_block() {
77
4
        std::lock_guard<std::mutex> l(_lock);
78
4
        DCHECK_EQ(_result_batch_queue.size(), 1);
79
4
        auto result = std::move(_result_batch_queue.front());
80
4
        _result_batch_queue.pop_front();
81
4
        return result;
82
4
    }
83
};
84
85
4.09k
Reusable::~Reusable() = default;
86
87
// get missing and include column ids
88
// input include_cids : the output expr slots columns unique ids
89
// missing_cids : the output expr columns that not in row columns cids
90
static void get_missing_and_include_cids(const TabletSchema& schema,
91
                                         const std::vector<SlotDescriptor*>& slots,
92
                                         int target_rs_column_id,
93
                                         std::unordered_set<int>& missing_cids,
94
4.05k
                                         std::unordered_set<int>& include_cids) {
95
4.05k
    missing_cids.clear();
96
4.05k
    include_cids.clear();
97
4.06k
    for (auto* slot : slots) {
98
4.06k
        missing_cids.insert(slot->col_unique_id());
99
4.06k
    }
100
    // insert delete sign column id
101
4.05k
    missing_cids.insert(schema.columns()[schema.delete_sign_idx()]->unique_id());
102
4.05k
    if (target_rs_column_id == -1) {
103
        // no row store columns
104
4.04k
        return;
105
4.04k
    }
106
5
    const TabletColumn& target_rs_column = schema.column_by_uid(target_rs_column_id);
107
5
    DCHECK(target_rs_column.is_row_store_column());
108
    // An empty row_columns_uids() means the row-store column contains the full row. Keep
109
    // missing_cids empty so full-row point queries can be served entirely from the row store,
110
    // including row-cache hits. Read-time-synthesized hidden columns are intentionally not
111
    // supported on this fast path: for example, JSONB stores 0 for __DORIS_VERSION_COL__, while
112
    // its published value must be obtained from the rowset. Resolving it would require bypassing
113
    // the row cache and reading the column store with rowset context, defeating this optimization.
114
6
    if (schema.row_columns_uids().empty()) {
115
6
        missing_cids.clear();
116
6
        return;
117
6
    }
118
18.4E
    for (int cid : schema.row_columns_uids()) {
119
0
        missing_cids.erase(cid);
120
0
        include_cids.insert(cid);
121
0
    }
122
18.4E
}
123
124
static void extract_slot_ref(const VExprSPtr& expr, TupleDescriptor* tuple_desc,
125
4.06k
                             std::vector<SlotDescriptor*>& slots) {
126
4.06k
    const auto& children = expr->children();
127
4.06k
    for (const auto& i : children) {
128
0
        extract_slot_ref(i, tuple_desc, slots);
129
0
    }
130
131
4.06k
    auto node_type = expr->node_type();
132
4.06k
    if (node_type == TExprNodeType::SLOT_REF) {
133
4.06k
        int column_id = static_cast<const VSlotRef*>(expr.get())->column_id();
134
4.06k
        auto* slot_desc = tuple_desc->slots()[column_id];
135
4.06k
        slots.push_back(slot_desc);
136
4.06k
    }
137
4.06k
}
138
139
Status Reusable::init(const TDescriptorTable& t_desc_tbl, const std::vector<TExpr>& output_exprs,
140
                      const TQueryOptions& query_options, const TabletSchema& schema,
141
4.05k
                      size_t block_size) {
142
4.05k
    _runtime_state = RuntimeState::create_unique();
143
4.05k
    _runtime_state->set_query_options(query_options);
144
4.05k
    RETURN_IF_ERROR(DescriptorTbl::create(_runtime_state->obj_pool(), t_desc_tbl, &_desc_tbl));
145
4.05k
    _runtime_state->set_desc_tbl(_desc_tbl);
146
89.0k
    for (const auto* slot : tuple_desc()->slots()) {
147
89.0k
        if (!slot->all_access_paths().empty() || !slot->predicate_access_paths().empty()) {
148
0
            return Status::InternalError(
149
0
                    "Short-circuit point query does not support nested column access paths, "
150
0
                    "slot: {}. Please upgrade FE to disable nested column pruning for "
151
0
                    "short-circuit point queries.",
152
0
                    slot->col_name());
153
0
        }
154
89.0k
    }
155
4.05k
    _block_pool.resize(block_size);
156
8.10k
    for (auto& i : _block_pool) {
157
8.10k
        i = Block::create_unique(tuple_desc()->slots(), 2);
158
        // Name is useless but cost space
159
8.10k
        i->clear_names();
160
8.10k
    }
161
162
4.05k
    RETURN_IF_ERROR(VExpr::create_expr_trees(output_exprs, _output_exprs_ctxs));
163
4.05k
    RowDescriptor row_desc(tuple_desc());
164
    // Prepare the exprs to run.
165
4.05k
    RETURN_IF_ERROR(VExpr::prepare(_output_exprs_ctxs, _runtime_state.get(), row_desc));
166
4.05k
    RETURN_IF_ERROR(VExpr::open(_output_exprs_ctxs, _runtime_state.get()));
167
4.05k
    _create_timestamp = butil::gettimeofday_ms();
168
4.05k
    _data_type_serdes = create_data_type_serdes(tuple_desc()->slots());
169
4.05k
    _col_default_values.resize(tuple_desc()->slots().size());
170
4.05k
    bool has_delete_sign = false;
171
93.0k
    for (int i = 0; i < tuple_desc()->slots().size(); ++i) {
172
89.0k
        auto* slot = tuple_desc()->slots()[i];
173
89.0k
        if (slot->col_name() == DELETE_SIGN) {
174
6
            has_delete_sign = true;
175
6
        }
176
89.0k
        _col_uid_to_idx[slot->col_unique_id()] = i;
177
89.0k
        _col_default_values[i] = slot->col_default_value();
178
89.0k
    }
179
180
    // Get the output slot descriptors
181
4.05k
    std::vector<SlotDescriptor*> output_slot_descs;
182
4.06k
    for (const auto& expr : _output_exprs_ctxs) {
183
4.06k
        extract_slot_ref(expr->root(), tuple_desc(), output_slot_descs);
184
4.06k
    }
185
186
    // get the delete sign idx in block
187
4.05k
    if (has_delete_sign) {
188
6
        _delete_sign_idx = _col_uid_to_idx[schema.columns()[schema.delete_sign_idx()]->unique_id()];
189
6
    }
190
191
4.05k
    if (schema.have_column(BeConsts::ROW_STORE_COL)) {
192
6
        const auto& column = *DORIS_TRY(schema.column(BeConsts::ROW_STORE_COL));
193
6
        _row_store_column_ids = column.unique_id();
194
6
    }
195
4.05k
    get_missing_and_include_cids(schema, output_slot_descs, _row_store_column_ids,
196
4.05k
                                 _missing_col_uids, _include_col_uids);
197
198
4.05k
    return Status::OK();
199
4.05k
}
200
201
6
std::unique_ptr<Block> Reusable::get_block() {
202
6
    std::lock_guard lock(_block_mutex);
203
6
    if (_block_pool.empty()) {
204
0
        auto block = Block::create_unique(tuple_desc()->slots(), 2);
205
        // Name is useless but cost space
206
0
        block->clear_names();
207
0
        return block;
208
0
    }
209
6
    auto block = std::move(_block_pool.back());
210
6
    CHECK(block != nullptr);
211
6
    _block_pool.pop_back();
212
6
    return block;
213
6
}
214
215
4
void Reusable::return_block(std::unique_ptr<Block>& block) {
216
4
    std::lock_guard lock(_block_mutex);
217
4
    if (block == nullptr) {
218
0
        return;
219
0
    }
220
4
    block->clear_column_data();
221
4
    _block_pool.push_back(std::move(block));
222
4
    const auto block_pool_size = config::get_lookup_connection_cache_block_pool_size();
223
4
    if (_block_pool.size() > block_pool_size) {
224
0
        _block_pool.resize(block_pool_size);
225
0
    }
226
4
}
227
228
0
LookupConnectionCache* LookupConnectionCache::create_global_instance(size_t capacity) {
229
0
    DCHECK(ExecEnv::GetInstance()->get_lookup_connection_cache() == nullptr);
230
0
    auto* res = new LookupConnectionCache(capacity);
231
0
    return res;
232
0
}
233
234
RowCache::RowCache(int64_t capacity, int num_shards)
235
9
        : LRUCachePolicy(CachePolicy::CacheType::POINT_QUERY_ROW_CACHE, capacity,
236
9
                         LRUCacheType::SIZE, config::point_query_row_cache_stale_sweep_time_sec,
237
9
                         num_shards, /*element count capacity */ 0,
238
9
                         /*enable prune*/ true, /*is lru-k*/ true) {}
239
240
// Create global instance of this class
241
0
RowCache* RowCache::create_global_cache(int64_t capacity, uint32_t num_shards) {
242
0
    DCHECK(ExecEnv::GetInstance()->get_row_cache() == nullptr);
243
0
    auto* res = new RowCache(capacity, num_shards);
244
0
    return res;
245
0
}
246
247
36
RowCache* RowCache::instance() {
248
36
    return ExecEnv::GetInstance()->get_row_cache();
249
36
}
250
251
26
bool RowCache::lookup(const RowCacheKey& key, CacheHandle* handle) {
252
26
    const std::string& encoded_key = key.encode();
253
26
    auto* lru_handle = LRUCachePolicy::lookup(encoded_key);
254
26
    if (!lru_handle) {
255
        // cache miss
256
13
        return false;
257
13
    }
258
13
    *handle = CacheHandle(this, lru_handle);
259
13
    return true;
260
26
}
261
262
23
void RowCache::insert(const RowCacheKey& key, const Slice& value) {
263
23
    char* cache_value = static_cast<char*>(malloc(value.size));
264
23
    memcpy(cache_value, value.data, value.size);
265
23
    auto* row_cache_value = new RowCacheValue;
266
23
    row_cache_value->cache_value = cache_value;
267
23
    const std::string& encoded_key = key.encode();
268
23
    auto* handle = LRUCachePolicy::insert(encoded_key, row_cache_value, value.size, value.size,
269
23
                                          CachePriority::NORMAL);
270
    // handle will released
271
23
    auto tmp = CacheHandle {this, handle};
272
23
}
273
274
3
void RowCache::erase(const RowCacheKey& key) {
275
3
    const std::string& encoded_key = key.encode();
276
3
    LRUCachePolicy::erase(encoded_key);
277
3
}
278
279
2.09k
LookupConnectionCache::CacheValue::~CacheValue() {
280
2.09k
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
281
2.09k
            ExecEnv::GetInstance()->point_query_executor_mem_tracker());
282
2.09k
    item.reset();
283
2.09k
}
284
285
6
PointQueryExecutor::~PointQueryExecutor() {
286
6
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(
287
6
            ExecEnv::GetInstance()->point_query_executor_mem_tracker());
288
6
    _tablet.reset();
289
6
    _reusable.reset();
290
6
    _result_block.reset();
291
6
    _row_read_ctxs.clear();
292
6
}
293
294
0
void PointQueryExecutor::_init_remote_scan_cache_write_limiter() {
295
0
    const auto& query_options = _reusable->runtime_state()->query_options();
296
0
    const bool initialize_remote_scan_cache_write_limiter =
297
0
            config::is_cloud_mode() && config::enable_file_cache &&
298
0
            query_options.__isset.file_cache_query_limit_bytes &&
299
0
            query_options.file_cache_query_limit_bytes >= 0 &&
300
0
            query_options.query_type == TQueryType::SELECT;
301
0
    if (initialize_remote_scan_cache_write_limiter) {
302
0
        _remote_scan_cache_write_limiter = std::make_unique<io::RemoteScanCacheWriteLimiter>(
303
0
                _reusable->runtime_state()->query_id(), query_options.file_cache_query_limit_bytes);
304
0
    }
305
0
}
306
307
Status PointQueryExecutor::init(const PTabletKeyLookupRequest* request,
308
0
                                PTabletKeyLookupResponse* response) {
309
0
    SCOPED_TIMER(&_profile_metrics.init_ns);
310
0
    _response = response;
311
    // using cache
312
0
    __int128_t uuid =
313
0
            static_cast<__int128_t>(request->uuid().uuid_high()) << 64 | request->uuid().uuid_low();
314
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->point_query_executor_mem_tracker());
315
0
    auto cache_handle = LookupConnectionCache::instance()->get(uuid);
316
0
    _binary_row_format = request->is_binary_row();
317
0
    _tablet = DORIS_TRY(ExecEnv::get_tablet(request->tablet_id()));
318
0
    if (cache_handle != nullptr) {
319
0
        _reusable = cache_handle;
320
0
        _profile_metrics.hit_lookup_cache = true;
321
0
    } else {
322
        // Lightweight request: FE may omit reusable query context and rely on uuid cache.
323
        // If cache miss and required parameters are absent, ask FE to resend a full request.
324
0
        if (uuid != 0 && (!request->has_desc_tbl() || request->desc_tbl().empty() ||
325
0
                          !request->has_output_expr() || request->output_expr().empty() ||
326
0
                          !request->has_query_options() || request->query_options().empty())) {
327
0
            if (VLOG_DEBUG_IS_ON) {
328
0
                VLOG_DEBUG << "lookup connection cache miss, ask FE to resend query context"
329
0
                           << ", tablet_id=" << request->tablet_id()
330
0
                           << ", uuid_high=" << request->uuid().uuid_high()
331
0
                           << ", uuid_low=" << request->uuid().uuid_low();
332
0
            }
333
0
            response->set_need_resend_query_context(true);
334
0
            return Status::OK();
335
0
        }
336
0
        if (uuid == 0 && (!request->has_desc_tbl() || request->desc_tbl().empty() ||
337
0
                          !request->has_output_expr() || request->output_expr().empty())) {
338
0
            return Status::InvalidArgument(
339
0
                    "tablet_fetch_data requires desc_tbl/output_expr when uuid is not set");
340
0
        }
341
        // init handle
342
0
        auto reusable_ptr = std::make_shared<Reusable>();
343
0
        TDescriptorTable t_desc_tbl;
344
0
        TExprList t_output_exprs;
345
0
        auto len = cast_set<uint32_t>(request->desc_tbl().size());
346
0
        RETURN_IF_ERROR(
347
0
                deserialize_thrift_msg(reinterpret_cast<const uint8_t*>(request->desc_tbl().data()),
348
0
                                       &len, false, &t_desc_tbl));
349
0
        len = cast_set<uint32_t>(request->output_expr().size());
350
0
        RETURN_IF_ERROR(deserialize_thrift_msg(
351
0
                reinterpret_cast<const uint8_t*>(request->output_expr().data()), &len, false,
352
0
                &t_output_exprs));
353
0
        _reusable = reusable_ptr;
354
0
        TQueryOptions t_query_options;
355
0
        len = cast_set<uint32_t>(request->query_options().size());
356
0
        if (request->has_query_options()) {
357
0
            RETURN_IF_ERROR(deserialize_thrift_msg(
358
0
                    reinterpret_cast<const uint8_t*>(request->query_options().data()), &len, false,
359
0
                    &t_query_options));
360
0
        }
361
0
        RETURN_IF_ERROR(reusable_ptr->init(t_desc_tbl, t_output_exprs.exprs, t_query_options,
362
0
                                           *_tablet->tablet_schema(), 1));
363
0
        if (uuid != 0) {
364
0
            LookupConnectionCache::instance()->add(uuid, reusable_ptr);
365
0
        }
366
0
    }
367
0
    _init_remote_scan_cache_write_limiter();
368
    // Set timezone from request for functions like from_unixtime()
369
0
    if (request->has_time_zone() && !request->time_zone().empty()) {
370
0
        _reusable->runtime_state()->set_timezone(request->time_zone());
371
0
    }
372
0
    if (request->has_version() && request->version() >= 0) {
373
0
        _version = request->version();
374
0
    }
375
0
    RETURN_IF_ERROR(_init_keys(request));
376
0
    _result_block = _reusable->get_block();
377
0
    CHECK(_result_block != nullptr);
378
379
0
    return Status::OK();
380
0
}
381
382
4
Status PointQueryExecutor::lookup_up() {
383
4
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->point_query_executor_mem_tracker());
384
4
    RETURN_IF_ERROR(_lookup_row_key());
385
4
    RETURN_IF_ERROR(_lookup_row_data());
386
4
    RETURN_IF_ERROR(_output_data());
387
4
    return Status::OK();
388
4
}
389
390
0
void PointQueryExecutor::print_profile() {
391
0
    auto init_us = _profile_metrics.init_ns.value() / 1000;
392
0
    auto init_key_us = _profile_metrics.init_key_ns.value() / 1000;
393
0
    auto lookup_key_us = _profile_metrics.lookup_key_ns.value() / 1000;
394
0
    auto lookup_data_us = _profile_metrics.lookup_data_ns.value() / 1000;
395
0
    auto output_data_us = _profile_metrics.output_data_ns.value() / 1000;
396
0
    auto load_segments_key_us = _profile_metrics.load_segment_key_stage_ns.value() / 1000;
397
0
    auto load_segments_data_us = _profile_metrics.load_segment_data_stage_ns.value() / 1000;
398
0
    auto total_us = init_us + lookup_key_us + lookup_data_us + output_data_us;
399
0
    auto read_stats = _profile_metrics.read_stats;
400
0
    const std::string stats_str = fmt::format(
401
0
            "[lookup profile:{}us] init:{}us, init_key:{}us,"
402
0
            " lookup_key:{}us, load_segments_key:{}us, lookup_data:{}us, load_segments_data:{}us,"
403
0
            " output_data:{}us, "
404
0
            "hit_lookup_cache:{}"
405
0
            ", is_binary_row:{}, output_columns:{}, total_keys:{}, row_cache_hits:{}"
406
0
            ", hit_cached_pages:{}, total_pages_read:{}, compressed_bytes_read:{}, "
407
0
            "io_latency:{}ns, "
408
0
            "uncompressed_bytes_read:{}, result_data_bytes:{}, row_hits:{}"
409
0
            ", rs_column_uid:{}, bytes_read_from_local:{}, bytes_read_from_remote:{}, "
410
0
            "local_io_timer:{}, remote_io_timer:{}, local_write_timer:{}",
411
0
            total_us, init_us, init_key_us, lookup_key_us, load_segments_key_us, lookup_data_us,
412
0
            load_segments_data_us, output_data_us, _profile_metrics.hit_lookup_cache,
413
0
            _binary_row_format, _reusable->output_exprs().size(), _row_read_ctxs.size(),
414
0
            _profile_metrics.row_cache_hits, read_stats.cached_pages_num,
415
0
            read_stats.total_pages_num, read_stats.compressed_bytes_read, read_stats.io_ns,
416
0
            read_stats.uncompressed_bytes_read, _profile_metrics.result_data_bytes, _row_hits,
417
0
            _reusable->rs_column_uid(),
418
0
            _profile_metrics.read_stats.file_cache_stats.bytes_read_from_local,
419
0
            _profile_metrics.read_stats.file_cache_stats.bytes_read_from_remote,
420
0
            _profile_metrics.read_stats.file_cache_stats.local_io_timer,
421
0
            _profile_metrics.read_stats.file_cache_stats.remote_io_timer,
422
0
            _profile_metrics.read_stats.file_cache_stats.write_cache_io_timer);
423
424
0
    const auto read_ahead_profile = [&]() {
425
0
        if (_profile_metrics.read_stats.read_ahead_stats == nullptr &&
426
0
            _read_stats.read_ahead_stats == nullptr) {
427
0
            return std::string {};
428
0
        }
429
0
        RuntimeProfile profile("PageReadAhead");
430
0
        for (auto* stats : {&_profile_metrics.read_stats, &_read_stats}) {
431
0
            if (stats->read_ahead_stats != nullptr) {
432
0
                stats->read_ahead_stats->update_profile(&profile);
433
0
            }
434
0
        }
435
0
        std::ostringstream output;
436
0
        profile.pretty_print(&output);
437
0
        return "\n" + output.str();
438
0
    };
439
440
0
    constexpr static int kSlowThreholdUs = 50 * 1000; // 50ms
441
0
    if (total_us > kSlowThreholdUs) {
442
0
        LOG(WARNING) << "slow query, " << stats_str << read_ahead_profile();
443
0
    } else if (VLOG_DEBUG_IS_ON) {
444
0
        VLOG_DEBUG << stats_str << read_ahead_profile();
445
0
    } else {
446
0
        LOG_EVERY_N(INFO, 1000) << stats_str << read_ahead_profile();
447
0
    }
448
0
}
449
450
6
Status PointQueryExecutor::_init_keys(const PTabletKeyLookupRequest* request) {
451
6
    SCOPED_TIMER(&_profile_metrics.init_key_ns);
452
6
    const auto& schema = _tablet->tablet_schema();
453
    // Point query is only supported on merge-on-write unique key tables.
454
6
    DCHECK(schema->keys_type() == UNIQUE_KEYS && _tablet->enable_unique_key_merge_on_write());
455
6
    if (schema->keys_type() != UNIQUE_KEYS || !_tablet->enable_unique_key_merge_on_write()) {
456
0
        return Status::InvalidArgument(
457
0
                "Point query is only supported on merge-on-write unique key tables, "
458
0
                "tablet_id={}",
459
0
                _tablet->tablet_id());
460
0
    }
461
    // 1. get primary key from conditions
462
6
    _row_read_ctxs.resize(request->key_tuples().size());
463
    // get row cursor and encode keys
464
34
    for (int i = 0; i < request->key_tuples().size(); ++i) {
465
28
        const KeyTuple& key_tuple = request->key_tuples(i);
466
28
        if (UNLIKELY(cast_set<size_t>(key_tuple.key_column_literals_size()) !=
467
28
                     schema->num_key_columns())) {
468
0
            return Status::InvalidArgument(
469
0
                    "Key column count mismatch. expected={}, actual={}, tablet_id={}",
470
0
                    schema->num_key_columns(), key_tuple.key_column_literals_size(),
471
0
                    _tablet->tablet_id());
472
0
        }
473
28
        RowCursor cursor;
474
28
        std::vector<Field> key_fields;
475
28
        key_fields.reserve(key_tuple.key_column_literals_size());
476
56
        for (int j = 0; j < key_tuple.key_column_literals_size(); ++j) {
477
28
            const auto& literal_bytes = key_tuple.key_column_literals(j);
478
28
            TExprNode expr_node;
479
28
            auto len = cast_set<uint32_t>(literal_bytes.size());
480
28
            RETURN_IF_ERROR(
481
28
                    deserialize_thrift_msg(reinterpret_cast<const uint8_t*>(literal_bytes.data()),
482
28
                                           &len, false, &expr_node));
483
28
            const auto& col = schema->column(j);
484
28
            auto data_type = DataTypeFactory::instance().create_data_type(
485
28
                    col.type(), col.precision(), col.frac(), col.length());
486
28
            key_fields.push_back(data_type->get_field(expr_node));
487
28
        }
488
28
        RETURN_IF_ERROR(cursor.init_scan_key(_tablet->tablet_schema(), std::move(key_fields)));
489
28
        cursor.encode_key_with_padding<true>(&_row_read_ctxs[i]._primary_key,
490
28
                                             _tablet->tablet_schema()->num_key_columns(), true);
491
28
    }
492
6
    return Status::OK();
493
6
}
494
495
6
Status PointQueryExecutor::_lookup_row_key() {
496
6
    SCOPED_TIMER(&_profile_metrics.lookup_key_ns);
497
    // 2. lookup row location
498
6
    Status st;
499
6
    if (_version >= 0) {
500
0
        CHECK(config::is_cloud_mode()) << "Only cloud mode support snapshot read at present";
501
0
        SyncOptions options;
502
0
        options.query_version = _version;
503
0
        RETURN_IF_ERROR(std::dynamic_pointer_cast<CloudTablet>(_tablet)->sync_rowsets(options));
504
0
    }
505
6
    std::vector<RowsetSharedPtr> specified_rowsets;
506
6
    {
507
6
        std::shared_lock rlock(_tablet->get_header_lock());
508
6
        specified_rowsets = _tablet->get_rowset_by_ids(nullptr);
509
6
    }
510
6
    io::IOContext io_ctx;
511
6
    io_ctx.reader_type = ReaderType::READER_QUERY;
512
6
    io_ctx.file_cache_stats = &_profile_metrics.read_stats.file_cache_stats;
513
6
    io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
514
6
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
515
34
    for (size_t i = 0; i < _row_read_ctxs.size(); ++i) {
516
28
        RowLocation location;
517
28
        if (!config::disable_storage_row_cache) {
518
16
            RowCache::CacheHandle cache_handle;
519
16
            auto hit_cache = RowCache::instance()->lookup(
520
16
                    {_tablet->tablet_id(), _row_read_ctxs[i]._primary_key}, &cache_handle);
521
16
            if (hit_cache) {
522
8
                _row_read_ctxs[i]._cached_row_data = std::move(cache_handle);
523
8
                ++_profile_metrics.row_cache_hits;
524
8
                continue;
525
8
            }
526
16
        }
527
        // Get rowlocation and rowset, ctx._rowset_ptr will acquire wrap this ptr
528
20
        auto rowset_ptr = std::make_unique<RowsetSharedPtr>();
529
20
        st = (_tablet->lookup_row_key(
530
20
                _row_read_ctxs[i]._primary_key, nullptr, false, specified_rowsets, &location,
531
20
                INT32_MAX /*rethink?*/, segment_caches, rowset_ptr.get(), false, nullptr,
532
20
                &_profile_metrics.read_stats, nullptr, &io_ctx, &_row_read_ctxs[i]._segment));
533
20
        if (st.is<ErrorCode::KEY_NOT_FOUND>()) {
534
4
            continue;
535
4
        }
536
16
        RETURN_IF_ERROR(st);
537
16
        _row_read_ctxs[i]._row_location = location;
538
        // acquire and wrap this rowset
539
16
        (*rowset_ptr)->acquire();
540
16
        VLOG_DEBUG << "aquire rowset " << (*rowset_ptr)->rowset_id();
541
16
        _row_read_ctxs[i]._rowset_ptr = std::unique_ptr<RowsetSharedPtr, decltype(&release_rowset)>(
542
16
                rowset_ptr.release(), &release_rowset);
543
16
        _row_hits++;
544
16
    }
545
6
    return Status::OK();
546
6
}
547
548
6
Status PointQueryExecutor::_lookup_row_data() {
549
    // 3. get values
550
6
    SCOPED_TIMER(&_profile_metrics.lookup_data_ns);
551
6
    std::shared_ptr<io::FileRangeReadContext> read_ahead_context;
552
6
    if (segment_v2::SegmentReadAhead::enabled()) {
553
0
        auto* scheduler = ExecEnv::GetInstance()->file_range_read_scheduler();
554
0
        DORIS_CHECK(scheduler != nullptr);
555
0
        read_ahead_context = scheduler->create_context();
556
0
    }
557
6
    {
558
6
        auto result_columns_guard = _result_block->mutate_columns_scoped();
559
6
        MutableColumns& result_columns = result_columns_guard.mutable_columns();
560
34
        for (size_t i = 0; i < _row_read_ctxs.size(); ++i) {
561
28
            if (_row_read_ctxs[i]._cached_row_data.valid()) {
562
8
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
563
8
                        _reusable->get_data_type_serdes(),
564
8
                        _row_read_ctxs[i]._cached_row_data.data().data,
565
8
                        _row_read_ctxs[i]._cached_row_data.data().size,
566
8
                        _reusable->get_col_uid_to_idx(), result_columns,
567
8
                        _reusable->get_col_default_values(), _reusable->include_col_uids()));
568
8
                continue;
569
8
            }
570
20
            if (!_row_read_ctxs[i]._row_location.has_value()) {
571
4
                continue;
572
4
            }
573
16
            std::string value;
574
            // fill block by row store
575
16
            if (_reusable->rs_column_uid() != -1) {
576
16
                bool use_row_cache = !config::disable_storage_row_cache;
577
16
                io::IOContext io_ctx;
578
16
                io_ctx.reader_type = ReaderType::READER_QUERY;
579
16
                io_ctx.file_cache_stats = &_profile_metrics.read_stats.file_cache_stats;
580
16
                io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
581
16
                if (read_ahead_context != nullptr) {
582
0
                    RETURN_IF_ERROR(_tablet->lookup_row_data_with_read_ahead(
583
0
                            _row_read_ctxs[i]._primary_key, _row_read_ctxs[i]._row_location.value(),
584
0
                            _row_read_ctxs[i]._segment, *(_row_read_ctxs[i]._rowset_ptr),
585
0
                            _profile_metrics.read_stats, value, use_row_cache, &io_ctx,
586
0
                            read_ahead_context));
587
16
                } else {
588
16
                    RETURN_IF_ERROR(_tablet->lookup_row_data(
589
16
                            _row_read_ctxs[i]._primary_key, _row_read_ctxs[i]._row_location.value(),
590
16
                            _row_read_ctxs[i]._segment, *(_row_read_ctxs[i]._rowset_ptr),
591
16
                            _profile_metrics.read_stats, value, use_row_cache, &io_ctx));
592
16
                }
593
                // serialize value to block, currently only jsonb row format
594
16
                RETURN_IF_ERROR(JsonbSerializeUtil::jsonb_to_columns(
595
16
                        _reusable->get_data_type_serdes(), value.data(), value.size(),
596
16
                        _reusable->get_col_uid_to_idx(), result_columns,
597
16
                        _reusable->get_col_default_values(), _reusable->include_col_uids()));
598
16
            }
599
16
            if (!_reusable->missing_col_uids().empty()) {
600
0
                if (!_reusable->runtime_state()->enable_short_circuit_query_access_column_store()) {
601
0
                    std::string missing_columns;
602
0
                    for (int cid : _reusable->missing_col_uids()) {
603
                        // Named from the query, not the tablet schema: a column a light schema
604
                        // change just added is not in the tablet schema yet, and column_by_uid
605
                        // throws on a uid it does not hold.
606
0
                        const int pos = _reusable->get_col_uid_to_idx().at(cid);
607
0
                        missing_columns += _reusable->tuple_desc()->slots()[pos]->col_name() + ",";
608
0
                    }
609
0
                    return Status::InternalError(
610
0
                            "Not support column store, set store_row_column=true or "
611
0
                            "row_store_columns in table properties, missing columns: " +
612
0
                            missing_columns + " should be added to row store");
613
0
                }
614
                // fill missing columns by column store
615
0
                RowLocation row_loc = _row_read_ctxs[i]._row_location.value();
616
0
                BetaRowsetSharedPtr rowset = std::static_pointer_cast<BetaRowset>(
617
0
                        _tablet->get_rowset(row_loc.rowset_id));
618
0
                SegmentCacheHandle segment_cache;
619
0
                io::IOContext io_ctx;
620
0
                io_ctx.reader_type = ReaderType::READER_QUERY;
621
0
                io_ctx.file_cache_stats = &_read_stats.file_cache_stats;
622
0
                io_ctx.remote_scan_cache_write_limiter = _remote_scan_cache_write_limiter.get();
623
0
                {
624
0
                    SCOPED_TIMER(&_profile_metrics.load_segment_data_stage_ns);
625
0
                    RETURN_IF_ERROR(SegmentLoader::instance()->load_segments(
626
0
                            rowset, &segment_cache, true, false, &_read_stats, &io_ctx));
627
0
                }
628
                // find segment
629
0
                auto it = std::find_if(segment_cache.get_segments().cbegin(),
630
0
                                       segment_cache.get_segments().cend(),
631
0
                                       [&](const segment_v2::SegmentSharedPtr& seg) {
632
0
                                           return seg->id() == row_loc.segment_id;
633
0
                                       });
634
0
                const auto& segment = *it;
635
0
                StorageReadOptions read_ahead_options(_read_stats);
636
0
                read_ahead_options.use_page_cache = !config::disable_storage_page_cache;
637
0
                read_ahead_options.io_ctx = io_ctx;
638
                // Pre-read iterators need the same rowset constants as the synchronous path:
639
                // a version column in rowset [7-7] must produce 7, not its stored placeholder 0.
640
0
                read_ahead_options.version = rowset->version();
641
0
                read_ahead_options.commit_tso = rowset->commit_tso();
642
0
                std::unique_ptr<segment_v2::SegmentReadAhead> read_ahead;
643
0
                if (read_ahead_context != nullptr) {
644
0
                    const auto status = segment_v2::SegmentReadAhead::create_for_query(
645
0
                            segment->file_reader(), ExecEnv::GetInstance(), read_ahead_context,
646
0
                            read_ahead_options, &read_ahead);
647
0
                    if (!status.ok()) {
648
0
                        LOG_EVERY_N(WARNING, 100)
649
0
                                << "failed to initialize point-read column read-ahead; use the "
650
0
                                   "original read path: "
651
0
                                << status;
652
0
                    }
653
0
                }
654
0
                if (read_ahead != nullptr) {
655
0
                    const auto missing_column_count = _reusable->missing_col_uids().size();
656
0
                    std::vector<StorageReadOptions> read_options(missing_column_count,
657
0
                                                                 read_ahead_options);
658
0
                    std::vector<std::unique_ptr<ColumnIterator>> iterators(missing_column_count);
659
0
                    std::vector<segment_v2::RowIdColumnRead> column_reads;
660
0
                    column_reads.reserve(missing_column_count);
661
0
                    size_t read_index = 0;
662
0
                    for (int cid : _reusable->missing_col_uids()) {
663
0
                        int pos = _reusable->get_col_uid_to_idx().at(cid);
664
0
                        SlotDescriptor* slot = _reusable->tuple_desc()->slots()[pos];
665
0
                        column_reads.push_back({.slot = slot,
666
0
                                                .result = &result_columns[pos],
667
0
                                                .read_options = &read_options[read_index],
668
0
                                                .iterator = &iterators[read_index]});
669
0
                        ++read_index;
670
0
                    }
671
0
                    std::vector<segment_v2::rowid_t> row_ids {
672
0
                            static_cast<segment_v2::rowid_t>(row_loc.row_id)};
673
0
                    RETURN_IF_ERROR(segment_v2::read_columns_by_rowids_with_read_ahead(
674
0
                            *segment, *_tablet->tablet_schema(), row_ids, column_reads,
675
0
                            *read_ahead));
676
0
                } else {
677
0
                    const auto tablet_schema = _tablet->tablet_schema();
678
0
                    for (int cid : _reusable->missing_col_uids()) {
679
0
                        int pos = _reusable->get_col_uid_to_idx().at(cid);
680
0
                        std::vector<segment_v2::rowid_t> row_ids {
681
0
                                static_cast<segment_v2::rowid_t>(row_loc.row_id)};
682
0
                        auto& column = result_columns[pos];
683
0
                        std::unique_ptr<ColumnIterator> iter;
684
0
                        SlotDescriptor* slot = _reusable->tuple_desc()->slots()[pos];
685
0
                        int32_t index = slot->col_unique_id() >= 0
686
0
                                                ? tablet_schema->field_index(slot->col_unique_id())
687
0
                                                : tablet_schema->field_index(slot->col_name());
688
                        // A light schema change adds a column without writing anything, and
689
                        // BaseTablet::_max_version_schema only moves forward on write, so until the
690
                        // next load the tablet schema here does not have it. No segment holds it
691
                        // either, so describe it from the slot and let the segment answer with its
692
                        // default -- the same answer it gives once a load does bring the column in.
693
0
                        TabletColumn column_awaiting_a_load;
694
0
                        if (index < 0) {
695
0
                            column_awaiting_a_load = ReadSchema::tablet_column_from_slot(*slot);
696
0
                        }
697
0
                        const TabletColumn& read_column =
698
0
                                index >= 0 ? tablet_schema->column(index) : column_awaiting_a_load;
699
0
                        StorageReadOptions storage_read_options(_read_stats);
700
0
                        storage_read_options.io_ctx = io_ctx;
701
                        // A point lookup bypasses TabletReader, so supply the rowset context here. For
702
                        // example, reading __DORIS_VERSION_COL__ from rowset [7-7] must return 7
703
                        // instead of its on-disk placeholder 0.
704
0
                        storage_read_options.version = rowset->version();
705
0
                        storage_read_options.commit_tso = rowset->commit_tso();
706
0
                        RETURN_IF_ERROR(segment->seek_and_read_by_rowid(
707
0
                                read_column, slot, row_ids, column, storage_read_options, iter));
708
0
                    }
709
0
                }
710
0
            }
711
16
        }
712
6
        if (result_columns.size() > _reusable->include_col_uids().size()) {
713
            // Padding rows for some columns that no need to output to mysql client
714
            // eg. SELECT k1,v1,v2 FROM TABLE WHERE k1 = 1, k1 is not in output slots, tuple as bellow
715
            // TupleDescriptor{id=1, tbl=table_with_column_group}
716
            // SlotDescriptor{id=8, col=v1, colUniqueId=1 ...}
717
            // SlotDescriptor{id=9, col=v2, colUniqueId=2 ...}
718
            // thus missing in include_col_uids and missing_col_uids
719
24
            for (auto& column : result_columns) {
720
24
                int padding_rows = _row_hits - cast_set<int>(column->size());
721
24
                if (padding_rows > 0) {
722
0
                    column->insert_many_defaults(padding_rows);
723
0
                }
724
24
            }
725
6
        }
726
6
    }
727
    // filter rows by delete sign
728
6
    if (_row_hits > 0 && _reusable->delete_sign_idx() != -1) {
729
4
        size_t filtered = 0;
730
4
        size_t total = 0;
731
4
        {
732
            // clear_column_data will check reference of ColumnPtr, so we need to release
733
            // reference before clear_column_data
734
4
            ColumnPtr delete_filter_columns =
735
4
                    _result_block->get_columns()[_reusable->delete_sign_idx()];
736
4
            const auto& filter =
737
4
                    assert_cast<const ColumnInt8*>(delete_filter_columns.get())->get_data();
738
4
            filtered = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
739
4
            total = filter.size();
740
4
        }
741
742
4
        if (filtered == total) {
743
0
            _result_block->clear_column_data();
744
4
        } else if (filtered > 0) {
745
0
            return Status::NotSupported("Not implemented since only single row at present");
746
0
        }
747
4
    }
748
6
    return Status::OK();
749
6
}
750
751
4
Status serialize_block(std::shared_ptr<TFetchDataResult> res, PTabletKeyLookupResponse* response) {
752
4
    uint8_t* buf = nullptr;
753
4
    uint32_t len = 0;
754
4
    ThriftSerializer ser(false, 4096);
755
4
    RETURN_IF_ERROR(ser.serialize(&(res->result_batch), &len, &buf));
756
4
    response->set_row_batch(std::string((const char*)buf, len));
757
4
    return Status::OK();
758
4
}
759
760
4
Status PointQueryExecutor::_output_data() {
761
    // 4. exprs exec and serialize to mysql row batches
762
4
    SCOPED_TIMER(&_profile_metrics.output_data_ns);
763
4
    if (_result_block->rows()) {
764
4
        RuntimeState state;
765
4
        auto buffer = std::make_shared<PointQueryResultBlockBuffer>(&state);
766
        // TODO reuse mysql_writer
767
4
        VMysqlResultWriter mysql_writer(buffer, _reusable->output_exprs(), nullptr,
768
4
                                        _binary_row_format);
769
4
        RETURN_IF_ERROR(mysql_writer.init(_reusable->runtime_state()));
770
4
        _result_block->clear_names();
771
4
        RETURN_IF_ERROR(mysql_writer.write(_reusable->runtime_state(), *_result_block));
772
4
        RETURN_IF_ERROR(serialize_block(buffer->get_block(), _response));
773
4
        VLOG_DEBUG << "dump block " << _result_block->dump_data();
774
4
    } else {
775
0
        _response->set_empty_batch(true);
776
0
    }
777
4
    _profile_metrics.result_data_bytes = _result_block->bytes();
778
4
    _reusable->return_block(_result_block);
779
4
    return Status::OK();
780
4
}
781
782
} // namespace doris