Coverage Report

Created: 2026-08-16 17:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/thread_context.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
18
#pragma once
19
20
#include <bthread/bthread.h>
21
#include <bthread/types.h>
22
23
#include <memory>
24
#include <string>
25
#include <thread>
26
27
#include "common/exception.h"
28
#include "common/logging.h"
29
#include "common/macros.h"
30
#include "runtime/memory/mem_tracker_limiter.h"
31
#include "runtime/memory/thread_mem_tracker_mgr.h"
32
#include "util/defer_op.h" // IWYU pragma: keep
33
34
// Used to tracking query/load/compaction/e.g. execution thread memory usage.
35
// This series of methods saves some information to the thread local context of the current worker thread,
36
// including MemTracker, QueryID, etc. Use CONSUME_THREAD_MEM_TRACKER/RELEASE_THREAD_MEM_TRACKER in the code segment where
37
// the macro is located to record the memory into MemTracker.
38
// Not use it in rpc done.run(), because bthread_setspecific may have errors when UBSAN compiles.
39
40
// Attach to query/load/compaction/e.g. when thread starts.
41
// This will save some info about a working thread in the thread context.
42
// Looking forward to tracking memory during thread execution into MemTrackerLimiter.
43
11.8M
#define SCOPED_ATTACH_TASK(arg1) auto VARNAME_LINENUM(attach_task) = AttachTask(arg1)
44
45
// If the current thread is not executing a Task, such as a StorageEngine thread,
46
// use SCOPED_INIT_THREAD_CONTEXT to initialize ThreadContext.
47
#define SCOPED_INIT_THREAD_CONTEXT() \
48
358
    auto VARNAME_LINENUM(scoped_tls_itc) = doris::ScopedInitThreadContext()
49
50
// Switch resource context in thread context, used after SCOPED_ATTACH_TASK.
51
// If just want to switch mem tracker, use SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER first.
52
#define SCOPED_SWITCH_RESOURCE_CONTEXT(arg1) \
53
    auto VARNAME_LINENUM(switch_resource_context) = doris::SwitchResourceContext(arg1)
54
55
// Switch MemTrackerLimiter for count memory during thread execution.
56
// Used after SCOPED_ATTACH_TASK, in order to count the memory into another
57
// MemTrackerLimiter instead of the MemTrackerLimiter added by the attach task.
58
#define SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(arg1) \
59
18.5M
    auto VARNAME_LINENUM(switch_mem_tracker) = doris::SwitchThreadMemTrackerLimiter(arg1)
60
61
// Looking forward to tracking memory during thread execution into MemTracker.
62
// Usually used to record query more detailed memory, including ExecNode operators.
63
#define SCOPED_CONSUME_MEM_TRACKER(mem_tracker) \
64
1.45M
    auto VARNAME_LINENUM(add_mem_consumer) = doris::AddThreadMemTrackerConsumer(mem_tracker)
65
66
#define DEFER_RELEASE_RESERVED()   \
67
8.41M
    Defer VARNAME_LINENUM(defer) { \
68
8.41M
            [&]() { doris::thread_context()->thread_mem_tracker_mgr->shrink_reserved(); }};
unity_7_cxx.cxx:_ZZN5doris12PipelineTask7executeEPbENK3$_2clEv
Line
Count
Source
68
6.26M
            [&]() { doris::thread_context()->thread_mem_tracker_mgr->shrink_reserved(); }};
unity_7_cxx.cxx:_ZZN5doris12PipelineTask7executeEPbENK3$_3clEv
Line
Count
Source
68
2.14M
            [&]() { doris::thread_context()->thread_mem_tracker_mgr->shrink_reserved(); }};
69
70
// Count a code segment memory
71
// Usage example:
72
//      int64_t peak_mem = 0;
73
//      {
74
//          SCOPED_PEAK_MEM(&peak_mem);
75
//          xxxx
76
//      }
77
//      LOG(INFO) << *peak_mem;
78
#define SCOPED_PEAK_MEM(peak_mem) \
79
742k
    auto VARNAME_LINENUM(scope_peak_mem) = doris::ScopedPeakMem(peak_mem)
80
81
#define SCOPED_SKIP_MEMORY_CHECK() \
82
23.0M
    auto VARNAME_LINENUM(scope_skip_memory_check) = doris::ScopeSkipMemoryCheck()
