hello-stephen commented on code in PR #71359:
URL: https://github.com/apache/doris/pull/71359#discussion_r4783972519


##########
be/src/runtime/fragment_mgr.cpp:
##########
@@ -1346,43 +1360,113 @@ Status FragmentMgr::rerun_fragment(const 
std::shared_ptr<brpc::ClosureGuard>& gu
                     print_id(query_id));
         }
         SCOPED_ATTACH_TASK(q_ctx.get());
-        RerunableFragmentInfo info;
+        // Keep owning snapshots outside lock scopes: their destruction can 
re-enter
+        // FragmentMgr through QueryContext/PFC cleanup.
+        TPipelineFragmentParams params;
+        FinishCallback finish_callback;
+        std::set<int> deregister_ids;
+        uint32_t next_stage = 0;
+        std::shared_ptr<PipelineFragmentContext> old_context;
         {
-            std::lock_guard<std::mutex> lk(_rerunnable_params_lock);
+            std::lock_guard lock(_rerunnable_params_lock);
             auto it = _rerunnable_params_map.find({query_id, fragment_id});
             if (it == _rerunnable_params_map.end()) {
                 return Status::NotFound("rebuild (query-id: {}, fragment-id: 
{}) not found",
                                         print_id(query_id), fragment_id);
             }
