Coverage Report

Created: 2026-05-09 09:50

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