83
84
#define SKIP_LARGE_MEMORY_CHECK(...)                                                    \
85
    do {                                                                                \
86
        doris::ThreadLocalHandle::create_thread_local_if_not_exits();                   \
87
        doris::thread_context()->thread_mem_tracker_mgr->skip_large_memory_check++;     \
88
        DEFER({                                                                         \
89
            doris::thread_context()->thread_mem_tracker_mgr->skip_large_memory_check--; \
90
            doris::ThreadLocalHandle::del_thread_local_if_count_is_zero();              \
91
        });                                                                             \
92
        __VA_ARGS__;                                                                    \
93
    } while (0)
94
95
#define LIMIT_LOCAL_SCAN_IO(data_dir, bytes_read)                                            \
96
21.4M
    std::shared_ptr<IOThrottle> iot = nullptr;                                               \
97
21.4M
    auto* t_ctx = doris::thread_context();                                                   \
98
21.4M
    if (t_ctx->is_attach_task() && t_ctx->resource_ctx()->workload_group() != nullptr) {     \
99
20.6M
        iot = t_ctx->resource_ctx()->workload_group()->get_local_scan_io_throttle(data_dir); \
100
20.6M
    }                                                                                        \
101
21.4M
    if (iot) {                                                                               \
102
20.6M
        iot->acquire(-1);                                                                    \
103
20.6M
    }                                                                                        \
104
21.4M
    Defer defer {                                                                            \
105
21.7M
        [&]() {                                                                              \
106
21.7M
            if (iot) {                                                                       \
107
20.5M
                iot->update_next_io_time(*bytes_read);                                       \
108
20.5M
                t_ctx->resource_ctx()->workload_group()->update_local_scan_io(data_dir,      \
109
20.5M
                                                                              *bytes_read);  \
110
20.5M
            }                                                                                \
111
21.7M
        }                                                                                    \
unity_2_cxx.cxx:_ZZN5doris2io15LocalFileReader12read_at_implEmNS_5SliceEPmPKNS0_9IOContextEENK3$_0clEv
Line
Count
Source
105
21.7M
        [&]() {                                                                              \
106
21.7M
            if (iot) {                                                                       \
107
20.5M
                iot->update_next_io_time(*bytes_read);                                       \
108
20.5M
                t_ctx->resource_ctx()->workload_group()->update_local_scan_io(data_dir,      \
109
20.5M
                                                                              *bytes_read);  \
110
20.5M
            }                                                                                \
111
21.7M
        }                                                                                    \
unity_2_cxx.cxx:_ZZN5doris2io15LocalFileReader18read_at_iobuf_implEmmPN5butil5IOBufEPmPKNS0_9IOContextEENK3$_0clEv
Line
Count
Source
105
7
        [&]() {                                                                              \
106
7
            if (iot) {                                                                       \
107
0
                iot->update_next_io_time(*bytes_read);                                       \
108
0
                t_ctx->resource_ctx()->workload_group()->update_local_scan_io(data_dir,      \
109
0
                                                                              *bytes_read);  \
110
0
            }                                                                                \
111
7
        }                                                                                    \
112
21.4M
    }
113
114
#define LIMIT_REMOTE_SCAN_IO(bytes_read)                                                     \
115
229k
    std::shared_ptr<IOThrottle> iot = nullptr;                                               \
116
229k
    auto* t_ctx = doris::thread_context();                                                   \
117
229k
    if (t_ctx->is_attach_task() && t_ctx->resource_ctx()->workload_group() != nullptr) {     \
118
193k
        iot = t_ctx->resource_ctx()->workload_group()->get_remote_scan_io_throttle();        \
119
193k
    }                                                                                        \
120
229k
    if (iot) {                                                                               \
121
193k
        iot->acquire(-1);                                                                    \
122
193k
    }                                                                                        \
