Coverage Report

Created: 2026-05-20 21:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/runtime_state.h
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
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/runtime/runtime-state.h
19
// and modified by Doris
20
21
#pragma once
22
23
#include <gen_cpp/PaloInternalService_types.h>
24
#include <gen_cpp/Types_types.h>
25
#include <gen_cpp/segment_v2.pb.h>
26
#include <stdint.h>
27
28
#include <atomic>
29
#include <cstdint>
30
#include <fstream>
31
#include <functional>
32
#include <memory>
33
#include <mutex>
34
#include <shared_mutex>
35
#include <string>
36
#include <vector>
37
38
#include "agent/be_exec_version_manager.h"
39
#include "cctz/time_zone.h"
40
#include "common/be_mock_util.h"
41
#include "common/compiler_util.h" // IWYU pragma: keep
42
#include "common/config.h"
43
#include "common/factory_creator.h"
44
#include "common/status.h"
45
#include "exec/scan/vector_search_user_params.h"
46
#include "io/fs/s3_file_system.h"
47
#include "runtime/runtime_profile.h"
48
#include "runtime/task_execution_context.h"
49
#include "runtime/workload_group/workload_group.h"
50
#include "util/debug_util.h"
51
#include "util/timezone_utils.h"
52
53
namespace doris {
54
class RuntimeFilter;
55
56
23
inline int32_t get_execution_rpc_timeout_ms(int32_t execution_timeout_sec) {
57
23
    return std::min(config::execution_max_rpc_timeout_sec, execution_timeout_sec) * 1000;
58
23
}
59
60
class PipelineXLocalStateBase;
61
class PipelineXSinkLocalStateBase;
62
class PipelineFragmentContext;
63
class PipelineTask;
64
class Dependency;
65
66
class DescriptorTbl;
67
class ObjectPool;
68
class ExecEnv;
69
class IdFileMap;
70
class RuntimeFilterMgr;
71
class MemTrackerLimiter;
72
class QueryContext;
73
class RuntimeFilterConsumer;
74
class RuntimeFilterProducer;
75
class TaskExecutionContext;
76
77
// A collection of items that are part of the global state of a
78
// query and shared across all execution nodes of that query.
79
class RuntimeState {
80
    ENABLE_FACTORY_CREATOR(RuntimeState);
81
82
public:
83
    RuntimeState(const TPlanFragmentExecParams& fragment_exec_params,
84
                 const TQueryOptions& query_options, const TQueryGlobals& query_globals,
85
                 ExecEnv* exec_env, QueryContext* ctx,
86
                 const std::shared_ptr<MemTrackerLimiter>& query_mem_tracker = nullptr);
87
88
    RuntimeState(const TUniqueId& instance_id, const TUniqueId& query_id, int32_t fragment_id,
89
                 const TQueryOptions& query_options, const TQueryGlobals& query_globals,
90
                 ExecEnv* exec_env, QueryContext* ctx);
91
92
    // Used by pipeline. This runtime state is only used for setup.
93
    RuntimeState(const TUniqueId& query_id, int32_t fragment_id, const TQueryOptions& query_options,
94
                 const TQueryGlobals& query_globals, ExecEnv* exec_env, QueryContext* ctx);
95
96
    // Only used in the materialization phase of delayed materialization,
97
    // when there may be no corresponding QueryContext.
98
    RuntimeState(const TUniqueId& query_id, int32_t fragment_id, const TQueryOptions& query_options,
99
                 const TQueryGlobals& query_globals, ExecEnv* exec_env,
100
                 const std::shared_ptr<MemTrackerLimiter>& query_mem_tracker);
101
102
    // RuntimeState for executing expr in fe-support.
103
    RuntimeState(const TQueryOptions& query_options, const TQueryGlobals& query_globals);
104
105
    // for job task only
106
    RuntimeState();
107
108
    // Empty d'tor to avoid issues with unique_ptr.
109
    MOCK_DEFINE(virtual) ~RuntimeState();
110
111
    // Set per-query state.
112
    Status init(const TUniqueId& fragment_instance_id, const TQueryOptions& query_options,
113
                const TQueryGlobals& query_globals, ExecEnv* exec_env);
114
115
    // for ut and non-query.
116
0
    void set_exec_env(ExecEnv* exec_env) { _exec_env = exec_env; }
117
118
    // for ut and non-query.
119
    void init_mem_trackers(const std::string& name = "ut", const TUniqueId& id = TUniqueId());
120
121
1.71k
    const TQueryOptions& query_options() const { return _query_options; }
122
8
    int64_t scan_queue_mem_limit() const {
123
8
        return _query_options.__isset.scan_queue_mem_limit ? _query_options.scan_queue_mem_limit
124
8
                                                           : _query_options.mem_limit / 20;
125
8
    }
126
127
48.2k
    bool enable_adjust_conjunct_order_by_cost() const {
128
48.2k
        return _query_options.__isset.enable_adjust_conjunct_order_by_cost &&
129
48.2k
               _query_options.enable_adjust_conjunct_order_by_cost;
130
48.2k
    }
131
132
6
    int32_t max_column_reader_num() const {
133
6
        return _query_options.__isset.max_column_reader_num ? _query_options.max_column_reader_num
134
6
                                                            : 20000;
135
6
    }
136
137
221k
    ObjectPool* obj_pool() const { return _obj_pool.get(); }
138
139
547k
    const DescriptorTbl& desc_tbl() const { return *_desc_tbl; }
140
270k
    void set_desc_tbl(const DescriptorTbl* desc_tbl) { _desc_tbl = desc_tbl; }
141
142
    // Row-count limit for output blocks. Clamp to [1, 65535].
143
    // Adaptive byte budgeting still uses this as the hard row ceiling.
144
10.2k
    MOCK_FUNCTION int batch_size() const {
145
10.2k
        static constexpr int kMax = 65535;
146
10.2k
        auto v = _query_options.batch_size;
147
10.2k
        return std::min(std::max(1, v), kMax);
148
10.2k
    }
149
150
    // Target byte budget per output block (default 8MB when adaptive is enabled).
151
    // The public FE/session contract is [1MB, 512MB]; this accessor still clamps any direct
152
    // thrift or mixed-version out-of-range value into that range. Returns `kMax` when adaptive
153
    // is disabled by BE config so the value is always a legal byte budget; callers that need
154
    // to know whether adaptive batch size is active should test
155
    // `config::enable_adaptive_batch_size` explicitly.
156
82
    MOCK_FUNCTION size_t preferred_block_size_bytes() const {
157
82
        static constexpr int64_t kDefault = 8388608L; // 8MB
158
82
        static constexpr int64_t kMax = 536870912L;   // 512MB
159
82
        static constexpr int64_t kMin = 1048576L;     // 1MB
160
82
        if (!config::enable_adaptive_batch_size) [[unlikely]] {
161
3
            return kMax;
162
3
        }
163
79
        if (_query_options.__isset.preferred_block_size_bytes) [[likely]] {
164
79
            return std::max<int64_t>(
165
79
                    kMin, std::min<int64_t>(_query_options.preferred_block_size_bytes, kMax));
166
79
        }
167
0
        return kDefault;
168
79
    }
169
170
45
    int query_parallel_instance_num() const { return _query_options.parallel_instance; }
171
0
    int max_errors() const { return _query_options.max_errors; }
172
28
    int execution_timeout() const {
173
28
        return _query_options.__isset.execution_timeout ? _query_options.execution_timeout
174
28
                                                        : _query_options.query_timeout;
175
28
    }
176
0
    int max_scanners_concurrency() const {
177
0
        return _query_options.__isset.max_scanners_concurrency
178
0
                       ? _query_options.max_scanners_concurrency
179
0
                       : 0;
180
0
    }
181
3
    int max_file_scanners_concurrency() const {
182
3
        return _query_options.__isset.max_file_scanners_concurrency
183
3
                       ? _query_options.max_file_scanners_concurrency
184
3
                       : max_scanners_concurrency();
185
3
    }
186
187
36
    int min_scanners_concurrency() const {
188
36
        return _query_options.__isset.min_scanners_concurrency
189
36
                       ? _query_options.min_scanners_concurrency
190
36
                       : 1;
191
36
    }
192
193
0
    int min_file_scanners_concurrency() const {
194
0
        return _query_options.__isset.min_file_scanners_concurrency
195
0
                       ? _query_options.min_file_scanners_concurrency
196
0
                       : 1;
197
0
    }
198
199
    // Support extended regex
200
    // like look-around zero-width assertions(`?=`, `?!`, `?<=`, `?<!`)
201
26
    bool enable_extended_regex() const {
202
26
        return _query_options.__isset.enable_extended_regex && _query_options.enable_extended_regex;
203
26
    }
204
205
121
    TQueryType::type query_type() const { return _query_options.query_type; }
206
21
    int64_t timestamp_ms() const { return _timestamp_ms; }
207
12
    int32_t nano_seconds() const { return _nano_seconds; }
208
    // if possible, use timezone_obj() rather than timezone()
209
37
    const std::string& timezone() const { return _timezone; }
210
278
    const cctz::time_zone& timezone_obj() const { return _timezone_obj; }
211
0
    void set_timezone(const std::string& timezone) {
212
0
        _timezone = timezone;
213
0
        TimezoneUtils::find_cctz_time_zone(_timezone, _timezone_obj);
214
0
    }
215
3
    const std::string& lc_time_names() const { return _lc_time_names; }
216
0
    const std::string& user() const { return _user; }
217
498
    const TUniqueId& query_id() const { return _query_id; }
218
20.7k
    const TUniqueId& fragment_instance_id() const { return _fragment_instance_id; }
219
    // should only be called in pipeline engine
220
73
    int32_t fragment_id() const { return _fragment_id; }
221
81
    ExecEnv* exec_env() { return _exec_env; }
222
    std::shared_ptr<MemTrackerLimiter> query_mem_tracker() const;
223
224
    // Returns runtime state profile
225
3
    RuntimeProfile* runtime_profile() { return &_profile; }
226
0
    RuntimeProfile* load_channel_profile() { return &_load_channel_profile; }
227
228
99
    bool enable_function_pushdown() const {
229
99
        return _query_options.__isset.enable_function_pushdown &&
230
99
               _query_options.enable_function_pushdown;
231
99
    }
232
233
103
    bool check_overflow_for_decimal() const {
234
103
        return _query_options.__isset.check_overflow_for_decimal &&
235
103
               _query_options.check_overflow_for_decimal;
236
103
    }
237
238
103
    bool enable_strict_mode() const {
239
103
        return _query_options.__isset.enable_strict_cast && _query_options.enable_strict_cast;
240
103
    }
241
242
0
    bool enable_insert_strict() const {
243
0
        return _query_options.__isset.enable_insert_strict && _query_options.enable_insert_strict;
244
0
    }
245
246
0
    bool enable_segment_limit_pushdown() const {
247
0
        return !_query_options.__isset.enable_segment_limit_pushdown ||
248
0
               _query_options.enable_segment_limit_pushdown;
249
0
    }
250
251
0
    bool mysql_row_binary_format() const {
252
0
        return _query_options.__isset.mysql_row_binary_format &&
253
0
               _query_options.mysql_row_binary_format;
254
0
    }
255
256
0
    bool enable_short_circuit_query_access_column_store() const {
257
0
        return _query_options.__isset.enable_short_circuit_query_access_column_store &&
258
0
               _query_options.enable_short_circuit_query_access_column_store;
259
0
    }
260
261
    // Appends error to the _error_log if there is space
262
    bool log_error(const std::string& error);
263
264
    // Returns true if the error log has not reached _max_errors.
265
0
    bool log_has_space() {
266
0
        std::lock_guard<std::mutex> l(_error_log_lock);
267
0
        return _error_log.size() < _query_options.max_errors;
268
0
    }
269
270
    // Append all _error_log[_unreported_error_idx+] to new_errors and set
271
    // _unreported_error_idx to _errors_log.size()
272
    void get_unreported_errors(std::vector<std::string>* new_errors);
273
274
    [[nodiscard]] MOCK_FUNCTION bool is_cancelled() const;
275
    MOCK_FUNCTION Status cancel_reason() const;
276
0
    void cancel(const Status& reason) {
277
0
        if (_exec_status.update(reason)) {
278
            // Create a error status, so that we could print error stack, and
279
            // we could know which path call cancel.
280
0
            LOG(WARNING) << "Task is cancelled, instance: "
281
0
                         << PrintInstanceStandardInfo(_query_id, _fragment_instance_id)
282
0
                         << ", st = " << reason;
283
0
        } else {
284
0
            LOG(WARNING) << "Task is already cancelled, instance: "
285
0
                         << PrintInstanceStandardInfo(_query_id, _fragment_instance_id)
286
0
                         << ", original cancel msg: " << _exec_status.status()
287
0
                         << ", new cancel msg: " << reason;
288
0
        }
289
0
    }
290
291
0
    void set_backend_id(int64_t backend_id) { _backend_id = backend_id; }
292
0
    int64_t backend_id() const { return _backend_id; }
293
294
77
    void set_be_number(int be_number) { _be_number = be_number; }
295
124
    int be_number(void) const { return _be_number; }
296
297
0
    std::vector<std::string>& output_files() { return _output_files; }
298
299
0
    void set_import_label(const std::string& import_label) { _import_label = import_label; }
300
301
0
    const std::vector<std::string>& export_output_files() const { return _export_output_files; }
302
303
0
    void add_export_output_file(const std::string& file) { _export_output_files.push_back(file); }
304
305
0
    void set_db_name(const std::string& db_name) { _db_name = db_name; }
306
307
0
    const std::string& db_name() { return _db_name; }
308
309
0
    void set_wal_id(int64_t wal_id) { _wal_id = wal_id; }
310
311
0
    int64_t wal_id() const { return _wal_id; }
312
313
0
    void set_content_length(size_t content_length) { _content_length = content_length; }
314
315
0
    size_t content_length() const { return _content_length; }
316
317
0
    const std::string& import_label() { return _import_label; }
318
319
0
    const std::string& load_dir() const { return _load_dir; }
320
321
0
    void set_load_job_id(int64_t job_id) { _load_job_id = job_id; }
322
323
0
    int64_t load_job_id() const { return _load_job_id; }
324
325
    std::string get_error_log_file_path();
326
327
0
    std::string get_first_error_msg() const { return _first_error_msg; }
328
329
    // append error msg and error line to file when loading data.
330
    // is_summary is true, means we are going to write the summary line
331
    // If we need to stop the processing, set stop_processing to true
332
    Status append_error_msg_to_file(std::function<std::string()> line,
333
                                    std::function<std::string()> error_msg);
334
335
0
    int64_t num_bytes_load_total() { return _num_bytes_load_total.load(); }
336
337
0
    int64_t num_finished_range() { return _num_finished_scan_range.load(); }
338
339
0
    int64_t num_rows_load_total() { return _num_rows_load_total.load(); }
340
341
0
    int64_t num_rows_load_filtered() { return _num_rows_load_filtered.load(); }
342
343
0
    int64_t num_rows_load_unselected() { return _num_rows_load_unselected.load(); }
344
345
0
    int64_t num_rows_filtered_in_strict_mode_partial_update() {
346
0
        return _num_rows_filtered_in_strict_mode_partial_update;
347
0
    }
348
349
0
    int64_t num_rows_load_success() {
350
0
        return num_rows_load_total() - num_rows_load_filtered() - num_rows_load_unselected();
351
0
    }
352
353
2
    void update_num_rows_load_total(int64_t num_rows) { _num_rows_load_total.fetch_add(num_rows); }
354
355
0
    void set_num_rows_load_total(int64_t num_rows) { _num_rows_load_total.store(num_rows); }
356
357
2
    void update_num_bytes_load_total(int64_t bytes_load) {
358
2
        _num_bytes_load_total.fetch_add(bytes_load);
359
2
    }
360
361
0
    void update_num_finished_scan_range(int64_t finished_range) {
362
0
        _num_finished_scan_range.fetch_add(finished_range);
363
0
    }
364
365
0
    void update_num_rows_load_filtered(int64_t num_rows) {
366
0
        _num_rows_load_filtered.fetch_add(num_rows);
367
0
    }
368
369
0
    void update_num_rows_load_unselected(int64_t num_rows) {
370
0
        _num_rows_load_unselected.fetch_add(num_rows);
371
0
    }
372
373
0
    void set_num_rows_filtered_in_strict_mode_partial_update(int64_t num_rows) {
374
0
        _num_rows_filtered_in_strict_mode_partial_update = num_rows;
375
0
    }
376
377
5
    void set_per_fragment_instance_idx(int idx) { _per_fragment_instance_idx = idx; }
378
379
15
    int per_fragment_instance_idx() const { return _per_fragment_instance_idx; }
380
381
5
    void set_num_per_fragment_instances(int num_instances) {
382
5
        _num_per_fragment_instances = num_instances;
383
5
    }
384
385
0
    int num_per_fragment_instances() const { return _num_per_fragment_instances; }
386
387
5
    void set_load_stream_per_node(int load_stream_per_node) {
388
5
        _load_stream_per_node = load_stream_per_node;
389
5
    }
390
391
0
    int load_stream_per_node() const { return _load_stream_per_node; }
392
393
5
    void set_total_load_streams(int total_load_streams) {
394
5
        _total_load_streams = total_load_streams;
395
5
    }
396
397
0
    int total_load_streams() const { return _total_load_streams; }
398
399
5
    void set_num_local_sink(int num_local_sink) { _num_local_sink = num_local_sink; }
400
401
0
    int num_local_sink() const { return _num_local_sink; }
402
403
0
    bool disable_stream_preaggregations() const {
404
0
        return _query_options.disable_stream_preaggregations;
405
0
    }
406
407
0
    int32_t runtime_filter_wait_time_ms() const {
408
0
        return _query_options.runtime_filter_wait_time_ms;
409
0
    }
410
411
0
    int32_t runtime_filter_max_in_num() const { return _query_options.runtime_filter_max_in_num; }
412
413
182
    int be_exec_version() const {
414
182
        DCHECK(_query_options.__isset.be_exec_version &&
415
182
               BeExecVersionManager::check_be_exec_version(_query_options.be_exec_version));
416
182
        return _query_options.be_exec_version;
417
182
    }
418
2
    bool plan_local_shuffle() const {
419
        // If local shuffle is enabled and not planned by local shuffle planner, we should plan local shuffle in BE.
420
2
        return _query_options.__isset.enable_local_shuffle && _query_options.enable_local_shuffle &&
421
2
               (!_query_options.__isset.enable_local_shuffle_planner ||
422
2
                !_query_options.enable_local_shuffle_planner);
423
2
    }
424
425
3
    MOCK_FUNCTION bool enable_local_exchange() const {
426
3
        return _query_options.__isset.enable_local_exchange && _query_options.enable_local_exchange;
427
3
    }
428
429
0
    bool trim_tailing_spaces_for_external_table_query() const {
430
0
        return _query_options.trim_tailing_spaces_for_external_table_query;
431
0
    }
432
433
0
    bool return_object_data_as_binary() const {
434
0
        return _query_options.return_object_data_as_binary;
435
0
    }
436
437
1
    bool enable_fuzzy_blockable_task() const {
438
1
        return _query_options.__isset.enable_fuzzy_blockable_task &&
439
1
               _query_options.enable_fuzzy_blockable_task;
440
1
    }
441
442
19
    segment_v2::CompressionTypePB fragement_transmission_compression_type() const {
443
19
        if (_query_options.__isset.fragment_transmission_compression_codec) {
444
0
            if (_query_options.fragment_transmission_compression_codec == "lz4") {
445
0
                return segment_v2::CompressionTypePB::LZ4;
446
0
            } else if (_query_options.fragment_transmission_compression_codec == "snappy") {
447
0
                return segment_v2::CompressionTypePB::SNAPPY;
448
0
            } else {
449
0
                return segment_v2::CompressionTypePB::NO_COMPRESSION;
450
0
            }
451
0
        }
452
19
        return segment_v2::CompressionTypePB::NO_COMPRESSION;
453
19
    }
454
455
0
    bool skip_storage_engine_merge() const {
456
0
        return _query_options.__isset.skip_storage_engine_merge &&
457
0
               _query_options.skip_storage_engine_merge;
458
0
    }
459
460
0
    bool skip_delete_predicate() const {
461
0
        return _query_options.__isset.skip_delete_predicate && _query_options.skip_delete_predicate;
462
0
    }
463
464
15
    bool skip_delete_bitmap() const {
465
15
        return _query_options.__isset.skip_delete_bitmap && _query_options.skip_delete_bitmap;
466
15
    }
467
468
0
    bool skip_missing_version() const {
469
0
        return _query_options.__isset.skip_missing_version && _query_options.skip_missing_version;
470
0
    }
471
472
6
    int64_t data_queue_max_blocks() const {
473
6
        return _query_options.__isset.data_queue_max_blocks ? _query_options.data_queue_max_blocks
474
6
                                                            : 1;
475
6
    }
476
477
    bool enable_page_cache() const;
478
479
0
    bool enable_prefer_cached_rowset() const {
480
0
        return _query_options.__isset.enable_prefer_cached_rowset &&
481
0
               _query_options.enable_prefer_cached_rowset;
482
0
    }
483
484
0
    int64_t query_freshness_tolerance_ms() const {
485
0
        return _query_options.query_freshness_tolerance_ms;
486
0
    }
487
488
0
    bool enable_query_freshness_tolerance() const {
489
0
        return _query_options.__isset.query_freshness_tolerance_ms &&
490
0
               _query_options.query_freshness_tolerance_ms > 0;
491
0
    }
492
493
0
    std::vector<TTabletCommitInfo> tablet_commit_infos() const {
494
0
        std::lock_guard<std::mutex> lock(_tablet_infos_mutex);
495
0
        return _tablet_commit_infos;
496
0
    }
497
498
0
    void add_tablet_commit_infos(std::vector<TTabletCommitInfo>& commit_infos) {
499
0
        std::lock_guard<std::mutex> lock(_tablet_infos_mutex);
500
0
        _tablet_commit_infos.insert(_tablet_commit_infos.end(),
501
0
                                    std::make_move_iterator(commit_infos.begin()),
502
0
                                    std::make_move_iterator(commit_infos.end()));
503
0
    }
504
505
0
    std::vector<TErrorTabletInfo> error_tablet_infos() const {
506
0
        std::lock_guard<std::mutex> lock(_tablet_infos_mutex);
507
0
        return _error_tablet_infos;
508
0
    }
509
510
0
    void add_error_tablet_infos(std::vector<TErrorTabletInfo>& tablet_infos) {
511
0
        std::lock_guard<std::mutex> lock(_tablet_infos_mutex);
512
0
        _error_tablet_infos.insert(_error_tablet_infos.end(),
513
0
                                   std::make_move_iterator(tablet_infos.begin()),
514
0
                                   std::make_move_iterator(tablet_infos.end()));
515
0
    }
516
517
0
    std::vector<THivePartitionUpdate> hive_partition_updates() const {
518
0
        std::lock_guard<std::mutex> lock(_hive_partition_updates_mutex);
519
0
        return _hive_partition_updates;
520
0
    }
521
522
0
    void add_hive_partition_updates(const THivePartitionUpdate& hive_partition_update) {
523
0
        std::lock_guard<std::mutex> lock(_hive_partition_updates_mutex);
524
0
        _hive_partition_updates.emplace_back(hive_partition_update);
525
0
    }
526
527
0
    std::vector<TIcebergCommitData> iceberg_commit_datas() const {
528
0
        std::lock_guard<std::mutex> lock(_iceberg_commit_datas_mutex);
529
0
        return _iceberg_commit_datas;
530
0
    }
531
532
0
    void add_iceberg_commit_datas(const TIcebergCommitData& iceberg_commit_data) {
533
0
        std::lock_guard<std::mutex> lock(_iceberg_commit_datas_mutex);
534
0
        _iceberg_commit_datas.emplace_back(iceberg_commit_data);
535
0
    }
536
537
0
    std::vector<TMCCommitData> mc_commit_datas() const {
538
0
        std::lock_guard<std::mutex> lock(_mc_commit_datas_mutex);
539
0
        return _mc_commit_datas;
540
0
    }
541
542
0
    void add_mc_commit_datas(const TMCCommitData& mc_commit_data) {
543
0
        std::lock_guard<std::mutex> lock(_mc_commit_datas_mutex);
544
0
        _mc_commit_datas.emplace_back(mc_commit_data);
545
0
    }
546
547
    // local runtime filter mgr, the runtime filter do not have remote target or
548
    // not need local merge should regist here. the instance exec finish, the local
549
    // runtime filter mgr can release the memory of local runtime filter
550
20.7k
    RuntimeFilterMgr* local_runtime_filter_mgr() { return _runtime_filter_mgr; }
551
552
    RuntimeFilterMgr* global_runtime_filter_mgr();
553
554
197
    void set_runtime_filter_mgr(RuntimeFilterMgr* runtime_filter_mgr) {
555
197
        _runtime_filter_mgr = runtime_filter_mgr;
556
197
    }
557
558
205k
    QueryContext* get_query_ctx() const { return _query_ctx; }
559
560
    [[nodiscard]] bool low_memory_mode() const;
561
562
    std::weak_ptr<QueryContext> get_query_ctx_weak();
563
    MOCK_FUNCTION WorkloadGroupPtr workload_group();
564
565
0
    void set_query_mem_tracker(const std::shared_ptr<MemTrackerLimiter>& tracker) {
566
0
        _query_mem_tracker = tracker;
567
0
    }
568
569
4.14k
    void set_query_options(const TQueryOptions& query_options) { _query_options = query_options; }
570
571
4
    bool enable_profile() const {
572
4
        return _query_options.__isset.enable_profile && _query_options.enable_profile;
573
4
    }
574
575
0
    int cte_max_recursion_depth() const {
576
0
        return _query_options.__isset.cte_max_recursion_depth
577
0
                       ? _query_options.cte_max_recursion_depth
578
0
                       : 0;
579
0
    }
580
581
0
    bool enable_streaming_agg_hash_join_force_passthrough() const {
582
0
        return _query_options.__isset.enable_streaming_agg_hash_join_force_passthrough &&
583
0
               _query_options.enable_streaming_agg_hash_join_force_passthrough;
584
0
    }
585
586
0
    bool enable_local_exchange_before_agg() const {
587
0
        return _query_options.__isset.enable_local_exchange_before_agg &&
588
0
               _query_options.enable_local_exchange_before_agg;
589
0
    }
590
591
0
    bool enable_distinct_streaming_agg_force_passthrough() const {
592
0
        return _query_options.__isset.enable_distinct_streaming_agg_force_passthrough &&
593
0
               _query_options.enable_distinct_streaming_agg_force_passthrough;
594
0
    }
595
596
1
    bool enable_broadcast_join_force_passthrough() const {
597
1
        return _query_options.__isset.enable_broadcast_join_force_passthrough &&
598
1
               _query_options.enable_broadcast_join_force_passthrough;
599
1
    }
600
601
0
    int rpc_verbose_profile_max_instance_count() const {
602
0
        return _query_options.__isset.rpc_verbose_profile_max_instance_count
603
0
                       ? _query_options.rpc_verbose_profile_max_instance_count
604
0
                       : 0;
605
0
    }
606
607
0
    MOCK_FUNCTION bool enable_share_hash_table_for_broadcast_join() const {
608
0
        return _query_options.__isset.enable_share_hash_table_for_broadcast_join &&
609
0
               _query_options.enable_share_hash_table_for_broadcast_join;
610
0
    }
611
612
0
    bool enable_parallel_scan() const {
613
0
        return _query_options.__isset.enable_parallel_scan && _query_options.enable_parallel_scan;
614
0
    }
615
616
20
    bool enable_aggregate_function_null_v2() const {
617
20
        return _query_options.__isset.enable_aggregate_function_null_v2 &&
618
20
               _query_options.enable_aggregate_function_null_v2;
619
20
    }
620
621
0
    bool is_read_csv_empty_line_as_null() const {
622
0
        return _query_options.__isset.read_csv_empty_line_as_null &&
623
0
               _query_options.read_csv_empty_line_as_null;
624
0
    }
625
626
0
    int parallel_scan_max_scanners_count() const {
627
0
        return _query_options.__isset.parallel_scan_max_scanners_count
628
0
                       ? _query_options.parallel_scan_max_scanners_count
629
0
                       : 0;
630
0
    }
631
632
431
    int partition_topn_max_partitions() const {
633
431
        return _query_options.__isset.partition_topn_max_partitions
634
431
                       ? _query_options.partition_topn_max_partitions
635
431
                       : 1024;
636
431
    }
637
638
0
    int partition_topn_per_partition_rows() const {
639
0
        return _query_options.__isset.partition_topn_pre_partition_rows
640
0
                       ? _query_options.partition_topn_pre_partition_rows
641
0
                       : 1000;
642
0
    }
643
644
0
    int64_t parallel_scan_min_rows_per_scanner() const {
645
0
        return _query_options.__isset.parallel_scan_min_rows_per_scanner
646
0
                       ? _query_options.parallel_scan_min_rows_per_scanner
647
0
                       : 0;
648
0
    }
649
650
0
    void set_be_exec_version(int32_t version) noexcept { _query_options.be_exec_version = version; }
651
652
    using LocalState = doris::PipelineXLocalStateBase;
653
    using SinkLocalState = doris::PipelineXSinkLocalStateBase;
654
    // get result can return an error message, and we will only call it during the prepare.
655
    void emplace_local_state(int id, std::unique_ptr<LocalState> state);
656
657
    LocalState* get_local_state(int id);
658
    Result<LocalState*> get_local_state_result(int id);
659
660
    void emplace_sink_local_state(int id, std::unique_ptr<SinkLocalState> state);
661
662
    SinkLocalState* get_sink_local_state();
663
664
    Result<SinkLocalState*> get_sink_local_state_result();
665
666
    void resize_op_id_to_local_state(int operator_size);
667
668
    std::vector<std::shared_ptr<RuntimeProfile>> pipeline_id_to_profile();
669
670
    std::vector<std::shared_ptr<RuntimeProfile>> build_pipeline_profile(std::size_t pipeline_size);
671
672
72.8k
    void set_task_execution_context(std::shared_ptr<TaskExecutionContext> context) {
673
72.8k
        _task_execution_context_inited = true;
674
72.8k
        _task_execution_context = context;
675
72.8k
    }
676
677
37
    bool task_execution_context_inited() const { return _task_execution_context_inited; }
678
679
125
    std::weak_ptr<TaskExecutionContext> get_task_execution_context() {
680
125
        CHECK(_task_execution_context_inited)
681
0
                << "_task_execution_context_inited == false, the ctx is not inited";
682
125
        return _task_execution_context;
683
125
    }
684
685
    Status register_producer_runtime_filter(
686
            const doris::TRuntimeFilterDesc& desc,
687
            std::shared_ptr<RuntimeFilterProducer>* producer_filter);
688
689
    Status register_consumer_runtime_filter(
690
            const doris::TRuntimeFilterDesc& desc, bool need_local_merge, int node_id,
691
            std::shared_ptr<RuntimeFilterConsumer>* consumer_filter);
692
693
    bool is_nereids() const;
694
695
4.82k
    bool enable_spill() const {
696
4.82k
        return (_query_options.__isset.enable_force_spill && _query_options.enable_force_spill) ||
697
4.82k
               (_query_options.__isset.enable_spill && _query_options.enable_spill);
698
4.82k
    }
699
700
0
    bool enable_force_spill() const {
701
0
        return _query_options.__isset.enable_force_spill && _query_options.enable_force_spill;
702
0
    }
703
704
70
    int64_t spill_min_revocable_mem() const {
705
70
        if (_query_options.__isset.min_revocable_mem) {
706
70
            return std::max(_query_options.min_revocable_mem, (int64_t)1 << 20);
707
70
        }
708
0
        return 32 << 20;
709
70
    }
710
711
39
    int spill_aggregation_partition_count() const {
712
39
        if (_query_options.__isset.spill_aggregation_partition_count) {
713
39
            return std::min(std::max(2, _query_options.spill_aggregation_partition_count), 32);
714
39
        }
715
0
        return 8;
716
39
    }
717
718
9
    int spill_hash_join_partition_count() const {
719
9
        if (_query_options.__isset.spill_hash_join_partition_count) {
720
9
            return std::min(std::max(2, _query_options.spill_hash_join_partition_count), 32);
721
9
        }
722
0
        return 8;
723
9
    }
724
725
23
    int spill_repartition_max_depth() const {
726
23
        if (_query_options.__isset.spill_repartition_max_depth) {
727
            // Clamp to a reasonable range: [1, 128]
728
23
            return std::max(1, std::min(_query_options.spill_repartition_max_depth, 128));
729
23
        }
730
0
        return 8;
731
23
    }
732
733
70
    int64_t spill_buffer_size_bytes() const {
734
        // clamp to [1MB, 256MB]
735
70
        constexpr int64_t kMin = 1LL * 1024 * 1024;
736
70
        constexpr int64_t kMax = 256LL * 1024 * 1024;
737
70
        if (_query_options.__isset.spill_buffer_size_bytes) {
738
70
            int64_t v = _query_options.spill_buffer_size_bytes;
739
70
            if (v < kMin) return kMin;
740
70
            if (v > kMax) return kMax;
741
70
            return v;
742
70
        }
743
0
        return 8LL * 1024 * 1024;
744
70
    }
745
746
    // Per-sink memory limits: after spill is triggered, the sink proactively
747
    // spills when its revocable memory exceeds this threshold.
748
    // Clamped to [1MB, 4GB], default 64MB.
749
2
    int64_t spill_join_build_sink_mem_limit_bytes() const {
750
2
        constexpr int64_t kMin = 1LL * 1024 * 1024;
751
2
        constexpr int64_t kMax = 4LL * 1024 * 1024 * 1024;
752
2
        constexpr int64_t kDefault = 64LL * 1024 * 1024;
753
2
        if (_query_options.__isset.spill_join_build_sink_mem_limit_bytes) {
754
2
            int64_t v = _query_options.spill_join_build_sink_mem_limit_bytes;
755
2
            return std::min(std::max(v, kMin), kMax);
756
2
        }
757
0
        return kDefault;
758
2
    }
759
760
16
    int64_t spill_aggregation_sink_mem_limit_bytes() const {
761
16
        constexpr int64_t kMin = 1LL * 1024 * 1024;
762
16
        constexpr int64_t kMax = 4LL * 1024 * 1024 * 1024;
763
16
        constexpr int64_t kDefault = 64LL * 1024 * 1024;
764
16
        if (_query_options.__isset.spill_aggregation_sink_mem_limit_bytes) {
765
16
            int64_t v = _query_options.spill_aggregation_sink_mem_limit_bytes;
766
16
            return std::min(std::max(v, kMin), kMax);
767
16
        }
768
0
        return kDefault;
769
16
    }
770
771
8
    int64_t spill_sort_sink_mem_limit_bytes() const {
772
8
        constexpr int64_t kMin = 1LL * 1024 * 1024;
773
8
        constexpr int64_t kMax = 4LL * 1024 * 1024 * 1024;
774
8
        constexpr int64_t kDefault = 64LL * 1024 * 1024;
775
8
        if (_query_options.__isset.spill_sort_sink_mem_limit_bytes) {
776
8
            int64_t v = _query_options.spill_sort_sink_mem_limit_bytes;
777
8
            return std::min(std::max(v, kMin), kMax);
778
8
        }
779
0
        return kDefault;
780
8
    }
781
782
10
    int64_t spill_sort_merge_mem_limit_bytes() const {
783
10
        constexpr int64_t kMin = 1LL * 1024 * 1024;
784
10
        constexpr int64_t kMax = 4LL * 1024 * 1024 * 1024;
785
10
        constexpr int64_t kDefault = 64LL * 1024 * 1024;
786
10
        if (_query_options.__isset.spill_sort_merge_mem_limit_bytes) {
787
10
            int64_t v = _query_options.spill_sort_merge_mem_limit_bytes;
788
10
            return std::min(std::max(v, kMin), kMax);
789
10
        }
790
0
        return kDefault;
791
10
    }
792
793
0
    int64_t low_memory_mode_buffer_limit() const {
794
0
        if (_query_options.__isset.low_memory_mode_buffer_limit) {
795
0
            return std::max(_query_options.low_memory_mode_buffer_limit, (int64_t)1);
796
0
        }
797
0
        return 32L * 1024 * 1024;
798
0
    }
799
800
0
    int spill_revocable_memory_high_watermark_percent() const {
801
0
        if (_query_options.__isset.revocable_memory_high_watermark_percent) {
802
0
            return _query_options.revocable_memory_high_watermark_percent;
803
0
        }
804
0
        return -1;
805
0
    }
806
807
0
    MOCK_FUNCTION bool enable_shared_exchange_sink_buffer() const {
808
0
        return _query_options.__isset.enable_shared_exchange_sink_buffer &&
809
0
               _query_options.enable_shared_exchange_sink_buffer;
810
0
    }
811
812
3.22M
    size_t minimum_operator_memory_required_bytes() const {
813
3.22M
        if (_query_options.__isset.minimum_operator_memory_required_kb) {
814
3.22M
            return _query_options.minimum_operator_memory_required_kb * 1024;
815
3.22M
        } else {
816
            // refer other database
817
0
            return 4 * 1024 * 1024;
818
0
        }
819
3.22M
    }
820
821
0
    MOCK_FUNCTION bool enable_use_hybrid_sort() const {
822
0
        return _query_options.__isset.enable_use_hybrid_sort &&
823
0
               _query_options.enable_use_hybrid_sort;
824
0
    }
825
826
72.1k
    void set_max_operator_id(int max_operator_id) { _max_operator_id = max_operator_id; }
827
828
21
    int max_operator_id() const { return _max_operator_id; }
829
830
25
    void set_task_id(int id) { _task_id = id; }
831
832
228
    int task_id() const { return _task_id; }
833
834
5
    void set_task_num(int task_num) { _task_num = task_num; }
835
836
1
    int task_num() const { return _task_num; }
837
838
0
    int profile_level() const { return _profile_level; }
839
840
0
    std::shared_ptr<IdFileMap>& get_id_file_map() { return _id_file_map; }
841
842
    void set_id_file_map();
843
18
    VectorSearchUserParams get_vector_search_params() const {
844
18
        VectorSearchUserParams params;
845
18
        params.hnsw_ef_search = _query_options.hnsw_ef_search;
846
18
        params.hnsw_check_relative_distance = _query_options.hnsw_check_relative_distance;
847
18
        params.hnsw_bounded_queue = _query_options.hnsw_bounded_queue;
848
18
        params.ivf_nprobe = _query_options.ivf_nprobe;
849
18
        return params;
850
18
    }
851
852
123
    bool runtime_filter_wait_infinitely() const {
853
123
        return _query_options.__isset.runtime_filter_wait_infinitely &&
854
123
               _query_options.runtime_filter_wait_infinitely;
855
123
    }
856
857
    const std::set<int>& get_deregister_runtime_filter() const;
858
859
    void merge_register_runtime_filter(const std::set<int>& runtime_filter_ids);
860
861
private:
862
    Status create_error_log_file();
863
864
    static const int DEFAULT_BATCH_SIZE = 4062;
865
866
    std::shared_ptr<MemTrackerLimiter> _query_mem_tracker = nullptr;
867
868
    // Could not find a better way to record if the weak ptr is inited, use a bool to record
869
    // it. In some unit test cases, the runtime state's task ctx is not inited, then the test
870
    // hang, it is very hard to debug.
871
    bool _task_execution_context_inited = false;
872
    // Hold execution context for other threads
873
    std::weak_ptr<TaskExecutionContext> _task_execution_context;
874
875
    // put runtime state before _obj_pool, so that it will be deconstructed after
876
    // _obj_pool. Because some of object in _obj_pool will use profile when deconstructing.
877
    RuntimeProfile _profile;
878
    RuntimeProfile _load_channel_profile;
879
    // Why 2?
880
    // During cluster upgrade, fe will not pass profile_level to be, so we need to set it to 2
881
    // to make sure user can see all profile counters like before.
882
    int _profile_level = 2;
883
884
    const DescriptorTbl* _desc_tbl = nullptr;
885
    std::shared_ptr<ObjectPool> _obj_pool;
886
887
    // owned by PipelineFragmentContext
888
    RuntimeFilterMgr* _runtime_filter_mgr = nullptr;
889
890
    // Lock protecting _error_log and _unreported_error_idx
891
    std::mutex _error_log_lock;
892
893
    // Logs error messages.
894
    std::vector<std::string> _error_log;
895
896
    // _error_log[_unreported_error_idx+] has been not reported to the coordinator.
897
    int _unreported_error_idx;
898
899
    // Username of user that is executing the query to which this RuntimeState belongs.
900
    std::string _user;
901
902
    //Query-global timestamp_ms
903
    int64_t _timestamp_ms;
904
    int32_t _nano_seconds;
905
    std::string _timezone;
906
    cctz::time_zone _timezone_obj;
907
    std::string _lc_time_names;
908
909
    TUniqueId _query_id;
910
    // fragment id for each TPipelineFragmentParams
911
    int32_t _fragment_id;
912
    TUniqueId _fragment_instance_id;
913
    TQueryOptions _query_options;
914
    ExecEnv* _exec_env = nullptr;
915
916
    AtomicStatus _exec_status;
917
918
    int _per_fragment_instance_idx;
919
    int _num_per_fragment_instances = 0;
920
    int _load_stream_per_node = 0;
921
    int _total_load_streams = 0;
922
    int _num_local_sink = 0;
923
924
    // The backend id on which this fragment instance runs
925
    int64_t _backend_id = -1;
926
927
    // used as send id
928
    int _be_number;
929
930
    // put here to collect files??
931
    std::vector<std::string> _output_files;
932
    std::atomic<int64_t> _num_rows_load_total;      // total rows read from source
933
    std::atomic<int64_t> _num_rows_load_filtered;   // unqualified rows
934
    std::atomic<int64_t> _num_rows_load_unselected; // rows filtered by predicates
935
    std::atomic<int64_t> _num_rows_filtered_in_strict_mode_partial_update;
936
    std::atomic<int64_t> _num_print_error_rows;
937
938
    std::atomic<int64_t> _num_bytes_load_total; // total bytes read from source
939
    std::atomic<int64_t> _num_finished_scan_range;
940
941
    std::vector<std::string> _export_output_files;
942
    std::string _import_label;
943
    std::string _db_name;
944
    std::string _load_dir;
945
    int64_t _load_job_id;
946
    int64_t _wal_id = -1;
947
    size_t _content_length = 0;
948
949
    // mini load
950
    std::string _error_log_file_path;
951
    std::unique_ptr<std::ofstream> _error_log_file; // error file path, absolute path
952
    std::string _first_error_msg = "";
953
    mutable std::mutex _tablet_infos_mutex;
954
    std::vector<TTabletCommitInfo> _tablet_commit_infos;
955
    std::vector<TErrorTabletInfo> _error_tablet_infos;
956
    int _max_operator_id = 0;
957
    int _task_id = -1;
958
    int _task_num = 0;
959
960
    mutable std::mutex _hive_partition_updates_mutex;
961
    std::vector<THivePartitionUpdate> _hive_partition_updates;
962
963
    mutable std::mutex _iceberg_commit_datas_mutex;
964
    std::vector<TIcebergCommitData> _iceberg_commit_datas;
965
966
    mutable std::mutex _mc_commit_datas_mutex;
967
    std::vector<TMCCommitData> _mc_commit_datas;
968
969
    std::vector<std::unique_ptr<doris::PipelineXLocalStateBase>> _op_id_to_local_state;
970
971
    std::unique_ptr<doris::PipelineXSinkLocalStateBase> _sink_local_state;
972
973
    QueryContext* _query_ctx = nullptr;
974
975
    // true if max_filter_ratio is 0
976
    bool _load_zero_tolerance = false;
977
978
    // only to lock _pipeline_id_to_profile
979
    std::shared_mutex _pipeline_profile_lock;
980
    std::vector<std::shared_ptr<RuntimeProfile>> _pipeline_id_to_profile;
981
982
    // save error log to s3
983
    std::shared_ptr<io::S3FileSystem> _s3_error_fs;
984
    // error file path on s3, ${bucket}/${prefix}/error_log/${label}_${fragment_instance_id}
985
    std::string _s3_error_log_file_path;
986
    std::mutex _s3_error_log_file_lock;
987
988
    // used for encoding the global lazy materialize
989
    std::shared_ptr<IdFileMap> _id_file_map = nullptr;
990
991
    std::set<int> _registered_runtime_filter_ids;
992
};
993
994
#define RETURN_IF_CANCELLED(state)               \
995
1.60k
    do {                                         \
996
1.60k
        if (UNLIKELY((state)->is_cancelled())) { \
997
0
            return (state)->cancel_reason();     \
998
0
        }                                        \
999
1.60k
    } while (false)
1000
1001
} // namespace doris