Coverage Report

Created: 2026-10-27 17:29

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