Coverage Report

Created: 2026-08-14 13:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/runtime_state.cpp
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.cpp
19
// and modified by Doris
20
21
#include "runtime/runtime_state.h"
22
23
#include <fmt/format.h>
24
#include <gen_cpp/PaloInternalService_types.h>
25
#include <gen_cpp/Types_types.h>
26
#include <glog/logging.h>
27
28
#include <fstream>
29
#include <memory>
30
#include <string>
31
32
#include "cloud/cloud_storage_engine.h"
33
#include "cloud/config.h"
34
#include "common/config.h"
35
#include "common/logging.h"
36
#include "common/object_pool.h"
37
#include "common/status.h"
38
#include "core/value/vdatetime_value.h"
39
#include "exec/operator/operator.h"
40
#include "exec/pipeline/pipeline_fragment_context.h"
41
#include "exec/pipeline/pipeline_task.h"
42
#include "exec/runtime_filter/runtime_filter_consumer.h"
43
#include "exec/runtime_filter/runtime_filter_mgr.h"
44
#include "exec/runtime_filter/runtime_filter_producer.h"
45
#include "exprs/function/cast/cast_to_date_or_datetime_impl.hpp"
46
#include "io/fs/s3_file_system.h"
47
#include "load/load_path_mgr.h"
48
#include "runtime/exec_env.h"
49
#include "runtime/fragment_mgr.h"
50
#include "runtime/memory/mem_tracker_limiter.h"
51
#include "runtime/query_context.h"
52
#include "runtime/thread_context.h"
53
#include "storage/id_manager.h"
54
#include "storage/storage_engine.h"
55
#include "util/thrift_util.h"
56
#include "util/timezone_utils.h"
57
#include "util/uid_util.h"
58
59
namespace doris {
60
using namespace ErrorCode;
61
62
4.11k
Status RuntimeState::add_iceberg_commit_datas(TIcebergCommitData iceberg_commit_data) {
63
4.11k
    ThriftSerializer serializer(false, 256);
64
4.11k
    uint32_t serialized_size = 0;
65
4.11k
    uint8_t* buffer = nullptr;
66
4.11k
    RETURN_IF_ERROR(serializer.serialize(&iceberg_commit_data, &serialized_size, &buffer));
67
68
    // This is an early per-vector guard only; the assembled RPC is measured again before send.
69
4.11k
    constexpr size_t report_envelope_headroom = 1024 * 1024;
70
4.11k
    const size_t thrift_limit = coordinator_thrift_message_limit();
71
4.11k
    const size_t commit_data_limit =
72
18.4E
            thrift_limit > report_envelope_headroom ? thrift_limit - report_envelope_headroom : 0;
73
4.11k
    std::lock_guard<std::mutex> budget_lock(_external_file_report_state->mutex);
74
    // Parallel task states share this budget because FE receives their vectors in one fragment report.
75
4.11k
    if (_external_file_report_state->iceberg_serialized_bytes + serialized_size + sizeof(uint32_t) >
76
4.11k
        commit_data_limit) {
77
3
        return Status::InternalError(
78
3
                "Iceberg commit metadata exceeds the Thrift report limit; reduce output file "
79
3
                "count");
80
3
    }
81
4.11k
    std::lock_guard<std::mutex> data_lock(_iceberg_commit_datas_mutex);
82
4.11k
    _external_file_report_state->iceberg_serialized_bytes += serialized_size + sizeof(uint32_t);
83
4.11k
    _iceberg_commit_datas.emplace_back(std::move(iceberg_commit_data));
84
4.11k
    return Status::OK();
85
4.11k
}
86
87
56.4k
size_t RuntimeState::coordinator_thrift_message_limit() const {
88
56.4k
    int32_t effective_thrift_limit = std::max(config::thrift_max_message_size, 0);
89
56.4k
    if (_query_options.__isset.coordinator_thrift_max_message_size &&
90
56.4k
        _query_options.coordinator_thrift_max_message_size > 0) {
91
        // An older FE omits this field; otherwise the receiver's smaller limit is authoritative.
92
56.2k
        effective_thrift_limit = std::min(effective_thrift_limit,
93
56.2k
                                          _query_options.coordinator_thrift_max_message_size);
94
56.2k
    }
95
56.4k
    return static_cast<size_t>(effective_thrift_limit);
96
56.4k
}
97
98
void RuntimeState::append_external_file_commit_data(TReportExecStatusParams* params,
99
226k
                                                    bool final_report) const {
100
226k
    if (!final_report) {
101
        // Ownership-bearing commit vectors must only appear in the final report that transfers them.
102
25.4k
        return;
103
25.4k
    }
104
201k
    if (auto updates = hive_partition_updates(); !updates.empty()) {
105
2.14k
        params->__isset.hive_partition_updates = true;
106
2.14k
        params->hive_partition_updates.insert(params->hive_partition_updates.end(), updates.begin(),
107
2.14k
                                              updates.end());
108
2.14k
    }
109
201k
    append_iceberg_commit_datas(&params->iceberg_commit_datas);
110
201k
    if (!params->iceberg_commit_datas.empty()) {
111
5.16k
        params->__isset.iceberg_commit_datas = true;
112
5.16k
    }
113
201k
    if (auto commit_datas = mc_commit_datas(); !commit_datas.empty()) {
114
1
        params->__isset.mc_commit_datas = true;
115
1
        params->mc_commit_datas.insert(params->mc_commit_datas.end(), commit_datas.begin(),
116
1
                                       commit_datas.end());
117
1
    }
118
201k
}
119
120
4.10k
void RuntimeState::add_rejected_external_file_report_cleanup(std::function<void()> cleanup) {
121
4.10k
    std::lock_guard lock(_external_file_report_state->mutex);
122
4.10k
    _external_file_report_state->rejected_report_cleanups.emplace_back(std::move(cleanup));
123
4.10k
}
124
125
47.0k
void RuntimeState::finalize_external_file_report_cleanup(ExternalFileReportOutcome outcome) {
126
47.0k
    std::vector<std::function<void()>> cleanups;
127
47.0k
    {
128
47.0k
        std::lock_guard lock(_external_file_report_state->mutex);
129
47.0k
        if (outcome == ExternalFileReportOutcome::ACKNOWLEDGED) {
130
45.3k
            _external_file_report_state->rejected_report_cleanups.clear();
131
45.3k
            return;
132
45.3k
        }
133
1.68k
        if (outcome == ExternalFileReportOutcome::AMBIGUOUS) {
134
            // Once an ACK can have been lost, a later rejection cannot prove FE never accepted the files.
135
2
            _external_file_report_state->ownership_may_have_transferred = true;
136
2
            return;
137
2
        }
138
1.68k
        if (_external_file_report_state->ownership_may_have_transferred) {
139
2
            return;
140
2
        }
141
1.68k
        cleanups.swap(_external_file_report_state->rejected_report_cleanups);
142
1.68k
    }
143
1
    for (auto& cleanup : cleanups) {
144
1
        cleanup();
145
1
    }
146
1.68k
}
147
148
RuntimeState::RuntimeState(const TPlanFragmentExecParams& fragment_exec_params,
149
                           const TQueryOptions& query_options, const TQueryGlobals& query_globals,
150
                           ExecEnv* exec_env, QueryContext* ctx,
151
                           const std::shared_ptr<MemTrackerLimiter>& query_mem_tracker)
152
575
        : _profile("Fragment " + print_id(fragment_exec_params.fragment_instance_id)),
153
575
          _load_channel_profile("<unnamed>"),
154
575
          _obj_pool(new ObjectPool()),
155
575
          _unreported_error_idx(0),
156
575
          _query_id(fragment_exec_params.query_id),
157
575
          _per_fragment_instance_idx(0),
158
575
          _num_rows_load_total(0),
159
575
          _num_rows_load_filtered(0),
160
575
          _num_rows_load_unselected(0),
161
575
          _num_print_error_rows(0),
162
575
          _num_bytes_load_total(0),
163
575
          _num_finished_scan_range(0),
164
575
          _query_ctx(ctx) {
165
575
    Status status =
166
575
            init(fragment_exec_params.fragment_instance_id, query_options, query_globals, exec_env);
167
575
    DCHECK(status.ok());
168
575
    _query_mem_tracker = query_mem_tracker;
169
575
    DCHECK(_query_mem_tracker != nullptr);
170
575
}
171
172
RuntimeState::RuntimeState(const TUniqueId& instance_id, const TUniqueId& query_id,
173
                           int32_t fragment_id, const TQueryOptions& query_options,
174
                           const TQueryGlobals& query_globals, ExecEnv* exec_env, QueryContext* ctx)
175
2.07M
        : _profile("Fragment " + print_id(instance_id)),
176
2.07M
          _load_channel_profile("<unnamed>"),
177
2.07M
          _obj_pool(new ObjectPool()),
178
2.07M
          _unreported_error_idx(0),
179
2.07M
          _query_id(query_id),
180
2.07M
          _fragment_id(fragment_id),
181
2.07M
          _per_fragment_instance_idx(0),
182
2.07M
          _num_rows_load_total(0),
183
2.07M
          _num_rows_load_filtered(0),
184
2.07M
          _num_rows_load_unselected(0),
185
2.07M
          _num_rows_filtered_in_strict_mode_partial_update(0),
186
2.07M
          _num_print_error_rows(0),
187
2.07M
          _num_bytes_load_total(0),
188
2.07M
          _num_finished_scan_range(0),
189
2.07M
          _query_ctx(ctx) {
190
2.07M
    [[maybe_unused]] auto status = init(instance_id, query_options, query_globals, exec_env);
191
2.07M
    DCHECK(status.ok());
192
2.07M
    _query_mem_tracker = ctx->query_mem_tracker();
193
2.07M
}
194
195
RuntimeState::RuntimeState(const TUniqueId& query_id, int32_t fragment_id,
196
                           const TQueryOptions& query_options, const TQueryGlobals& query_globals,
197
                           ExecEnv* exec_env, QueryContext* ctx)
198
470k
        : _profile(fmt::format("PipelineX(fragment_id={})", fragment_id)),
199
470k
          _load_channel_profile("<unnamed>"),
200
470k
          _obj_pool(new ObjectPool()),
201
470k
          _unreported_error_idx(0),
202
470k
          _query_id(query_id),
203
470k
          _fragment_id(fragment_id),
204
470k
          _per_fragment_instance_idx(0),
205
470k
          _num_rows_load_total(0),
206
470k
          _num_rows_load_filtered(0),
207
470k
          _num_rows_load_unselected(0),
208
470k
          _num_rows_filtered_in_strict_mode_partial_update(0),
209
470k
          _num_print_error_rows(0),
210
470k
          _num_bytes_load_total(0),
211
470k
          _num_finished_scan_range(0),
212
470k
          _query_ctx(ctx) {
213
    // TODO: do we really need instance id?
214
470k
    Status status = init(TUniqueId(), query_options, query_globals, exec_env);
215
470k
    DCHECK(status.ok());
216
470k
    _query_mem_tracker = ctx->query_mem_tracker();
217
470k
}
218
219
RuntimeState::RuntimeState(const TUniqueId& query_id, int32_t fragment_id,
220
                           const TQueryOptions& query_options, const TQueryGlobals& query_globals,
221
                           ExecEnv* exec_env,
222
                           const std::shared_ptr<MemTrackerLimiter>& query_mem_tracker)
223
2.03k
        : _profile(fmt::format("PipelineX(fragment_id={})", fragment_id)),
224
2.03k
          _load_channel_profile("<unnamed>"),
225
2.03k
          _obj_pool(new ObjectPool()),
226
2.03k
          _unreported_error_idx(0),
227
2.03k
          _query_id(query_id),
228
2.03k
          _fragment_id(fragment_id),
229
2.03k
          _per_fragment_instance_idx(0),
230
2.03k
          _num_rows_load_total(0),
231
2.03k
          _num_rows_load_filtered(0),
232
2.03k
          _num_rows_load_unselected(0),
233
2.03k
          _num_rows_filtered_in_strict_mode_partial_update(0),
234
2.03k
          _num_print_error_rows(0),
235
2.03k
          _num_bytes_load_total(0),
236
2.03k
          _num_finished_scan_range(0) {
237
2.03k
    Status status = init(TUniqueId(), query_options, query_globals, exec_env);
238
2.03k
    DCHECK(status.ok());
239
2.03k
    _query_mem_tracker = query_mem_tracker;
240
2.03k
    DCHECK(_query_mem_tracker != nullptr);
241
2.03k
}
242
243
RuntimeState::RuntimeState(const TQueryOptions& query_options, const TQueryGlobals& query_globals)
244
80.9k
        : _profile("<unnamed>"),
245
80.9k
          _load_channel_profile("<unnamed>"),
246
80.9k
          _obj_pool(new ObjectPool()),
247
80.9k
          _unreported_error_idx(0),
248
80.9k
          _per_fragment_instance_idx(0) {
249
80.9k
    Status status = init(TUniqueId(), query_options, query_globals, nullptr);
250
80.9k
    _exec_env = ExecEnv::GetInstance();
251
80.9k
    init_mem_trackers("<unnamed>");
252
80.9k
    DCHECK(status.ok());
253
80.9k
}
254
255
RuntimeState::RuntimeState()
256
137k
        : _profile("<unnamed>"),
257
137k
          _load_channel_profile("<unnamed>"),
258
137k
          _obj_pool(new ObjectPool()),
259
137k
          _unreported_error_idx(0),
260
137k
          _per_fragment_instance_idx(0) {
261
137k
    _query_options.batch_size = DEFAULT_BATCH_SIZE;
262
137k
    _query_options.be_exec_version = BeExecVersionManager::get_newest_version();
263
137k
    _timezone = TimezoneUtils::default_time_zone;
264
137k
    _timestamp_ms = 0;
265
137k
    _nano_seconds = 0;
266
137k
    TimezoneUtils::find_cctz_time_zone(_timezone, _timezone_obj);
267
137k
    _exec_env = ExecEnv::GetInstance();
268
137k
    init_mem_trackers("<unnamed>");
269
137k
}
270
271
2.77M
RuntimeState::~RuntimeState() {
272
2.77M
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_mem_tracker);
273
    // close error log file
274
2.77M
    if (_error_log_file != nullptr && _error_log_file->is_open()) {
275
60
        _error_log_file->close();
276
60
    }
277
2.77M
    _obj_pool->clear();
278
2.77M
}
279
280
25.4k
const std::set<int>& RuntimeState::get_deregister_runtime_filter() const {
281
25.4k
    return _registered_runtime_filter_ids;
282
25.4k
}
283
284
2
void RuntimeState::merge_register_runtime_filter(const std::set<int>& runtime_filter_ids) {
285
2
    _registered_runtime_filter_ids.insert(runtime_filter_ids.begin(), runtime_filter_ids.end());
286
2
}
287
288
Status RuntimeState::init(const TUniqueId& fragment_instance_id, const TQueryOptions& query_options,
289
2.62M
                          const TQueryGlobals& query_globals, ExecEnv* exec_env) {
290
2.62M
    _fragment_instance_id = fragment_instance_id;
291
2.62M
    _query_options = query_options;
292
2.62M
    _lc_time_names = query_globals.lc_time_names;
293
2.62M
    if (query_globals.__isset.time_zone && query_globals.__isset.nano_seconds) {
294
2.60M
        _timezone = query_globals.time_zone;
295
2.60M
        _timestamp_ms = query_globals.timestamp_ms;
296
2.60M
        _nano_seconds = query_globals.nano_seconds;
297
2.60M
    } else if (query_globals.__isset.time_zone) {
298
1.04k
        _timezone = query_globals.time_zone;
299
1.04k
        _timestamp_ms = query_globals.timestamp_ms;
300
1.04k
        _nano_seconds = 0;
301
16.3k
    } else if (!query_globals.now_string.empty()) {
302
0
        _timezone = TimezoneUtils::default_time_zone;
303
0
        VecDateTimeValue dt;
304
0
        CastParameters params;
305
0
        DORIS_CHECK((CastToDateOrDatetime::from_string_strict_mode<DatelikeParseMode::STRICT,
306
0
                                                                   DatelikeTargetType::DATE_TIME>(
307
0
                {query_globals.now_string.c_str(), query_globals.now_string.size()}, dt, nullptr,
308
0
                params)));
309
0
        int64_t timestamp;
310
0
        dt.unix_timestamp(&timestamp, _timezone);
311
0
        _timestamp_ms = timestamp * 1000;
312
0
        _nano_seconds = 0;
313
16.3k
    } else {
314
        //Unit test may set into here
315
16.3k
        _timezone = TimezoneUtils::default_time_zone;
316
16.3k
        _timestamp_ms = 0;
317
16.3k
        _nano_seconds = 0;
318
16.3k
    }
319
2.62M
    TimezoneUtils::find_cctz_time_zone(_timezone, _timezone_obj);
320
321
2.62M
    if (query_globals.__isset.load_zero_tolerance) {
322
2.62M
        _load_zero_tolerance = query_globals.load_zero_tolerance;
323
2.62M
    }
324
325
2.62M
    _exec_env = exec_env;
326
327
2.62M
    if (_query_options.max_errors <= 0) {
328
        // TODO: fix linker error and uncomment this
329
        //_query_options.max_errors = config::max_errors;
330
2.61M
        _query_options.max_errors = 100;
331
2.61M
    }
332
333
2.62M
    if (_query_options.batch_size <= 0) {
334
62.3k
        _query_options.batch_size = DEFAULT_BATCH_SIZE;
335
62.3k
    }
336
337
2.62M
    _db_name = "insert_stmt";
338
2.62M
    _import_label = print_id(fragment_instance_id);
339
340
18.4E
    _profile_level = query_options.__isset.profile_level ? query_options.profile_level : 2;
341
342
2.62M
    return Status::OK();
343
2.62M
}
344
345
2.54k
std::weak_ptr<QueryContext> RuntimeState::get_query_ctx_weak() {
346
2.54k
    return _exec_env->fragment_mgr()->get_query_ctx(_query_ctx->query_id());
347
2.54k
}
348
349
218k
void RuntimeState::init_mem_trackers(const std::string& name, const TUniqueId& id) {
350
218k
    _query_mem_tracker = MemTrackerLimiter::create_shared(
351
218k
            MemTrackerLimiter::Type::OTHER, fmt::format("{}#Id={}", name, print_id(id)));
352
218k
}
353
354
3.33M
std::shared_ptr<MemTrackerLimiter> RuntimeState::query_mem_tracker() const {
355
3.33M
    CHECK(_query_mem_tracker != nullptr);
356
3.33M
    return _query_mem_tracker;
357
3.33M
}
358
359
6.28M
WorkloadGroupPtr RuntimeState::workload_group() {
360
6.28M
    return _query_ctx->workload_group();
361
6.28M
}
362
363
0
bool RuntimeState::log_error(const std::string& error) {
364
0
    std::lock_guard<std::mutex> l(_error_log_lock);
365
366
0
    if (_error_log.size() < _query_options.max_errors) {
367
0
        _error_log.push_back(error);
368
0
        return true;
369
0
    }
370
371
0
    return false;
372
0
}
373
374
52.4k
void RuntimeState::get_unreported_errors(std::vector<std::string>* new_errors) {
375
52.4k
    std::lock_guard<std::mutex> l(_error_log_lock);
376
377
52.4k
    if (_unreported_error_idx < _error_log.size()) {
378
0
        new_errors->assign(_error_log.begin() + _unreported_error_idx, _error_log.end());
379
0
        _unreported_error_idx = (int)_error_log.size();
380
0
    }
381
52.4k
}
382
383
20.9M
bool RuntimeState::is_cancelled() const {
384
    // Maybe we should just return _is_cancelled.load()
385
20.9M
    return !_exec_status.ok() || (_query_ctx && _query_ctx->is_cancelled());
386
20.9M
}
387
388
204
Status RuntimeState::cancel_reason() const {
389
204
    if (!_exec_status.ok()) {
390
13
        return _exec_status.status();
391
13
    }
392
393
191
    if (_query_ctx) {
394
191
        return _query_ctx->exec_status();
395
191
    }
396
397
0
    return Status::Cancelled("Query cancelled");
398
191
}
399
400
const int64_t MAX_ERROR_NUM = 50;
401
402
630
Status RuntimeState::create_error_log_file() {
403
630
    if (config::save_load_error_log_to_s3 && config::is_cloud_mode()) {
404
582
        _s3_error_fs = std::dynamic_pointer_cast<io::S3FileSystem>(
405
582
                ExecEnv::GetInstance()->storage_engine().to_cloud().latest_fs());
406
582
        if (_s3_error_fs) {
407
582
            std::stringstream ss;
408
            // https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_basic_err_packet.html
409
            // shorten the path as much as possible to prevent the length of the presigned URL from
410
            // exceeding the MySQL error packet size limit
411
582
            ss << "error_log/" << std::hex << _fragment_instance_id.lo;
412
582
            _s3_error_log_file_path = ss.str();
413
582
        }
414
582
    }
415
416
630
    static_cast<void>(_exec_env->load_path_mgr()->get_load_error_file_name(
417
630
            _db_name, _import_label, _fragment_instance_id, &_error_log_file_path));
418
630
    std::string error_log_absolute_path =
419
630
            _exec_env->load_path_mgr()->get_load_error_absolute_path(_error_log_file_path);
420
630
    _error_log_file = std::make_unique<std::ofstream>(error_log_absolute_path, std::ifstream::out);
421
630
    if (!_error_log_file->is_open()) {
422
0
        std::stringstream error_msg;
423
0
        error_msg << "Fail to open error file: [" << _error_log_file_path << "].";
424
0
        LOG(WARNING) << error_msg.str();
425
0
        return Status::InternalError(error_msg.str());
426
0
    }
427
630
    LOG(INFO) << "create error log file: " << _error_log_file_path
428
630
              << ", query id: " << print_id(_query_id)
429
630
              << ", fragment instance id: " << print_id(_fragment_instance_id);
430
431
630
    return Status::OK();
432
630
}
433
434
Status RuntimeState::append_error_msg_to_file(std::function<std::string()> line,
435
8.54k
                                              std::function<std::string()> error_msg) {
436
8.54k
    if (query_type() != TQueryType::LOAD) {
437
0
        return Status::OK();
438
0
    }
439
    // If file haven't been opened, open it here
440
8.54k
    if (_error_log_file == nullptr) {
441
630
        Status status = create_error_log_file();
442
630
        if (!status.ok()) {
443
0
            LOG(WARNING) << "Create error file log failed. because: " << status;
444
0
            if (_error_log_file != nullptr) {
445
0
                _error_log_file->close();
446
0
            }
447
0
            return status;
448
0
        }
449
        // record the first error message if the file is just created
450
630
        _first_error_msg = error_msg() + ". Src line: " + line();
451
630
        LOG(INFO) << "The first error message: " << _first_error_msg;
452
630
    }
453
    // If num of printed error row exceeds the limit, don't add error messages to error log file any more
454
8.54k
    if (_num_print_error_rows.fetch_add(1, std::memory_order_relaxed) > MAX_ERROR_NUM) {
455
        // if _load_zero_tolerance, return Error to stop the load process immediately.
456
4.93k
        if (_load_zero_tolerance) {
457
10
            return Status::DataQualityError(
458
10
                    "Encountered unqualified data, stop processing. Please check if the source "
459
10
                    "data matches the schema, and consider disabling strict mode or increasing "
460
10
                    "max_filter_ratio.");
461
10
        }
462
4.92k
        return Status::OK();
463
4.93k
    }
464
465
3.60k
    fmt::memory_buffer out;
466
    // Note: export reason first in case src line too long and be truncated.
467
3.60k
    fmt::format_to(out, "Reason: {}. src line [{}]; ", error_msg(), line());
468
469
3.60k
    size_t error_row_size = out.size();
470
3.60k
    if (error_row_size > 0) {
471
3.60k
        if (error_row_size > config::load_error_log_limit_bytes) {
472
0
            fmt::memory_buffer limit_byte_out;
473
0
            limit_byte_out.append(out.data(), out.data() + config::load_error_log_limit_bytes);
474
0
            (*_error_log_file) << fmt::to_string(limit_byte_out) + "error log is too long"
475
0
                               << std::endl;
476
3.60k
        } else {
477
3.60k
            (*_error_log_file) << fmt::to_string(out) << std::endl;
478
3.60k
        }
479
3.60k
    }
480
481
3.60k
    return Status::OK();
482
8.54k
}
483
484
386k
std::string RuntimeState::get_error_log_file_path() {
485
386k
    DBUG_EXECUTE_IF("RuntimeState::get_error_log_file_path.block", {
486
386k
        if (!_error_log_file_path.empty()) {
487
386k
            std::this_thread::sleep_for(std::chrono::seconds(1));
488
386k
        }
489
386k
    });
490
386k
    std::lock_guard<std::mutex> l(_s3_error_log_file_lock);
491
386k
    if (_s3_error_fs && _error_log_file && _error_log_file->is_open()) {
492
        // close error log file
493
570
        _error_log_file->close();
494
570
        std::string error_log_absolute_path =
495
570
                _exec_env->load_path_mgr()->get_load_error_absolute_path(_error_log_file_path);
496
        // upload error log file to s3
497
570
        Status st = _s3_error_fs->upload(error_log_absolute_path, _s3_error_log_file_path);
498
570
        if (!st.ok()) {
499
            // upload failed and return local error log file path
500
0
            LOG(WARNING) << "Fail to upload error file to s3, error_log_file_path="
501
0
                         << _error_log_file_path << ", error=" << st;
502
0
            return _error_log_file_path;
503
0
        }
504
        // expiration must be less than a week (in seconds) for presigned url
505
570
        static const unsigned EXPIRATION_SECONDS = 7 * 24 * 60 * 60 - 1;
506
        // Use public or private endpoint based on configuration
507
570
        _error_log_file_path =
508
570
                _s3_error_fs->generate_presigned_url(_s3_error_log_file_path, EXPIRATION_SECONDS,
509
570
                                                     config::use_public_endpoint_for_error_log);
510
570
    }
511
386k
    return _error_log_file_path;
512
386k
}
513
514
2.14M
void RuntimeState::resize_op_id_to_local_state(int operator_size) {
515
2.14M
    _op_id_to_local_state.resize(-operator_size);
516
2.14M
}
517
518
void RuntimeState::emplace_local_state(int id,
519
2.55M
                                       std::unique_ptr<doris::PipelineXLocalStateBase> state) {
520
2.55M
    id = -id;
521
2.55M
    DCHECK_LT(id, _op_id_to_local_state.size())
522
0
            << state->parent()->get_name() << " node id = " << state->parent()->node_id();
523
2.55M
    DCHECK(!_op_id_to_local_state[id]);
524
2.55M
    _op_id_to_local_state[id] = std::move(state);
525
2.55M
}
526
527
61.5M
doris::PipelineXLocalStateBase* RuntimeState::get_local_state(int id) {
528
61.5M
    DCHECK_GT(_op_id_to_local_state.size(), -id);
529
61.5M
    return _op_id_to_local_state[-id].get();
530
61.5M
}
531
532
6.07M
Result<RuntimeState::LocalState*> RuntimeState::get_local_state_result(int id) {
533
6.07M
    id = -id;
534
6.07M
    if (id >= _op_id_to_local_state.size()) {
535
0
        return ResultError(Status::InternalError("get_local_state out of range size:{} , id:{}",
536
0
                                                 _op_id_to_local_state.size(), id));
537
0
    }
538
6.07M
    if (!_op_id_to_local_state[id]) {
539
0
        return ResultError(Status::InternalError("get_local_state id:{} is null", id));
540
0
    }
541
6.07M
    return _op_id_to_local_state[id].get();
542
6.07M
};
543
544
void RuntimeState::emplace_sink_local_state(
545
2.14M
        int id, std::unique_ptr<doris::PipelineXSinkLocalStateBase> state) {
546
18.4E
    DCHECK(!_sink_local_state) << " id=" << id << " state: " << state->debug_string(0);
547
2.14M
    _sink_local_state = std::move(state);
548
2.14M
}
549
550
39.8M
doris::PipelineXSinkLocalStateBase* RuntimeState::get_sink_local_state() {
551
39.8M
    return _sink_local_state.get();
552
39.8M
}
553
554
10.4M
Result<RuntimeState::SinkLocalState*> RuntimeState::get_sink_local_state_result() {
555
10.4M
    if (!_sink_local_state) {
556
0
        return ResultError(Status::InternalError("_op_id_to_sink_local_state not exist"));
557
0
    }
558
10.4M
    return _sink_local_state.get();
559
10.4M
}
560
561
1.32M
bool RuntimeState::enable_page_cache() const {
562
1.32M
    return !config::disable_storage_page_cache &&
563
1.32M
           (_query_options.__isset.enable_page_cache && _query_options.enable_page_cache);
564
1.32M
}
565
566
148k
RuntimeFilterMgr* RuntimeState::global_runtime_filter_mgr() {
567
148k
    return _query_ctx->runtime_filter_mgr();
568
148k
}
569
570
Status RuntimeState::register_producer_runtime_filter(
571
50.6k
        const TRuntimeFilterDesc& desc, std::shared_ptr<RuntimeFilterProducer>* producer_filter) {
572
50.6k
    _registered_runtime_filter_ids.insert(desc.filter_id);
573
    // Producers are created by local runtime filter mgr and shared by global runtime filter manager.
574
    // When RF is published, consumers in both global and local RF mgr will be found.
575
50.6k
    RETURN_IF_ERROR(local_runtime_filter_mgr()->register_producer_filter(_query_ctx, desc,
576
50.6k
                                                                         producer_filter));
577
    // Stamp the producer with the current recursive CTE stage so that outgoing merge RPCs
578
    // carry the correct round number and stale messages from old rounds are discarded.
579
    // PFC must still be alive: this runs inside a pipeline task, so the execution context
580
    // cannot have expired yet.
581
    // In unit-test scenarios the task execution context is never set (no PipelineFragmentContext
582
    // exists), so skip the stage stamping — the default stage (0) is correct.
583
51.0k
    if (task_execution_context_inited()) {
584
51.0k
        auto pfc = std::static_pointer_cast<PipelineFragmentContext>(
585
51.0k
                get_task_execution_context().lock());
586
51.0k
        DORIS_CHECK(pfc);
587
51.0k
        (*producer_filter)->set_stage(pfc->rec_cte_stage());
588
51.0k
    }
589
50.6k
    RETURN_IF_ERROR(global_runtime_filter_mgr()->register_local_merge_producer_filter(
590
50.6k
            _query_ctx, desc, *producer_filter));
591
50.6k
    return Status::OK();
592
50.6k
}
593
594
Status RuntimeState::register_consumer_runtime_filter(
595
        const TRuntimeFilterDesc& desc, bool need_local_merge, int node_id,
596
15.0k
        std::shared_ptr<RuntimeFilterConsumer>* consumer_filter) {
597
15.0k
    _registered_runtime_filter_ids.insert(desc.filter_id);
598
15.0k
    bool need_merge = desc.has_remote_targets || need_local_merge ||
599
15.0k
                      (desc.__isset.force_local_merge && desc.force_local_merge);
600
15.0k
    RuntimeFilterMgr* mgr = need_merge ? global_runtime_filter_mgr() : local_runtime_filter_mgr();
601
15.0k
    RETURN_IF_ERROR(mgr->register_consumer_filter(this, desc, node_id, consumer_filter));
602
    // Stamp the consumer with the current recursive CTE stage so that incoming publish RPCs
603
    // from old rounds are detected and discarded.
604
    // PFC must still be alive: this runs inside a pipeline task, so the execution context
605
    // cannot have expired yet.
606
    // In unit-test scenarios the task execution context is never set (no PipelineFragmentContext
607
    // exists), so skip the stage stamping — the default stage (0) is correct.
608
15.0k
    if (task_execution_context_inited()) {
609
15.0k
        auto pfc = std::static_pointer_cast<PipelineFragmentContext>(
610
15.0k
                get_task_execution_context().lock());
611
15.0k
        DORIS_CHECK(pfc);
612
15.0k
        (*consumer_filter)->set_stage(pfc->rec_cte_stage());
613
15.0k
    }
614
15.0k
    return Status::OK();
615
15.0k
}
616
617
13.2M
bool RuntimeState::is_nereids() const {
618
13.2M
    return _query_ctx->is_nereids();
619
13.2M
}
620
621
3.40k
std::vector<std::shared_ptr<RuntimeProfile>> RuntimeState::pipeline_id_to_profile() {
622
3.40k
    std::shared_lock lc(_pipeline_profile_lock);
623
3.40k
    return _pipeline_id_to_profile;
624
3.40k
}
625
626
std::vector<std::shared_ptr<RuntimeProfile>> RuntimeState::build_pipeline_profile(
627
469k
        std::size_t pipeline_size) {
628
469k
    std::unique_lock lc(_pipeline_profile_lock);
629
469k
    if (!_pipeline_id_to_profile.empty()) {
630
0
        return _pipeline_id_to_profile;
631
0
    }
632
469k
    _pipeline_id_to_profile.resize(pipeline_size);
633
469k
    {
634
469k
        size_t pip_idx = 0;
635
732k
        for (auto& pipeline_profile : _pipeline_id_to_profile) {
636
732k
            pipeline_profile =
637
732k
                    std::make_shared<RuntimeProfile>(fmt::format("Pipeline(id={})", pip_idx));
638
732k
            pip_idx++;
639
732k
        }
640
469k
    }
641
469k
    return _pipeline_id_to_profile;
642
469k
}
643
644
17.4M
bool RuntimeState::low_memory_mode() const {
645
#ifdef BE_TEST
646
    if (!_query_ctx) {
647
        return false;
648
    }
649
#endif
650
17.4M
    return _query_ctx->low_memory_mode();
651
17.4M
}
652
653
5.37k
void RuntimeState::set_id_file_map() {
654
5.37k
    _id_file_map = _exec_env->get_id_manager()->add_id_file_map(_query_id, execution_timeout());
655
5.37k
}
656
} // end namespace doris