123
229k
    Defer defer {                                                                            \
124
229k
        [&]() {                                                                              \
125
229k
            if (iot) {                                                                       \
126
193k
                iot->update_next_io_time(*bytes_read);                                       \
127
193k
                t_ctx->resource_ctx()->workload_group()->update_remote_scan_io(*bytes_read); \
128
193k
            }                                                                                \
129
229k
        }                                                                                    \
unity_2_cxx.cxx:_ZZN5doris2io12S3FileReader12read_at_implEmNS_5SliceEPmPKNS0_9IOContextEENK3$_0clEv
Line
Count
Source
124
228k
        [&]() {                                                                              \
125
228k
            if (iot) {                                                                       \
126
192k
                iot->update_next_io_time(*bytes_read);                                       \
127
192k
                t_ctx->resource_ctx()->workload_group()->update_remote_scan_io(*bytes_read); \
128
192k
            }                                                                                \
129
228k
        }                                                                                    \
unity_1_cxx.cxx:_ZZN5doris2io14PrefetchBuffer11read_bufferEmPKcmPmENK3$_1clEv
Line
Count
Source
124
139
        [&]() {                                                                              \
125
139
            if (iot) {                                                                       \
126
108
                iot->update_next_io_time(*bytes_read);                                       \
127
108
                t_ctx->resource_ctx()->workload_group()->update_remote_scan_io(*bytes_read); \
128
108
            }                                                                                \
129
139
        }                                                                                    \
Unexecuted instantiation: unity_1_cxx.cxx:_ZZN5doris2io14HdfsFileReader15do_read_at_implEmNS_5SliceEPmPKNS0_9IOContextEENK3$_0clEv
unity_0_cxx.cxx:_ZZN5doris2io19PeerFileCacheReader12fetch_blocksERKSt6vectorISt10shared_ptrINS0_9FileBlockEESaIS5_EEPNS0_15PeerFetchResultEmPKNS0_9IOContextEblNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEENK3$_0clEv
Line
Count
Source
124
39
        [&]() {                                                                              \
125
39
            if (iot) {                                                                       \
126
3
                iot->update_next_io_time(*bytes_read);                                       \
127
3
                t_ctx->resource_ctx()->workload_group()->update_remote_scan_io(*bytes_read); \
128
3
            }                                                                                \
129
39
        }                                                                                    \
130
229k
    }
