This is an automated email from the ASF dual-hosted git repository.

yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 6ecdf94b09a branch-4.1: [Chore](check) add some Sanity-check for avoid 
npe #62691 (#62807)
6ecdf94b09a is described below

commit 6ecdf94b09abea7a61023cb7dca4addda1909f2b
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Sat Apr 25 20:55:56 2026 +0800

    branch-4.1: [Chore](check) add some Sanity-check for avoid npe #62691 
(#62807)
    
    Cherry-picked from #62691
    
    Co-authored-by: Pxl <[email protected]>
---
 be/src/exec/operator/hashjoin_build_sink.cpp       |   9 +-
 .../partitioned_hash_join_sink_operator.cpp        |  11 ++-
 be/src/exec/operator/set_sink_operator.cpp         |   8 +-
 be/src/exec/pipeline/pipeline_task.cpp             |   1 +
 be/src/runtime/memory/thread_mem_tracker_mgr.cpp   |  39 ++++++++
 be/src/runtime/thread_context.cpp                  | 101 +++++++++++++++++++++
 be/src/runtime/thread_context.h                    |   5 +
 7 files changed, 171 insertions(+), 3 deletions(-)

diff --git a/be/src/exec/operator/hashjoin_build_sink.cpp 
b/be/src/exec/operator/hashjoin_build_sink.cpp
index 94256a36dd2..0d5f742692e 100644
--- a/be/src/exec/operator/hashjoin_build_sink.cpp
+++ b/be/src/exec/operator/hashjoin_build_sink.cpp
@@ -119,7 +119,14 @@ Status 
HashJoinBuildSinkLocalState::terminate(RuntimeState* state) {
     if (_terminated) {
         return Status::OK();
     }
-    RETURN_IF_ERROR(_runtime_filter_producer_helper->skip_process(state));
+    // Defensive null-guard: other paths in this file already gate on
+    // `_runtime_filter_producer_helper` because cancel / early wake-up may
+    // run terminate before the helper is attached. The terminate path used
+    // to be the only one missing the guard, which would NPE inside
+    // skip_process() and surface as a generic crash deep in the allocator.
+    if (_runtime_filter_producer_helper) {
+        RETURN_IF_ERROR(_runtime_filter_producer_helper->skip_process(state));
+    }
     return JoinBuildSinkLocalState::terminate(state);
 }
 
diff --git a/be/src/exec/operator/partitioned_hash_join_sink_operator.cpp 
b/be/src/exec/operator/partitioned_hash_join_sink_operator.cpp
index dacceabb59c..7e3267d8e58 100644
--- a/be/src/exec/operator/partitioned_hash_join_sink_operator.cpp
+++ b/be/src/exec/operator/partitioned_hash_join_sink_operator.cpp
@@ -236,12 +236,21 @@ Status 
PartitionedHashJoinSinkLocalState::terminate(RuntimeState* state) {
     if (_terminated) {
         return Status::OK();
     }
+    // Walk the chain `_shared_state -> _inner_runtime_state` defensively.
+    // The inner runtime state is built separately from the outer sink's
+    // setup_local_state path, so its atomicity is weaker than a top-level
+    // local-state init. Any null in this chain on a cancel / early-wake
+    // path would NPE inside terminate.
+    if (_shared_state == nullptr || _shared_state->_inner_runtime_state == 
nullptr) {
+        return 
PipelineXSpillSinkLocalState<PartitionedHashJoinSharedState>::terminate(state);
+    }
     HashJoinBuildSinkLocalState* inner_sink_state {nullptr};
     if (auto* tmp_sink_state = 
_shared_state->_inner_runtime_state->get_sink_local_state()) {
         inner_sink_state = 
assert_cast<HashJoinBuildSinkLocalState*>(tmp_sink_state);
     }
     if (inner_sink_state) {
-        if 
(_parent->cast<PartitionedHashJoinSinkOperatorX>()._inner_sink_operator) {
+        if 
(_parent->cast<PartitionedHashJoinSinkOperatorX>()._inner_sink_operator &&
+            inner_sink_state->_runtime_filter_producer_helper) {
             
RETURN_IF_ERROR(inner_sink_state->_runtime_filter_producer_helper->skip_process(state));
         }
         inner_sink_state->_terminated = true;
diff --git a/be/src/exec/operator/set_sink_operator.cpp 
b/be/src/exec/operator/set_sink_operator.cpp
index 27a11f31a66..17a10d95eab 100644
--- a/be/src/exec/operator/set_sink_operator.cpp
+++ b/be/src/exec/operator/set_sink_operator.cpp
@@ -32,7 +32,13 @@ Status 
SetSinkLocalState<is_intersect>::terminate(RuntimeState* state) {
     if (_terminated) {
         return Status::OK();
     }
-    RETURN_IF_ERROR(_runtime_filter_producer_helper->skip_process(state));
+    // Defensive null-guard, mirroring the close()/sink() paths in this
+    // file which already gate on `_runtime_filter_producer_helper`.
+    // terminate() may run on a cancel / early-wake path before the helper
+    // is attached, in which case skip_process() would NPE.
+    if (_runtime_filter_producer_helper) {
+        RETURN_IF_ERROR(_runtime_filter_producer_helper->skip_process(state));
+    }
     return Base::terminate(state);
 }
 
diff --git a/be/src/exec/pipeline/pipeline_task.cpp 
b/be/src/exec/pipeline/pipeline_task.cpp
index 37575e8b5bc..19da7499872 100644
--- a/be/src/exec/pipeline/pipeline_task.cpp
+++ b/be/src/exec/pipeline/pipeline_task.cpp
@@ -27,6 +27,7 @@
 #include <ostream>
 #include <vector>
 
+#include "common/exception.h"
 #include "common/logging.h"
 #include "common/status.h"
 #include "core/block/block.h"
diff --git a/be/src/runtime/memory/thread_mem_tracker_mgr.cpp 
b/be/src/runtime/memory/thread_mem_tracker_mgr.cpp
index 3339fd680ab..c876eab7bb4 100644
--- a/be/src/runtime/memory/thread_mem_tracker_mgr.cpp
+++ b/be/src/runtime/memory/thread_mem_tracker_mgr.cpp
@@ -19,6 +19,8 @@
 
 #include <gen_cpp/types.pb.h>
 
+#include "common/exception.h"
+#include "common/signal_handler.h"
 #include "runtime/exec_env.h"
 
 namespace doris {
@@ -27,6 +29,25 @@ namespace doris {
 void ThreadMemTrackerMgr::attach_limiter_tracker(
         const std::shared_ptr<MemTrackerLimiter>& mem_tracker) {
     DCHECK(mem_tracker);
+    if (UNLIKELY(!mem_tracker)) {
+        // Without this guard, _limiter_tracker silently becomes null and any
+        // later allocation on this thread would dereference it inside the
+        // allocator's memory check path, surfacing as a generic NPE far from
+        // the real call site that fed the null tracker. The query id is
+        // read from signal-handler thread-local storage; it does not depend
+        // on any object that may already be torn down. Note: do not call
+        // print_debug_string() here — it itself dereferences _limiter_tracker
+        // (via make_profile_str()), which on a fresh ThreadMemTrackerMgr is
+        // still null and would crash inside the format call before the
+        // intended FatalError is thrown.
+        throw Exception(Status::FatalError(
+                "ThreadMemTrackerMgr::attach_limiter_tracker called with null 
mem_tracker. "
+                "previous limiter label={}, snapshot_stack_depth={}, "
+                "query_id={:x}-{:x}",
+                _limiter_tracker ? _limiter_tracker->label() : "<null>",
+                _last_attach_snapshots_stack.size(), 
doris::signal::query_id_hi,
+                doris::signal::query_id_lo));
+    }
     CHECK(init());
     flush_untracked_mem();
     _last_attach_snapshots_stack.push_back(
@@ -55,7 +76,25 @@ void ThreadMemTrackerMgr::detach_limiter_tracker() {
     CHECK(init());
     flush_untracked_mem();
     shrink_reserved();
+    if (UNLIKELY(_last_attach_snapshots_stack.empty())) {
+        // detach_limiter_tracker() is invoked from RAII destructors that are
+        // noexcept; throwing would call std::terminate without a useful
+        // message. A LOG(FATAL) gives a controlled abort with a flushed
+        // message and a glog-captured stack trace.
+        LOG(FATAL) << "ThreadMemTrackerMgr::detach_limiter_tracker called with 
empty snapshot "
+                      "stack. current limiter label="
+                   << (_limiter_tracker ? _limiter_tracker->label() : "<null>")
+                   << ", query_id=" << std::hex << doris::signal::query_id_hi 
<< "-"
+                   << doris::signal::query_id_lo << std::dec;
+    }
     DCHECK(!_last_attach_snapshots_stack.empty());
+    if (UNLIKELY(!_last_attach_snapshots_stack.back().limiter_tracker)) {
+        // Same noexcept-destructor rationale as above.
+        LOG(FATAL) << "ThreadMemTrackerMgr::detach_limiter_tracker restored 
null limiter from "
+                      "snapshot. stack_depth_before_pop="
+                   << _last_attach_snapshots_stack.size() << ", query_id=" << 
std::hex
+                   << doris::signal::query_id_hi << "-" << 
doris::signal::query_id_lo << std::dec;
+    }
     _limiter_tracker_sptr = 
_last_attach_snapshots_stack.back().limiter_tracker;
     _limiter_tracker = _limiter_tracker_sptr.get();
     _wg_wptr = _last_attach_snapshots_stack.back().wg_wptr;
diff --git a/be/src/runtime/thread_context.cpp 
b/be/src/runtime/thread_context.cpp
index 7e8354f6ff6..83f38369d6c 100644
--- a/be/src/runtime/thread_context.cpp
+++ b/be/src/runtime/thread_context.cpp
@@ -25,6 +25,35 @@ namespace doris {
 class MemTracker;
 
 void AttachTask::init(const std::shared_ptr<ResourceContext>& rc) {
+    // Validate the ResourceContext chain before mutating any thread-local
+    // or signal state. If any link is null we throw immediately, so the
+    // caller's stack-unwind sees a clean state (no thread-local handle is
+    // acquired and no signal task id is set). Without these the previous
+    // code would silently propagate a null mem_tracker into
+    // ThreadMemTrackerMgr and crash much later inside the allocator.
+    if (UNLIKELY(rc == nullptr)) {
+        throw Exception(
+                Status::FatalError("AttachTask::init: rc is null. 
signal_query_id={:x}-{:x}",
+                                   signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->memory_context() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask::init: rc->memory_context() is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->memory_context()->mem_tracker() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask::init: rc->memory_context()->mem_tracker() is 
null. "
+                "ResourceContext was created but set_mem_tracker has not been 
called yet "
+                "(likely a half-initialized QueryContext used before 
_init_query_mem_tracker). "
+                "signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->task_controller() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask::init: rc->task_controller() is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
     ThreadLocalHandle::create_thread_local_if_not_exits();
     signal::set_signal_task_id(rc->task_controller()->task_id());
     thread_context()->attach_task(rc);
@@ -38,17 +67,52 @@ AttachTask::AttachTask(const 
std::shared_ptr<MemTrackerLimiter>& mem_tracker) {
     // if parameter is `orphan_mem_tracker`, if you do not switch thraed mem 
tracker afterwards,
     // alloc or free memory from Allocator will fail DCHECK. unless you know 
for sure that
     // the thread will not alloc or free memory from Allocator later.
+    //
+    // Validate before constructing the ResourceContext: 
MemoryContext::set_mem_tracker()
+    // immediately dereferences mem_tracker->limit(), so a null shared_ptr 
would
+    // crash there before reaching init()'s diagnostics.
+    if (UNLIKELY(mem_tracker == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask(MemTrackerLimiter): mem_tracker is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
     std::shared_ptr<ResourceContext> rc = ResourceContext::create_shared();
     rc->memory_context()->set_mem_tracker(mem_tracker);
     init(rc);
 }
 
 AttachTask::AttachTask(RuntimeState* runtime_state) {
+    // Walk the chain `runtime_state -> get_query_ctx() -> resource_ctx()`
+    // step by step so that an unexpected null pinpoints exactly which link
+    // failed instead of crashing with a generic NPE inside attach_task() or
+    // even later inside the allocator.
+    if (UNLIKELY(runtime_state == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask(RuntimeState*): runtime_state is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(runtime_state->get_query_ctx() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask(RuntimeState*): runtime_state->get_query_ctx() is 
null. "
+                "signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(runtime_state->get_query_ctx()->resource_ctx() == nullptr)) {
+        throw Exception(
+                Status::FatalError("AttachTask(RuntimeState*): 
query_ctx->resource_ctx() is null. "
+                                   "signal_query_id={:x}-{:x}",
+                                   signal::query_id_hi, signal::query_id_lo));
+    }
     signal::set_signal_is_nereids(runtime_state->is_nereids());
     init(runtime_state->get_query_ctx()->resource_ctx());
 }
 
 AttachTask::AttachTask(QueryContext* query_ctx) {
+    if (UNLIKELY(query_ctx == nullptr)) {
+        throw Exception(Status::FatalError(
+                "AttachTask(QueryContext*): query_ctx is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
     init(query_ctx->resource_ctx());
 }
 
@@ -60,6 +124,33 @@ AttachTask::~AttachTask() {
 
 SwitchResourceContext::SwitchResourceContext(const 
std::shared_ptr<ResourceContext>& rc) {
     DCHECK(rc != nullptr);
+    // Validate the chain before mutating any thread-local or signal state,
+    // symmetric to AttachTask::init(). Throwing after the thread-local
+    // handle was acquired or the signal task id was set would skip this
+    // object's destructor (because construction failed) and leak the
+    // handle / leave a stale signal task id behind.
+    if (UNLIKELY(rc == nullptr)) {
+        throw Exception(
+                Status::FatalError("SwitchResourceContext: rc is null. 
signal_query_id={:x}-{:x}",
+                                   signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->memory_context() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "SwitchResourceContext: rc->memory_context() is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->memory_context()->mem_tracker() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "SwitchResourceContext: rc->memory_context()->mem_tracker() is 
null. "
+                "ResourceContext was switched in before 
_init_query_mem_tracker ran. "
+                "signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
+    if (UNLIKELY(rc->task_controller() == nullptr)) {
+        throw Exception(Status::FatalError(
+                "SwitchResourceContext: rc->task_controller() is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
     doris::ThreadLocalHandle::create_thread_local_if_not_exits();
     DCHECK(thread_context()->is_attach_task());
     old_resource_ctx_ = thread_context()->resource_ctx();
@@ -84,6 +175,16 @@ SwitchResourceContext::~SwitchResourceContext() {
 SwitchThreadMemTrackerLimiter::SwitchThreadMemTrackerLimiter(
         const std::shared_ptr<doris::MemTrackerLimiter>& mem_tracker) {
     DCHECK(mem_tracker);
+    // Third entry point that calls attach_limiter_tracker(). Without this
+    // null guard a null mem_tracker silently propagates and the next
+    // allocation on this thread would NPE deep inside the allocator. Throw
+    // before acquiring the thread-local handle / doing any side effect so
+    // the destructor (which is noexcept) never runs in a dirty state.
+    if (UNLIKELY(mem_tracker == nullptr)) {
+        throw Exception(Status::FatalError(
+                "SwitchThreadMemTrackerLimiter: mem_tracker is null. 
signal_query_id={:x}-{:x}",
+                signal::query_id_hi, signal::query_id_lo));
+    }
     doris::ThreadLocalHandle::create_thread_local_if_not_exits();
     if (mem_tracker != 
thread_context()->thread_mem_tracker_mgr->limiter_mem_tracker_sptr()) {
         
thread_context()->thread_mem_tracker_mgr->attach_limiter_tracker(mem_tracker);
diff --git a/be/src/runtime/thread_context.h b/be/src/runtime/thread_context.h
index 54e565cc424..332cd0f6545 100644
--- a/be/src/runtime/thread_context.h
+++ b/be/src/runtime/thread_context.h
@@ -168,6 +168,11 @@ public:
     void attach_task(const std::shared_ptr<ResourceContext>& rc) {
         // will only attach_task at the beginning of the thread function, 
there should be no duplicate attach_task.
         DCHECK(resource_ctx_ == nullptr);
+        // Validation of `rc` and its sub-objects is performed by the
+        // AttachTask::init() / SwitchResourceContext constructor entry
+        // points before any thread-local or signal mutation, so a thrown
+        // FatalError does not leak thread-local handle counts or leave a
+        // stale signal task id behind.
         resource_ctx_ = rc;
         
thread_mem_tracker_mgr->attach_limiter_tracker(rc->memory_context()->mem_tracker(),
                                                        rc->workload_group());


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to