-            it->second.stage++;
-            // Deregister old runtime filters so new ones can be registered in 
the new PFC.
-            for (int32_t filter_id : it->second.deregister_runtime_filter_ids) 
{
-                q_ctx->runtime_filter_mgr()->remove_filter(filter_id);
+            auto& info = it->second;
+            if (target_round) {
+                auto [round_it, inserted] =
+                        
info.completed_rounds.try_emplace(target_round->controller_node_id, 0);
+                RETURN_IF_ERROR(target_round->check_after(round_it->second));
+                // A delayed replay can arrive after SUBMIT or after the next 
WAIT.
+                // It must not deregister RFs or create another PFC in either 
case.
+                if (target_round->round <= round_it->second) {
+                    return Status::OK();
+                }
             }
-            info = it->second;
+            // Never ACK a not-yet-prepared rebuild or overwrite a live PFC. 
Legacy
+            // requests also need this guard, even though they cannot identify 
replays.
+            old_context = _pipeline_map.find({query_id, fragment_id});
+            if (info.rebuild_in_progress || old_context) {
+                return Status::InvalidArgument("Recursive CTE rebuild requires 
completed WAIT");
+            }
+            if (info.stage == std::numeric_limits<uint32_t>::max()) {
+                return Status::InvalidArgument("Recursive CTE fragment stage 
overflow");
+            }
+            params = info.params;
+            finish_callback = info.finish_callback;
+            deregister_ids = info.deregister_runtime_filter_ids;
+            next_stage = info.stage + 1;
+            info.rebuild_in_progress = true;
         }
-
-        auto context = std::make_shared<PipelineFragmentContext>(
-                q_ctx->query_id(), info.params, q_ctx, _exec_env, 
info.finish_callback);
-        // Propagate the recursion stage so that runtime filters created by 
this PFC
-        // carry the correct stage number.
-        context->set_rec_cte_stage(info.stage);
-
+        bool owns_reservation = true;
+        Defer release_reservation([&] {
+            if (!owns_reservation) return;
+            std::lock_guard lock(_rerunnable_params_lock);
+            auto it = _rerunnable_params_map.find({query_id, fragment_id});
+            // Query removal may have detached this entry during prepare.
+            if (it != _rerunnable_params_map.end()) {
+                it->second.rebuild_in_progress = false;
+            }
+        });
+        for (int filter_id : deregister_ids) {
+            q_ctx->runtime_filter_mgr()->remove_filter(filter_id);
+        }
+        auto context = 
std::make_shared<PipelineFragmentContext>(q_ctx->query_id(), params, q_ctx,
+                                                                 _exec_env, 
finish_callback);
+        // Registration during prepare must see the new data stage, not the 
default 0.
+        context->set_rec_cte_stage(next_stage);
         Status prepare_st = Status::OK();
-        ASSIGN_STATUS_IF_CATCH_EXCEPTION(prepare_st = 
context->prepare(_thread_pool.get()),
-                                         prepare_st);
+        ASSIGN_STATUS_IF_CATCH_EXCEPTION(
+                prepare_st = 
SYNC_POINT_HOOK_RETURN_VALUE(context->prepare(_thread_pool.get()),
+                                                          
"FragmentMgr::rebuild:prepare"),
+                prepare_st);
         if (!prepare_st.ok()) {
             q_ctx->cancel(prepare_st);
             return prepare_st;
         }
 
-        // Insert new PFC into _pipeline_map (old one was removed)
-        _pipeline_map.insert({info.params.query_id, info.params.fragment_id}, 
context);
-        increment_fragment_executing_count();
-
-        // Update QueryContext mapping (must support overwrite)
-        q_ctx->set_pipeline_context(info.params.fragment_id, context);
-        return Status::OK();
+        bool published = false;
+        bool committed = false;
+        Status publish_st = Status::OK();
+        Defer rollback([&] {
+            // Removal/destruction and counter cleanup must run outside the 
params lock.
+            if (published && !committed) {
+                remove_pipeline_context({query_id, fragment_id});
+            }
+        });
+        {
+            std::lock_guard lock(_rerunnable_params_lock);
+            auto it = _rerunnable_params_map.find({query_id, fragment_id});
+            // Do not resurrect a query removed while this request was 
preparing.
+            if (it == _rerunnable_params_map.end()) {
+                return Status::NotFound("Recursive CTE rebuild was removed 
during prepare");
+            }
+            DORIS_CHECK(it->second.rebuild_in_progress);
+            if (q_ctx->is_cancelled()) {
+                return q_ctx->exec_status();
+            }
+            // Unlike ordinary insert callers, REBUILD must observe insertion 
failure
+            // so it cannot increase the executing count for an existing map 
entry.
+            if (!_pipeline_map.insert({query_id, fragment_id}, context)) {
+                return Status::InternalError("Recursive CTE rebuild conflicts 
with existing PFC");
+            }
+            increment_fragment_executing_count();
+            published = true;
+            publish_st = q_ctx->set_pipeline_context(fragment_id, context, 
true);

Review Comment:
   [P2] Clean up a rebuilt fragment if the round aborts before SUBMIT. The new 
registration check handles cancellation that has already started, but 
successful registration does not make an unsubmitted PFC cancellable to 
completion. For example, this driver REBUILDs all child fragments before 
sending any SUBMIT; if a later child returns the new in-progress REBUILD error, 
the driver exits without submitting the earlier, successfully published PFCs 
(rec_cte_source_operator.h:257–266). For those PFCs, prepare has created tasks 
and incremented _total_tasks, but only PipelineFragmentContext::submit queues 
them. QueryContext::cancel finds the PFC; PipelineFragmentContext::notify_close 
only removes it when _closed_tasks >= _total_tasks, and cancel merely unblocks 
dependencies, which cannot schedule tasks that have never run or registered as 
blocked. FragmentMgr::cancel_query removes the query/rerunnable metadata, not 
these pipeline map entries. Consequently the PFC, tasks, QueryContext an
 d executing-fragment count remain retained. The underlying pre-SUBMIT cleanup 
gap predates this PR, but the new explicit rebuild rejection adds a path into 
it and the added cancellation checks don't close it. Please coordinate 
cancellation of prepared-but-not-submitted PFCs with SUBMIT (so they are 
removed or their tasks are guaranteed to finish), and test cancellation after 
successful REBUILD with real prepared tasks; the new fixture skips prepare and 
manually erases its PFCs.



-- 
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