131
132
namespace doris {
133
134
class ThreadContext;
135
class MemTracker;
136
class QueryContext;
137
class ResourceContext;
138
class RuntimeState;
139
class SwitchResourceContext;
140
141
extern bthread_key_t btls_key;
142
143
static std::string NO_THREAD_CONTEXT_MSG =
144
        "Current thread not exist ThreadContext, usually after the thread is started, using "
145
        "SCOPED_ATTACH_TASK macro to create a ThreadContext and bind a Task.";
146
147
// Is true after ThreadContext construction.
148
inline thread_local bool pthread_context_ptr_init = false;
149
inline thread_local constinit ThreadContext* thread_context_ptr = nullptr;
150
151
// The thread context saves some info about a working thread.
152
// 2 required info:
153
//   1. thread_id:   Current thread id, Auto generated.
154
//   2. type(abolished):        The type is a enum value indicating which type of task current thread is running.
155
//                   For example: QUERY, LOAD, COMPACTION, ...
156
//   3. task id:     A unique id to identify this task. maybe query id, load job id, etc.
157
//   4. ThreadMemTrackerMgr
158
//
159
// There may be other optional info to be added later.
160
//
161
// Note: Keep the class simple and only add properties.
162
class ThreadContext {
163
public:
164
3.54M
    ThreadContext() { thread_mem_tracker_mgr = std::make_unique<ThreadMemTrackerMgr>(); }
165
166
3.54M
    ~ThreadContext() = default;
167
168
    void attach_task(const std::shared_ptr<ResourceContext>& rc);
169
170
11.8M
    void detach_task() {
171
11.8M
        resource_ctx_.reset();
172
11.8M
        thread_mem_tracker_mgr->detach_limiter_tracker();
173
11.8M
        thread_mem_tracker_mgr->disable_wait_gc();
174
11.8M
    }
175
176
149M
    bool is_attach_task() { return resource_ctx_ != nullptr; }
177
178
64.1M
    std::shared_ptr<ResourceContext> resource_ctx() {
179
64.1M
#ifndef BE_TEST
180
64.1M
        DCHECK(is_attach_task());
181
64.1M
#endif
182
64.1M
        if (is_attach_task()) {
183
64.1M
            return resource_ctx_;
184
64.1M
        }
185
18.4E
        return _make_orphan_resource_ctx();
186
64.1M
    }
187
188
43.0k
    static std::string get_thread_id() {
189
43.0k
        std::stringstream ss;
190
43.0k
        ss << std::this_thread::get_id();
191
43.0k
        return ss.str();
192
43.0k
    }
193
    // Note that if set global Memory Hook, After thread_mem_tracker_mgr is initialized,
194
    // the current thread Hook starts to consume/release mem_tracker.
195
    // the use of shared_ptr will cause a crash. The guess is that there is an
196
    // intermediate state during the copy construction of shared_ptr. Shared_ptr is not equal
197
    // to nullptr, but the object it points to is not initialized. At this time, when the memory
198
    // is released somewhere, the hook is triggered to cause the crash.
199
    std::unique_ptr<ThreadMemTrackerMgr> thread_mem_tracker_mgr;
200
201
    int thread_local_handle_count = 0;
202
203
private:
204
    friend class SwitchResourceContext;
205
206
    // Cold fallback for threads without an attached task; defined in the .cpp
207
    // so this header does not need the full ResourceContext / ExecEnv types.
208
    static std::shared_ptr<ResourceContext> _make_orphan_resource_ctx();
209
210
    std::shared_ptr<ResourceContext> resource_ctx_;
211
};
212
213
class ThreadLocalHandle {
214
public:
215
55.6M
    static void create_thread_local_if_not_exits() {
216
55.6M
        if (bthread_self() == 0) {
217
53.0M
            if (!pthread_context_ptr_init) {
218
1.42M
                thread_context_ptr = new ThreadContext();
219
1.42M
                pthread_context_ptr_init = true;
220
1.42M
            }
221
53.0M
            DCHECK(thread_context_ptr != nullptr);
222
53.0M
            thread_context_ptr->thread_local_handle_count++;
223
53.0M
        } else {
224
            // Avoid calling bthread_getspecific frequently to get bthread local.
225
            // Very frequent bthread_getspecific will slow, but create_thread_local_if_not_exits is not expected to be much.
226
            // Cache the pointer of bthread local in pthead local.
227
2.57M
            auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
228
2.57M
            if (bthread_context == nullptr) {
229
                // If bthread_context == nullptr:
230
                // 1. First call to bthread_getspecific (and before any bthread_setspecific) returns NULL
231
                // 2. There are not enough reusable btls in btls pool.
232
                // else if bthread_context != nullptr:
233
                // 1. A new bthread starts, but get a reuses btls.
234
2.10M
                bthread_context = new ThreadContext;
235
                // The brpc server should respond as quickly as possible.
236
2.10M
                bthread_context->thread_mem_tracker_mgr->disable_wait_gc();
237
                // set the data so that next time bthread_getspecific in the thread returns the data.
238
2.10M
                CHECK(0 == bthread_setspecific(btls_key, bthread_context) || doris::k_doris_exit);
239
2.10M
            }
240
2.57M
            DCHECK(bthread_context != nullptr);
241
2.57M
            bthread_context->thread_local_handle_count++;
242
2.57M
        }
243
55.6M
    }
244
245
    // `create_thread_local_if_not_exits` and `del_thread_local_if_count_is_zero` should be used in pairs,
246
    // `del_thread_local_if_count_is_zero` should only be called if `create_thread_local_if_not_exits` returns true
247
55.6M
    static void del_thread_local_if_count_is_zero() {
248
55.6M
        if (pthread_context_ptr_init) {
249
            // in pthread
250
53.0M
            thread_context_ptr->thread_local_handle_count--;
251
53.0M
            if (thread_context_ptr->thread_local_handle_count == 0) {
252
1.41M
                pthread_context_ptr_init = false;
253
1.41M
                delete doris::thread_context_ptr;
254
1.41M
                thread_context_ptr = nullptr;
255
1.41M
            }
256
53.0M
        } else if (bthread_self() != 0) {
257
            // in bthread
258
2.64M
            auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
259
2.64M
            DCHECK(bthread_context != nullptr);
260
2.64M
            bthread_context->thread_local_handle_count--;
261
18.4E
        } else {
262
18.4E
            throw Exception(Status::FatalError("__builtin_unreachable"));
263
18.4E
        }
264
55.6M
    }
265
};
266
267
// must call create_thread_local_if_not_exits() before use thread_context().
268
626M
static ThreadContext* thread_context() {
269
626M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
620M
        DCHECK(bthread_self() == 0);
272
620M
        DCHECK(thread_context_ptr != nullptr);
273
620M
        return thread_context_ptr;
274
620M
    }
275
5.49M
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
5.49M
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
5.49M
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
5.49M
        return bthread_context;
281
5.49M
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
5.46M
}
Unexecuted instantiation: doris_main.cpp:_ZN5dorisL14thread_contextEv
unity_0_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
460M
static ThreadContext* thread_context() {
269
460M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
459M
        DCHECK(bthread_self() == 0);
272
459M
        DCHECK(thread_context_ptr != nullptr);
273
459M
        return thread_context_ptr;
274
459M
    }
