Coverage Report

Created: 2026-06-09 12:08

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