Coverage Report

Created: 2026-06-09 21:04

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