275
151k
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
108k
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
108k
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
108k
        return bthread_context;
281
108k
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
42.5k
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
151k
}
Unexecuted instantiation: config.cpp:_ZN5dorisL14thread_contextEv
unity_2_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
22.0M
static ThreadContext* thread_context() {
269
22.0M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
22.0M
        DCHECK(bthread_self() == 0);
272
22.0M
        DCHECK(thread_context_ptr != nullptr);
273
22.0M
        return thread_context_ptr;
274
22.0M
    }
275
18.4E
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
0
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
0
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
0
        return bthread_context;
281
0
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
18.4E
}
Unexecuted instantiation: field.cpp:_ZN5dorisL14thread_contextEv
unity_3_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
53.6M
static ThreadContext* thread_context() {
269
53.6M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
48.3M
        DCHECK(bthread_self() == 0);
272
48.3M
        DCHECK(thread_context_ptr != nullptr);
273
48.3M
        return thread_context_ptr;
274
48.3M
    }
275
5.33M
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
5.33M
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
5.33M
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
5.33M
        return bthread_context;
281
5.33M
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
5.28M
}
unity_1_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
73.2M
static ThreadContext* thread_context() {
269
73.2M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
73.1M
        DCHECK(bthread_self() == 0);
272
73.1M
        DCHECK(thread_context_ptr != nullptr);
273
73.1M
        return thread_context_ptr;
274
73.1M
    }
275
53.8k
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
53.8k
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
53.8k
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
53.8k
        return bthread_context;
281
53.8k
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
45.9k
}
Unexecuted instantiation: unity_5_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_6_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vdatetime_value.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: data_type_serde.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: data_type_number_serde.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_4_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: column_variant.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: convert_field_to_type.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_13_cxx.cxx:_ZN5dorisL14thread_contextEv
unity_7_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
15.1M
static ThreadContext* thread_context() {
269
15.1M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
15.1M
        DCHECK(bthread_self() == 0);
272
15.1M
        DCHECK(thread_context_ptr != nullptr);
273
15.1M
        return thread_context_ptr;
274
15.1M
    }
275
18.4E
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
0
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
0
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
0
        return bthread_context;
