Coverage Report

Created: 2026-08-02 02:36

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