Copilot commented on code in PR #61806:
URL: https://github.com/apache/doris/pull/61806#discussion_r2999402447


##########
be/src/runtime/task_execution_context.h:
##########
@@ -19,14 +19,20 @@
 
 #include <memory>
 
+#include "runtime/runtime_state.h"
+

Review Comment:
   `task_execution_context.h` includes `runtime_state.h` but only needs a 
forward declaration for `RuntimeState` (the constructor is defined in the 
.cpp). This introduces an unnecessary include cycle (`runtime_state.h` already 
includes `task_execution_context.h`) and increases compile-time coupling. 
Prefer removing the include and keeping only the forward declaration.



##########
be/src/exec/runtime_filter/runtime_filter_consumer.h:
##########
@@ -86,17 +86,18 @@ class RuntimeFilterConsumer : public RuntimeFilter {
     }
 
 private:
-    RuntimeFilterConsumer(const QueryContext* query_ctx, const 
TRuntimeFilterDesc* desc,
-                          int node_id)
+    RuntimeFilterConsumer(const RuntimeState* state, const TRuntimeFilterDesc* 
desc, int node_id)
             : RuntimeFilter(desc),
               _probe_expr(desc->planId_to_target_expr.find(node_id)->second),
               _registration_time(MonotonicMillis()),
               _rf_state(State::NOT_READY) {
+        auto* query_ctx = state->get_query_ctx();
         // If bitmap filter is not applied, it will cause the query result to 
be incorrect
         // local rf must wait until timeout, otherwise it may lead results 
incorrectness, because LEFT_SEMI_DIRECT_RETURN_OPT
         bool wait_infinitely = query_ctx->runtime_filter_wait_infinitely() ||
                                _runtime_filter_type == 
RuntimeFilterType::BITMAP_FILTER ||
-                               !has_remote_target();
+                               !has_remote_target() ||
+                               state->force_make_rf_wait_infinite();
         _rf_wait_time_ms = wait_infinitely ? query_ctx->execution_timeout() * 
1000
                                            : 
query_ctx->runtime_filter_wait_time_ms();
         DorisMetrics::instance()->runtime_filter_consumer_num->increment(1);

Review Comment:
   `RuntimeFilterConsumer` now calls 
`query_ctx->runtime_filter_wait_infinitely()`, but that method was removed from 
`QueryContext` in this PR. This will fail to compile. Use 
`RuntimeState::runtime_filter_wait_infinitely()` (already added) or reintroduce 
a `QueryContext` accessor delegating to `_query_options`.



##########
be/src/runtime/query_context.h:
##########
@@ -297,6 +293,23 @@ class QueryContext : public 
std::enable_shared_from_this<QueryContext> {
     void set_first_error_msg(std::string error_msg);
     std::string get_first_error_msg();
 
+    Status send_block_to_cte_scan(const TUniqueId& instance_id, int node_id,
+                                  const 
google::protobuf::RepeatedPtrField<doris::PBlock>& pblocks,
+                                  bool eos);
+    void registe_cte_scan(const TUniqueId& instance_id, int node_id,
+                          pipeline::RecCTEScanLocalState* scan);
+    void deregiste_cte_scan(const TUniqueId& instance_id, int node_id);

Review Comment:
   Method names `registe_cte_scan` / `deregiste_cte_scan` (and related DCHECK 
messages) contain spelling errors and are inconsistent with the codebase’s 
typical `register_*`/`deregister_*` naming. Since these are new public methods 
on `QueryContext`, consider renaming them to avoid propagating the typo into 
call sites and logs.



##########
be/src/exec/operator/rec_cte_source_operator.h:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+#pragma once
+
+#include <gen_cpp/internal_service.pb.h>
+
+#include "common/status.h"
+#include "operator.h"
+#include "exec/operator/union_sink_operator.h"
+#include "exec/pipeline/rec_cte_shared_state.h"
+#include "util/brpc_client_cache.h"
+#include "util/uid_util.h"
+#include "core/block/block.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+class RuntimeState;
+
+class DataQueue;
+
+class RecCTESourceOperatorX;
+class RecCTESourceLocalState final : public 
PipelineXLocalState<RecCTESharedState> {
+public:
+    ENABLE_FACTORY_CREATOR(RecCTESourceLocalState);
+    using Base = PipelineXLocalState<RecCTESharedState>;
+    using Parent = RecCTESourceOperatorX;
+    RecCTESourceLocalState(RuntimeState* state, OperatorXBase* parent);
+
+    Status open(RuntimeState* state) override;
+    Status init(RuntimeState* state, LocalStateInfo& info) override;
+
+    bool is_blockable() const override { return true; }
+
+    std::vector<Dependency*> dependencies() const override {
+        return std::vector<Dependency*> {_dependency, 
_anchor_dependency.get()};
+    }
+
+private:
+    friend class RecCTESourceOperatorX;
+    friend class OperatorX<RecCTESourceLocalState>;
+
+    std::shared_ptr<Dependency> _anchor_dependency = nullptr;
+};
+
+// RecCTESourceOperatorX drives the recursive CTE fragment rerun lifecycle.
+//
+// It orchestrates child fragment destruction and recreation for each 
recursion round
+// via the rerun_fragment RPC (defined in internal_service.proto). The 4 
opcodes are:
+//
+//   wait_for_destroy (=1) : notify old PFC to close, async wait for tasks to 
finish
+//   rebuild          (=2) : increment stage, deregister old runtime filters, 
create new PFC
+//   submit           (=3) : submit new PFC pipeline tasks for execution
+//   final_close      (=4) : last round cleanup, send final report, destroy 
fragment
+//
+// State Transition Diagram
+// ========================
+//
+//   ┌────────────────────────────────────┐
+//   │          Query Start (FE)          │
+//   │  FE sets need_notify_close = true  │
+//   │  on recursive-side child fragments │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │      Initial Registration (BE)     │
+//   │  FragmentMgr saves params in       │
+//   │  _rerunnable_params_map            │
+//   │  PFC created, prepared & submitted │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │        Fragment Running            │
+//   │  PFC executing pipeline tasks      │◄─────────────────────────────┐
+//   │  _need_notify_close = true         │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  │ tasks complete, but PFC does NOT                   │
+//                  │ self-remove (blocked by _need_notify_close)        │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │  RecCTESourceOperatorX::get_block()│                              │
+//   │  ready_to_return? round < max?     │                              │
+//   └───────┬─────────────────┬──────────┘                              │
+//           │                 │                                         │
+//   more rounds remain   no more rounds                                │
+//           │                 │                                         │
+//           ▼                 │                                         │
+//   ┌──────────────────┐     │                                         │
+//   │_recursive_process│     │                                         │
+//   └───────┬──────────┘     │                                         │
+//           │                │                                         │
+//           ▼                │                                         │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1: wait_for_destroy (=1)      │                              │
+//   │  • collect deregister RF IDs       │                              │
+//   │  • store brpc closure guard        │                              │
+//   │  • notify_close() on old PFC       │                              │
+//   │    → _need_notify_close = false    │                              │
+//   │    → old PFC begins shutdown       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1.5: reset_global_rf          │                              │
+//   │  • reset global runtime filters    │                              │
+//   │    on merge coordinator            │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 2: rebuild (=2)               │                              │
+//   │  • increment recursion stage       │                              │
+//   │  • deregister old runtime filters  │                              │
+//   │  • create NEW PFC from saved params│                              │
+//   │  • prepare() new PFC              │                              │
+//   │  • insert into _pipeline_map       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 3: submit (=3)                │                              │
+//   │  • find new PFC in pipeline_map    │                              │
+//   │  • call fragment_ctx->submit()     │                              │
+//   │  • pipeline tasks start running    │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 4: send_data_to_targets       │                              │
+//   │  • transmit_rec_cte_block() to     │                              │
+//   │    RecursiveCteScanNode targets    │                              │
+//   │  • new recursion round begins      │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  └──── loop back to Fragment Running ─────────────────┘
+//
+//           (when no more rounds remain)
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │ final_close (=4)                   │
+//   │  • listen_wait_close(guard,        │
+//   │    need_send_report = true)        │
+//   │  • notify_close() on PFC           │
+//   │  • send final status report        │
+//   │  • clean up completely             │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │       Fragment Destroyed           │
+//   │  rerunnable_params removed on      │
+//   │  query end                         │
+//   └────────────────────────────────────┘
+//
+class RecCTESourceOperatorX : public OperatorX<RecCTESourceLocalState> {
+public:
+    using Base = OperatorX<RecCTESourceLocalState>;
+    RecCTESourceOperatorX(ObjectPool* pool, const TPlanNode& tnode, int 
operator_id,
+                          const DescriptorTbl& descs)
+            : Base(pool, tnode, operator_id, descs),
+              _is_union_all(tnode.rec_cte_node.is_union_all),
+              _targets(tnode.rec_cte_node.targets),
+              _fragments_to_reset(tnode.rec_cte_node.fragments_to_reset),
+              _global_rf_ids(tnode.rec_cte_node.rec_side_runtime_filter_ids),
+              
_is_used_by_other_rec_cte(tnode.rec_cte_node.is_used_by_other_rec_cte) {
+        DCHECK(tnode.__isset.rec_cte_node);
+    }
+    ~RecCTESourceOperatorX() override = default;
+
+    Status init(const TPlanNode& tnode, RuntimeState* state) override;
+    Status prepare(RuntimeState* state) override;
+
+    Status terminate(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::terminate(state);
+    }
+
+    Status close(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::close(state);
+    }
+
+    Status set_child(OperatorPtr child) override {
+        Base::_child = child;
+        return Status::OK();
+    }
+
+    bool is_serial_operator() const override { return true; }
+
+    DataDistribution required_data_distribution(RuntimeState* /*state*/) const 
override {
+        return {ExchangeType::NOOP};
+    }
+
+    Status get_block(RuntimeState* state, Block* block, bool* eos) override {
+        auto& local_state = get_local_state(state);
+        auto& ctx = local_state._shared_state;
+        ctx->update_ready_to_return();
+
+        if (!ctx->ready_to_return) {
+            if (ctx->current_round + 1 > _max_recursion_depth) {

Review Comment:
   The recursion-depth guard aborts when `_max_recursion_depth` is 0. Since 
`RuntimeState::cte_max_recursion_depth()` returns 0 when the query option is 
unset, this would abort recursive CTEs by default unless FE always populates 
the option. Consider treating 0 as "no limit" (or applying a sensible default) 
and only enforcing the check when the configured depth is > 0.
   ```suggestion
               if (_max_recursion_depth > 0 && ctx->current_round + 1 > 
_max_recursion_depth) {
   ```



##########
be/src/exec/runtime_filter/runtime_filter_mgr.cpp:
##########
@@ -433,11 +468,44 @@ Status 
RuntimeFilterMergeControllerEntity::_send_rf_to_target(GlobalMergeContext
     return st;
 }
 
+// Reset merge context for the next recursive CTE round.
+// Recreates the merger to clear accumulated state, preserving expected 
producer count.
+// Increments the stage counter so stale merge/size RPCs from old rounds are 
discarded.
+Status GlobalMergeContext::reset(QueryContext* query_ctx) {
+    std::unique_lock<std::mutex> lock(mtx);
+    // Merger must exist: reset() is only called on fully initialized merge 
contexts.
+    DORIS_CHECK(merger);
+    int producer_size = merger->get_expected_producer_num();
+    RETURN_IF_ERROR(RuntimeFilterMerger::create(query_ctx, 
&runtime_filter_desc, &merger));
+    merger->set_expected_producer_num(producer_size);
+    arrive_id.clear();
+    source_addrs.clear();
+    done = false;
+    stage++;
+    // Keep the Merger's own stage in sync for consistent debug output.
+    merger->set_stage(stage);
+    return Status::OK();
+}
+
+Status RuntimeFilterMergeControllerEntity::reset_global_rf(
+        QueryContext* query_ctx, const 
google::protobuf::RepeatedField<int32_t>& filter_ids) {
+    for (const auto& filter_id : filter_ids) {
+        GlobalMergeContext* cnt_val;
+        {
+            std::unique_lock<std::shared_mutex> guard(_filter_map_mutex);
+            cnt_val = &_filter_map[filter_id]; // may inplace construct 
default object
+        }
+        RETURN_IF_ERROR(cnt_val->reset(query_ctx));
+    }
+    return Status::OK();

Review Comment:
   `RuntimeFilterMergeControllerEntity::reset_global_rf()` uses 
`_filter_map[filter_id]`, which will default-construct a `GlobalMergeContext` 
when `filter_id` is missing. The subsequent `cnt_val->reset()` then hits 
`DORIS_CHECK(merger)` and can crash the BE if an unexpected/unknown filter id 
is passed. Avoid `operator[]` here: look up with `find()` and either return 
`NotFound` (or skip gracefully) when the filter id is not present; also 
consider guarding `debug_string()` against `ctx.merger == nullptr` for the same 
reason.



##########
be/src/exec/operator/rec_cte_source_operator.h:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+#pragma once
+
+#include <gen_cpp/internal_service.pb.h>
+
+#include "common/status.h"
+#include "operator.h"
+#include "exec/operator/union_sink_operator.h"
+#include "exec/pipeline/rec_cte_shared_state.h"
+#include "util/brpc_client_cache.h"
+#include "util/uid_util.h"
+#include "core/block/block.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+class RuntimeState;
+
+class DataQueue;
+
+class RecCTESourceOperatorX;
+class RecCTESourceLocalState final : public 
PipelineXLocalState<RecCTESharedState> {
+public:
+    ENABLE_FACTORY_CREATOR(RecCTESourceLocalState);
+    using Base = PipelineXLocalState<RecCTESharedState>;
+    using Parent = RecCTESourceOperatorX;
+    RecCTESourceLocalState(RuntimeState* state, OperatorXBase* parent);
+
+    Status open(RuntimeState* state) override;
+    Status init(RuntimeState* state, LocalStateInfo& info) override;
+
+    bool is_blockable() const override { return true; }
+
+    std::vector<Dependency*> dependencies() const override {
+        return std::vector<Dependency*> {_dependency, 
_anchor_dependency.get()};
+    }
+
+private:
+    friend class RecCTESourceOperatorX;
+    friend class OperatorX<RecCTESourceLocalState>;
+
+    std::shared_ptr<Dependency> _anchor_dependency = nullptr;
+};
+
+// RecCTESourceOperatorX drives the recursive CTE fragment rerun lifecycle.
+//
+// It orchestrates child fragment destruction and recreation for each 
recursion round
+// via the rerun_fragment RPC (defined in internal_service.proto). The 4 
opcodes are:
+//
+//   wait_for_destroy (=1) : notify old PFC to close, async wait for tasks to 
finish
+//   rebuild          (=2) : increment stage, deregister old runtime filters, 
create new PFC
+//   submit           (=3) : submit new PFC pipeline tasks for execution
+//   final_close      (=4) : last round cleanup, send final report, destroy 
fragment
+//
+// State Transition Diagram
+// ========================
+//
+//   ┌────────────────────────────────────┐
+//   │          Query Start (FE)          │
+//   │  FE sets need_notify_close = true  │
+//   │  on recursive-side child fragments │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │      Initial Registration (BE)     │
+//   │  FragmentMgr saves params in       │
+//   │  _rerunnable_params_map            │
+//   │  PFC created, prepared & submitted │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │        Fragment Running            │
+//   │  PFC executing pipeline tasks      │◄─────────────────────────────┐
+//   │  _need_notify_close = true         │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  │ tasks complete, but PFC does NOT                   │
+//                  │ self-remove (blocked by _need_notify_close)        │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │  RecCTESourceOperatorX::get_block()│                              │
+//   │  ready_to_return? round < max?     │                              │
+//   └───────┬─────────────────┬──────────┘                              │
+//           │                 │                                         │
+//   more rounds remain   no more rounds                                │
+//           │                 │                                         │
+//           ▼                 │                                         │
+//   ┌──────────────────┐     │                                         │
+//   │_recursive_process│     │                                         │
+//   └───────┬──────────┘     │                                         │
+//           │                │                                         │
+//           ▼                │                                         │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1: wait_for_destroy (=1)      │                              │
+//   │  • collect deregister RF IDs       │                              │
+//   │  • store brpc closure guard        │                              │
+//   │  • notify_close() on old PFC       │                              │
+//   │    → _need_notify_close = false    │                              │
+//   │    → old PFC begins shutdown       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1.5: reset_global_rf          │                              │
+//   │  • reset global runtime filters    │                              │
+//   │    on merge coordinator            │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 2: rebuild (=2)               │                              │
+//   │  • increment recursion stage       │                              │
+//   │  • deregister old runtime filters  │                              │
+//   │  • create NEW PFC from saved params│                              │
+//   │  • prepare() new PFC              │                              │
+//   │  • insert into _pipeline_map       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 3: submit (=3)                │                              │
+//   │  • find new PFC in pipeline_map    │                              │
+//   │  • call fragment_ctx->submit()     │                              │
+//   │  • pipeline tasks start running    │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 4: send_data_to_targets       │                              │
+//   │  • transmit_rec_cte_block() to     │                              │
+//   │    RecursiveCteScanNode targets    │                              │
+//   │  • new recursion round begins      │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  └──── loop back to Fragment Running ─────────────────┘
+//
+//           (when no more rounds remain)
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │ final_close (=4)                   │
+//   │  • listen_wait_close(guard,        │
+//   │    need_send_report = true)        │
+//   │  • notify_close() on PFC           │
+//   │  • send final status report        │
+//   │  • clean up completely             │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │       Fragment Destroyed           │
+//   │  rerunnable_params removed on      │
+//   │  query end                         │
+//   └────────────────────────────────────┘
+//
+class RecCTESourceOperatorX : public OperatorX<RecCTESourceLocalState> {
+public:
+    using Base = OperatorX<RecCTESourceLocalState>;
+    RecCTESourceOperatorX(ObjectPool* pool, const TPlanNode& tnode, int 
operator_id,
+                          const DescriptorTbl& descs)
+            : Base(pool, tnode, operator_id, descs),
+              _is_union_all(tnode.rec_cte_node.is_union_all),
+              _targets(tnode.rec_cte_node.targets),
+              _fragments_to_reset(tnode.rec_cte_node.fragments_to_reset),
+              _global_rf_ids(tnode.rec_cte_node.rec_side_runtime_filter_ids),
+              
_is_used_by_other_rec_cte(tnode.rec_cte_node.is_used_by_other_rec_cte) {
+        DCHECK(tnode.__isset.rec_cte_node);
+    }
+    ~RecCTESourceOperatorX() override = default;
+
+    Status init(const TPlanNode& tnode, RuntimeState* state) override;
+    Status prepare(RuntimeState* state) override;
+
+    Status terminate(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::terminate(state);
+    }
+
+    Status close(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::close(state);
+    }
+
+    Status set_child(OperatorPtr child) override {
+        Base::_child = child;
+        return Status::OK();
+    }
+
+    bool is_serial_operator() const override { return true; }
+
+    DataDistribution required_data_distribution(RuntimeState* /*state*/) const 
override {
+        return {ExchangeType::NOOP};
+    }
+
+    Status get_block(RuntimeState* state, Block* block, bool* eos) override {
+        auto& local_state = get_local_state(state);
+        auto& ctx = local_state._shared_state;
+        ctx->update_ready_to_return();
+
+        if (!ctx->ready_to_return) {
+            if (ctx->current_round + 1 > _max_recursion_depth) {
+                return Status::Aborted("reach cte_max_recursion_depth {}", 
_max_recursion_depth);
+            }
+
+            ctx->source_dep->block();
+            // ctx->blocks.size() may be changed after _recursive_process
+            int current_blocks_size = int(ctx->blocks.size());
+            RETURN_IF_ERROR(_recursive_process(state, ctx->last_round_offset));
+            ctx->current_round++;
+            ctx->last_round_offset = current_blocks_size;
+        } else {
+            if (ctx->blocks.empty()) {
+                *eos = true;
+            } else {
+                block->swap(ctx->blocks.back());
+                RETURN_IF_ERROR(
+                        local_state.filter_block(local_state.conjuncts(), 
block, block->columns()));
+                ctx->blocks.pop_back();
+            }
+        }
+        return Status::OK();
+    }
+
+    bool is_source() const override { return true; }
+
+private:
+    Status _send_close(RuntimeState* state) {
+        if (!_already_send_close && !_is_used_by_other_rec_cte) {
+            _already_send_close = true;
+            auto* round_counter = 
ADD_COUNTER(get_local_state(state).Base::custom_profile(),
+                                              "RecursiveRound", TUnit::UNIT);
+            
round_counter->set(int64_t(get_local_state(state)._shared_state->current_round));
+
+            RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::FINAL_CLOSE));
+        }
+        return Status::OK();
+    }
+
+    Status _recursive_process(RuntimeState* state, size_t last_round_offset) 
const {
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::WAIT_FOR_DESTROY));
+        RETURN_IF_ERROR(_send_reset_global_rf(state));
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::REBUILD));
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::SUBMIT));
+        
RETURN_IF_ERROR(get_local_state(state)._shared_state->send_data_to_targets(
+                state, last_round_offset));
+        return Status::OK();
+    }
+
+    Status _send_reset_global_rf(RuntimeState* state) const {
+        TNetworkAddress addr;
+        
RETURN_IF_ERROR(state->global_runtime_filter_mgr()->get_merge_addr(&addr));
+        auto stub =
+                
state->get_query_ctx()->exec_env()->brpc_internal_client_cache()->get_client(addr);
+        PResetGlobalRfParams request;
+        
request.mutable_query_id()->CopyFrom(UniqueId(state->query_id()).to_proto());
+        for (auto filter_id : _global_rf_ids) {
+            request.add_filter_ids(filter_id);
+        }
+
+        PResetGlobalRfResult result;
+        brpc::Controller controller;
+        controller.set_timeout_ms(
+                
get_execution_rpc_timeout_ms(state->get_query_ctx()->execution_timeout()));
+        stub->reset_global_rf(&controller, &request, &result, 
brpc::DoNothing());
+        brpc::Join(controller.call_id());
+        return Status::create(result.status());

Review Comment:
   `_send_reset_global_rf()` does not check whether `get_client(addr)` returned 
a valid stub, and it also ignores `controller.Failed()`. If the client cache 
cannot create a stub or the RPC fails, this can dereference null and/or 
silently treat transport errors as success. Add a null check for `stub` 
(similar to `RecCTESharedState::send_data_to_targets`) and return an error when 
`controller.Failed()` is true.



##########
be/src/exec/operator/rec_cte_source_operator.h:
##########
@@ -0,0 +1,331 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+#pragma once
+
+#include <gen_cpp/internal_service.pb.h>
+
+#include "common/status.h"
+#include "operator.h"
+#include "exec/operator/union_sink_operator.h"
+#include "exec/pipeline/rec_cte_shared_state.h"
+#include "util/brpc_client_cache.h"
+#include "util/uid_util.h"
+#include "core/block/block.h"
+
+namespace doris {
+#include "common/compile_check_begin.h"
+class RuntimeState;
+
+class DataQueue;
+
+class RecCTESourceOperatorX;
+class RecCTESourceLocalState final : public 
PipelineXLocalState<RecCTESharedState> {
+public:
+    ENABLE_FACTORY_CREATOR(RecCTESourceLocalState);
+    using Base = PipelineXLocalState<RecCTESharedState>;
+    using Parent = RecCTESourceOperatorX;
+    RecCTESourceLocalState(RuntimeState* state, OperatorXBase* parent);
+
+    Status open(RuntimeState* state) override;
+    Status init(RuntimeState* state, LocalStateInfo& info) override;
+
+    bool is_blockable() const override { return true; }
+
+    std::vector<Dependency*> dependencies() const override {
+        return std::vector<Dependency*> {_dependency, 
_anchor_dependency.get()};
+    }
+
+private:
+    friend class RecCTESourceOperatorX;
+    friend class OperatorX<RecCTESourceLocalState>;
+
+    std::shared_ptr<Dependency> _anchor_dependency = nullptr;
+};
+
+// RecCTESourceOperatorX drives the recursive CTE fragment rerun lifecycle.
+//
+// It orchestrates child fragment destruction and recreation for each 
recursion round
+// via the rerun_fragment RPC (defined in internal_service.proto). The 4 
opcodes are:
+//
+//   wait_for_destroy (=1) : notify old PFC to close, async wait for tasks to 
finish
+//   rebuild          (=2) : increment stage, deregister old runtime filters, 
create new PFC
+//   submit           (=3) : submit new PFC pipeline tasks for execution
+//   final_close      (=4) : last round cleanup, send final report, destroy 
fragment
+//
+// State Transition Diagram
+// ========================
+//
+//   ┌────────────────────────────────────┐
+//   │          Query Start (FE)          │
+//   │  FE sets need_notify_close = true  │
+//   │  on recursive-side child fragments │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │      Initial Registration (BE)     │
+//   │  FragmentMgr saves params in       │
+//   │  _rerunnable_params_map            │
+//   │  PFC created, prepared & submitted │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │        Fragment Running            │
+//   │  PFC executing pipeline tasks      │◄─────────────────────────────┐
+//   │  _need_notify_close = true         │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  │ tasks complete, but PFC does NOT                   │
+//                  │ self-remove (blocked by _need_notify_close)        │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │  RecCTESourceOperatorX::get_block()│                              │
+//   │  ready_to_return? round < max?     │                              │
+//   └───────┬─────────────────┬──────────┘                              │
+//           │                 │                                         │
+//   more rounds remain   no more rounds                                │
+//           │                 │                                         │
+//           ▼                 │                                         │
+//   ┌──────────────────┐     │                                         │
+//   │_recursive_process│     │                                         │
+//   └───────┬──────────┘     │                                         │
+//           │                │                                         │
+//           ▼                │                                         │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1: wait_for_destroy (=1)      │                              │
+//   │  • collect deregister RF IDs       │                              │
+//   │  • store brpc closure guard        │                              │
+//   │  • notify_close() on old PFC       │                              │
+//   │    → _need_notify_close = false    │                              │
+//   │    → old PFC begins shutdown       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 1.5: reset_global_rf          │                              │
+//   │  • reset global runtime filters    │                              │
+//   │    on merge coordinator            │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 2: rebuild (=2)               │                              │
+//   │  • increment recursion stage       │                              │
+//   │  • deregister old runtime filters  │                              │
+//   │  • create NEW PFC from saved params│                              │
+//   │  • prepare() new PFC              │                              │
+//   │  • insert into _pipeline_map       │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 3: submit (=3)                │                              │
+//   │  • find new PFC in pipeline_map    │                              │
+//   │  • call fragment_ctx->submit()     │                              │
+//   │  • pipeline tasks start running    │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  ▼                                                    │
+//   ┌────────────────────────────────────┐                              │
+//   │ Step 4: send_data_to_targets       │                              │
+//   │  • transmit_rec_cte_block() to     │                              │
+//   │    RecursiveCteScanNode targets    │                              │
+//   │  • new recursion round begins      │                              │
+//   └──────────────┬─────────────────────┘                              │
+//                  │                                                    │
+//                  └──── loop back to Fragment Running ─────────────────┘
+//
+//           (when no more rounds remain)
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │ final_close (=4)                   │
+//   │  • listen_wait_close(guard,        │
+//   │    need_send_report = true)        │
+//   │  • notify_close() on PFC           │
+//   │  • send final status report        │
+//   │  • clean up completely             │
+//   └──────────────┬─────────────────────┘
+//                  │
+//                  ▼
+//   ┌────────────────────────────────────┐
+//   │       Fragment Destroyed           │
+//   │  rerunnable_params removed on      │
+//   │  query end                         │
+//   └────────────────────────────────────┘
+//
+class RecCTESourceOperatorX : public OperatorX<RecCTESourceLocalState> {
+public:
+    using Base = OperatorX<RecCTESourceLocalState>;
+    RecCTESourceOperatorX(ObjectPool* pool, const TPlanNode& tnode, int 
operator_id,
+                          const DescriptorTbl& descs)
+            : Base(pool, tnode, operator_id, descs),
+              _is_union_all(tnode.rec_cte_node.is_union_all),
+              _targets(tnode.rec_cte_node.targets),
+              _fragments_to_reset(tnode.rec_cte_node.fragments_to_reset),
+              _global_rf_ids(tnode.rec_cte_node.rec_side_runtime_filter_ids),
+              
_is_used_by_other_rec_cte(tnode.rec_cte_node.is_used_by_other_rec_cte) {
+        DCHECK(tnode.__isset.rec_cte_node);
+    }
+    ~RecCTESourceOperatorX() override = default;
+
+    Status init(const TPlanNode& tnode, RuntimeState* state) override;
+    Status prepare(RuntimeState* state) override;
+
+    Status terminate(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::terminate(state);
+    }
+
+    Status close(RuntimeState* state) override {
+        RETURN_IF_ERROR(_send_close(state));
+        return Base::close(state);
+    }
+
+    Status set_child(OperatorPtr child) override {
+        Base::_child = child;
+        return Status::OK();
+    }
+
+    bool is_serial_operator() const override { return true; }
+
+    DataDistribution required_data_distribution(RuntimeState* /*state*/) const 
override {
+        return {ExchangeType::NOOP};
+    }
+
+    Status get_block(RuntimeState* state, Block* block, bool* eos) override {
+        auto& local_state = get_local_state(state);
+        auto& ctx = local_state._shared_state;
+        ctx->update_ready_to_return();
+
+        if (!ctx->ready_to_return) {
+            if (ctx->current_round + 1 > _max_recursion_depth) {
+                return Status::Aborted("reach cte_max_recursion_depth {}", 
_max_recursion_depth);
+            }
+
+            ctx->source_dep->block();
+            // ctx->blocks.size() may be changed after _recursive_process
+            int current_blocks_size = int(ctx->blocks.size());
+            RETURN_IF_ERROR(_recursive_process(state, ctx->last_round_offset));
+            ctx->current_round++;
+            ctx->last_round_offset = current_blocks_size;
+        } else {
+            if (ctx->blocks.empty()) {
+                *eos = true;
+            } else {
+                block->swap(ctx->blocks.back());
+                RETURN_IF_ERROR(
+                        local_state.filter_block(local_state.conjuncts(), 
block, block->columns()));
+                ctx->blocks.pop_back();
+            }
+        }
+        return Status::OK();
+    }
+
+    bool is_source() const override { return true; }
+
+private:
+    Status _send_close(RuntimeState* state) {
+        if (!_already_send_close && !_is_used_by_other_rec_cte) {
+            _already_send_close = true;
+            auto* round_counter = 
ADD_COUNTER(get_local_state(state).Base::custom_profile(),
+                                              "RecursiveRound", TUnit::UNIT);
+            
round_counter->set(int64_t(get_local_state(state)._shared_state->current_round));
+
+            RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::FINAL_CLOSE));
+        }
+        return Status::OK();
+    }
+
+    Status _recursive_process(RuntimeState* state, size_t last_round_offset) 
const {
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::WAIT_FOR_DESTROY));
+        RETURN_IF_ERROR(_send_reset_global_rf(state));
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::REBUILD));
+        RETURN_IF_ERROR(_send_rerun_fragments(state, 
PRerunFragmentParams::SUBMIT));
+        
RETURN_IF_ERROR(get_local_state(state)._shared_state->send_data_to_targets(
+                state, last_round_offset));
+        return Status::OK();
+    }
+
+    Status _send_reset_global_rf(RuntimeState* state) const {
+        TNetworkAddress addr;
+        
RETURN_IF_ERROR(state->global_runtime_filter_mgr()->get_merge_addr(&addr));
+        auto stub =
+                
state->get_query_ctx()->exec_env()->brpc_internal_client_cache()->get_client(addr);
+        PResetGlobalRfParams request;
+        
request.mutable_query_id()->CopyFrom(UniqueId(state->query_id()).to_proto());
+        for (auto filter_id : _global_rf_ids) {
+            request.add_filter_ids(filter_id);
+        }
+
+        PResetGlobalRfResult result;
+        brpc::Controller controller;
+        controller.set_timeout_ms(
+                
get_execution_rpc_timeout_ms(state->get_query_ctx()->execution_timeout()));
+        stub->reset_global_rf(&controller, &request, &result, 
brpc::DoNothing());
+        brpc::Join(controller.call_id());
+        return Status::create(result.status());
+    }
+
+    Status _send_rerun_fragments(RuntimeState* state, 
PRerunFragmentParams_Opcode stage) const {
+        for (auto fragment : _fragments_to_reset) {
+            auto stub =
+                    
state->get_query_ctx()->exec_env()->brpc_internal_client_cache()->get_client(
+                            fragment.addr);
+
+            PRerunFragmentParams request;
+            
request.mutable_query_id()->CopyFrom(UniqueId(state->query_id()).to_proto());
+            request.set_fragment_id(fragment.fragment_id);
+            request.set_stage(stage);
+
+            PRerunFragmentResult result;
+            brpc::Controller controller;
+            controller.set_timeout_ms(
+                    
get_execution_rpc_timeout_ms(state->get_query_ctx()->execution_timeout()));
+            stub->rerun_fragment(&controller, &request, &result, 
brpc::DoNothing());
+            brpc::Join(controller.call_id());

Review Comment:
   `_send_rerun_fragments()` dereferences `stub` without a null check. If 
`brpc_internal_client_cache()->get_client(fragment.addr)` returns null, this 
will crash. Add the same stub-null validation used elsewhere before issuing the 
RPC.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to