281
0
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
18.4E
}
unity_12_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
19.9k
static ThreadContext* thread_context() {
269
19.9k
    if (pthread_context_ptr_init) {
270
        // in pthread
271
19.9k
        DCHECK(bthread_self() == 0);
272
19.9k
        DCHECK(thread_context_ptr != nullptr);
273
19.9k
        return thread_context_ptr;
274
19.9k
    }
275
0
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
0
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
0
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
0
        return bthread_context;
281
0
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
0
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
0
}
unity_11_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
172k
static ThreadContext* thread_context() {
269
172k
    if (pthread_context_ptr_init) {
270
        // in pthread
271
172k
        DCHECK(bthread_self() == 0);
272
172k
        DCHECK(thread_context_ptr != nullptr);
273
172k
        return thread_context_ptr;
274
172k
    }
275
18.4E
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
0
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
0
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
0
        return bthread_context;
281
0
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
18.4E
}
Unexecuted instantiation: unity_10_cxx.cxx:_ZN5dorisL14thread_contextEv
unity_9_cxx.cxx:_ZN5dorisL14thread_contextEv
Line
Count
Source
268
1.80M
static ThreadContext* thread_context() {
269
1.81M
    if (pthread_context_ptr_init) {
270
        // in pthread
271
1.81M
        DCHECK(bthread_self() == 0);
272
1.81M
        DCHECK(thread_context_ptr != nullptr);
273
1.81M
        return thread_context_ptr;
274
1.81M
    }
275
18.4E
    if (bthread_self() != 0) {
276
        // in bthread
277
        // bthread switching pthread may be very frequent, remember not to use lock or other time-consuming operations.
278
0
        auto* bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
279
0
        DCHECK(bthread_context != nullptr && bthread_context->thread_local_handle_count > 0);
280
0
        return bthread_context;
281
0
    }
282
    // It means that use thread_context() but this thread not attached a query/load using SCOPED_ATTACH_TASK macro.
283
18.4E
    throw Exception(Status::FatalError("{}", doris::NO_THREAD_CONTEXT_MSG));
284
18.4E
}
Unexecuted instantiation: unity_8_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hashjoin_build_sink.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: join_build_sink_operator.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: operator.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: partitioned_aggregation_sink_operator.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: scan_operator.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vfile_result_writer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_30_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_29_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_28_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_27_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_26_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_25_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_24_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_23_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_22_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_21_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_20_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_19_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_18_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_17_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_16_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_15_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: unity_14_cxx.cxx:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: ai_functions.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_array_aggregation.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_cast_decimal.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_bitmap_variadic.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_date_or_datetime_computation.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_datetime_floor_ceil.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_jsonb_transform.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_string_misc.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: function_variant_element.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: in.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: minus.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: multiply.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: plus.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: round.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: uuid.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: arrow_row_batch.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: arrow_stream_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: csv_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: new_plain_binary_line_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: new_json_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: native_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vorc_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: column_type_convert.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: schema_desc.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_group_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_column_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_column_chunk_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_page_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: parquet_column_convert.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_page_index.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: parquet_block_split_bloom_filter.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: deletion_vector_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: es_http_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: es_scroll_parser.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hive_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hive_orc_nested_column_utils.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hudi_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hudi_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_delete_file_reader_helper.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_position_delete_sys_table_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_orc_nested_column_utils.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: equality_delete.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_sys_table_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: jdbc_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: max_compute_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: paimon_cpp_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: paimon_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: paimon_predicate_converter.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: paimon_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: parquet_metadata_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: parquet_utils.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: remote_doris_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: table_format_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: table_schema_change_helper.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: transactional_hive_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: trino_connector_jni_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: text_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: merge_partitioner.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: iceberg_partition_function.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vcsv_transformer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vfile_format_transformer_factory.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vjni_format_transformer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vnative_transformer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vorc_transformer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vparquet_transformer.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: adbc_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: hdfs_file_system.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: s3_file_system.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: collection_statistics.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: inverted_index_compound_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: inverted_index_fs_directory.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: zone_map_index.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: vcollect_iterator.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: predicate_creator_comparison.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: predicate_creator_in_list_in.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: predicate_creator_in_list_not_in.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: tablet.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: engine_clone_task.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: descriptors.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: backend_service.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: internal_service.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: point_query_executor.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: be_server_starter_factory.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: http_service.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: arrow_flight_batch_reader.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: thrift_util.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: load_stream.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: routine_load_task_executor.cpp:_ZN5dorisL14thread_contextEv
Unexecuted instantiation: cloud_compaction_action.cpp:_ZN5dorisL14thread_contextEv
285
286
class ScopedPeakMem {
287
public:
288
    explicit ScopedPeakMem(int64_t* peak_mem)
289
742k
            : _peak_mem(peak_mem),
290
742k
              _mem_tracker("ScopedPeakMem:" + UniqueId::gen_uid().to_string()) {
291
742k
        ThreadLocalHandle::create_thread_local_if_not_exits();
292
742k
        thread_context()->thread_mem_tracker_mgr->push_consumer_tracker(&_mem_tracker);
293
742k
    }
294
295
741k
    ~ScopedPeakMem() {
296
741k
        thread_context()->thread_mem_tracker_mgr->pop_consumer_tracker();
297
741k
        *_peak_mem += _mem_tracker.peak_consumption();
298
741k
        ThreadLocalHandle::del_thread_local_if_count_is_zero();
299
741k
    }
300
301
private:
302
    int64_t* _peak_mem;
303
    MemTracker _mem_tracker;
304
};
305
306
// only hold thread context in scope.
307
class ScopedInitThreadContext {
308
public:
309
482
    explicit ScopedInitThreadContext() { ThreadLocalHandle::create_thread_local_if_not_exits(); }
310
311
473
    ~ScopedInitThreadContext() { ThreadLocalHandle::del_thread_local_if_count_is_zero(); }
312
};
313
314
class AttachTask {
315
public:
316
    // you must use ResourceCtx or MemTracker initialization.
317
    explicit AttachTask() = delete;
318
319
    explicit AttachTask(const std::shared_ptr<ResourceContext>& rc);
320
321
    // Shortcut attach task, initialize an empty resource context, and set the memory tracker.
322
    explicit AttachTask(const std::shared_ptr<MemTrackerLimiter>& mem_tracker);
323
324
    // is query or load, initialize with memory tracker, query id and workload group wptr.
325
    explicit AttachTask(RuntimeState* runtime_state);
326
327
    explicit AttachTask(QueryContext* query_ctx);
328
329
    void init(const std::shared_ptr<ResourceContext>& rc);
330
331
    ~AttachTask();
332
};
333
334
class SwitchResourceContext {
335
public:
336
    explicit SwitchResourceContext(const std::shared_ptr<ResourceContext>& rc);
337
338
    ~SwitchResourceContext();
339
340
private:
341
    std::shared_ptr<ResourceContext> old_resource_ctx_ {nullptr};
342
};
343
344
class SwitchThreadMemTrackerLimiter {
345
public:
346
    explicit SwitchThreadMemTrackerLimiter(
347
            const std::shared_ptr<doris::MemTrackerLimiter>& mem_tracker);
348
349
    ~SwitchThreadMemTrackerLimiter();
350
351
private:
352
    bool is_switched_ {false};
353
};
354
355
class AddThreadMemTrackerConsumer {
356
public:
357
    // The owner and user of MemTracker are in the same thread, and the raw pointer is faster.
358
    // If mem_tracker is nullptr, do nothing.
359
    explicit AddThreadMemTrackerConsumer(MemTracker* mem_tracker);
360
361
    // The owner and user of MemTracker are in different threads. If mem_tracker is nullptr, do nothing.
362
    explicit AddThreadMemTrackerConsumer(const std::shared_ptr<MemTracker>& mem_tracker);
363
364
    ~AddThreadMemTrackerConsumer();
365
366
private:
367
    std::shared_ptr<MemTracker> _mem_tracker; // Avoid mem_tracker being released midway.
368
    bool _need_pop = false;
369
};
370
371
class ScopeSkipMemoryCheck {
372
public:
373
23.0M
    explicit ScopeSkipMemoryCheck() {
374
23.0M
        ThreadLocalHandle::create_thread_local_if_not_exits();
375
23.0M
        doris::thread_context()->thread_mem_tracker_mgr->skip_memory_check++;
376
23.0M
    }
377
378
23.0M
    ~ScopeSkipMemoryCheck() {
379
23.0M
        doris::thread_context()->thread_mem_tracker_mgr->skip_memory_check--;
380
23.0M
        ThreadLocalHandle::del_thread_local_if_count_is_zero();
381
23.0M
    }
382
};
383
384
// Basic macros for mem tracker, usually do not need to be modified and used.
385
// must call create_thread_local_if_not_exits() before use thread_context().
386
#define CONSUME_THREAD_MEM_TRACKER(size)                                                           \
387
144M
    do {                                                                                           \
388
144M
        if (size == 0) {                                                                           \
389
231k
            break;                                                                                 \
390
231k
        }                                                                                          \
391
144M
        if (doris::pthread_context_ptr_init) {                                                     \
392
143M
            DCHECK(bthread_self() == 0);                                                           \
393
143M
            doris::thread_context_ptr->thread_mem_tracker_mgr->consume(size);                      \
394
143M
        } else if (bthread_self() != 0) {                                                          \
395
1.41k
            auto* bthread_context =                                                                \
396
1.41k
                    static_cast<doris::ThreadContext*>(bthread_getspecific(doris::btls_key));      \
397
1.41k
            DCHECK(bthread_context != nullptr);                                                    \
398
1.41k
            if (bthread_context != nullptr) {                                                      \
399
1.41k
                bthread_context->thread_mem_tracker_mgr->consume(size);                            \
400
1.41k
            } else {                                                                               \
401
0
                doris::ExecEnv::GetInstance()->orphan_mem_tracker()->consume_no_update_peak(size); \
402
0
            }                                                                                      \
403
526k
        } else if (doris::ExecEnv::ready()) {                                                      \
404
0
            DCHECK(doris::k_doris_exit || !doris::config::enable_memory_orphan_check)              \
405
0
                    << doris::NO_THREAD_CONTEXT_MSG;                                               \
406
0
            doris::ExecEnv::GetInstance()->orphan_mem_tracker()->consume_no_update_peak(size);     \
407
0
        }                                                                                          \
408
143M
    } while (0)
409
72.1M
#define RELEASE_THREAD_MEM_TRACKER(size) CONSUME_THREAD_MEM_TRACKER(-size)
410
411
} // namespace doris