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


##########
be/test/exec/pipeline/spill_completion_failure_test.cpp:
##########
@@ -0,0 +1,540 @@
+// 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.
+
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <functional>
+#include <future>
+#include <memory>
+#include <stdexcept>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "common/config.h"
+#include "common/exception.h"
+#include "exec/operator/operator.h"
+#include "exec/operator/spill_utils.h"
+#include "exec/pipeline/dependency.h"
+#include "exec/pipeline/dummy_task_queue.h"
+#include "exec/pipeline/pipeline.h"
+#include "exec/pipeline/pipeline_fragment_context.h"
+#include "exec/pipeline/pipeline_task.h"
+#include "exec/pipeline/revokable_task.h"
+#include "exec/pipeline/thrift_builder.h"
+#include "exec/spill/spill_file.h"
+#include "load/stream_load/new_load_stream_mgr.h"
+#include "runtime/exec_env.h"
+#include "runtime/fragment_mgr.h"
+#include "runtime/workload_group/workload_group.h"
+#include "runtime/workload_group/workload_group_manager.h"
+#include "runtime/workload_management/query_task_controller.h"
+#include "testutil/mock/mock_runtime_state.h"
+#include "testutil/mock/mock_thread_mem_tracker_mgr.h"
+#include "util/defer_op.h"
+
+namespace doris {
+namespace {
+
+enum class FailureMode { NONE, STATUS, DORIS_EXCEPTION, STD_EXCEPTION };
+
+struct SpillStep {
+    Status run() {
+        ++calls;
+        switch (mode) {
+        case FailureMode::NONE:
+            return Status::OK();
+        case FailureMode::STATUS:
+            return failure;
+        case FailureMode::DORIS_EXCEPTION:
+            throw Exception(failure);
+        case FailureMode::STD_EXCEPTION:
+            throw std::runtime_error(std::string(failure.msg()));
+        }
+        __builtin_unreachable();
+    }
+
+    FailureMode mode = FailureMode::NONE;
+    Status failure = Status::IOError("original spill I/O failure");
+    int calls = 0;
+};
+
+class CompletionFailureSource final : public 
OperatorX<DummyOperatorLocalState> {
+public:
+    CompletionFailureSource() : OperatorX<DummyOperatorLocalState>(nullptr, 0, 
0) {}
+    bool is_source() const override { return true; }
+    Status get_block_impl(RuntimeState*, Block*, bool* eos) override {
+        *eos = true;
+        return Status::OK();
+    }
+    size_t revocable_mem_size(RuntimeState*) const override {
+        return SpillFile::MIN_SPILL_WRITE_BATCH_MEM + 1;
+    }
+    Status revoke_memory(RuntimeState*) override { return revoke.run(); }
+    Status terminate(RuntimeState*) override { return termination.run(); }
+    SpillStep revoke;
+    SpillStep termination;
+};
+
+class CompletionFailureSink final : public 
DataSinkOperatorX<DummySinkLocalState> {
+public:
+    CompletionFailureSink() : DataSinkOperatorX<DummySinkLocalState>(1, 2, 3) 
{}
+    Status sink_impl(RuntimeState*, Block*, bool) override { return 
Status::OK(); }
+    size_t revocable_mem_size(RuntimeState*) const override {
+        return SpillFile::MIN_SPILL_WRITE_BATCH_MEM + 1;
+    }
+    Status revoke_memory(RuntimeState*) override { return revoke.run(); }
+    Status terminate(RuntimeState*) override { return termination.run(); }
+    SpillStep revoke;
+    SpillStep termination;
+};
+
+class RejectingSpillScheduler final : public MockTaskScheduler {
+public:
+    Status submit(PipelineTaskSPtr task) override {
+        if (std::dynamic_pointer_cast<RevokableTask>(task)) {
+            if (reject_spill) {
+                return rejection;
+            }
+        } else {
+            ++waiter_submissions;
+            waiter_status = 
task->runtime_state()->get_query_ctx()->exec_status();
+        }
+        auto status = MockTaskScheduler::submit(std::move(task));
+        if (on_waiter_submission) {
+            on_waiter_submission();
+        }
+        return status;
+    }
+    std::function<void()> on_waiter_submission;
+    const Status rejection = Status::InternalError("injected spill scheduler 
rejection");
+    Status waiter_status = Status::OK();
+    int waiter_submissions = 0;
+    bool reject_spill = true;
+};
+
+class ObservedSpillCompletionTask final : public PipelineTask {
+public:
+    using PipelineTask::PipelineTask;
+    bool set_running(bool running) override {
+        const auto previous = PipelineTask::set_running(running);
+        if (!running && on_idle) {
+            on_idle();
+        }
+        return previous;
+    }
+    std::function<void()> on_idle;
+};
+
+class SpillCompletionFailureTest : public testing::Test {
+protected:
+    void SetUp() override {
+        _old_tracker = std::move(thread_context()->thread_mem_tracker_mgr);
+        thread_context()->thread_mem_tracker_mgr = 
std::make_unique<MockThreadMemTrackerMgr>();
+        _options = TQueryOptionsBuilder()
+                           .set_runtime_filter_max_in_num(15)
+                           .set_execution_timeout(1)
+                           .build();
+        TNetworkAddress address;
+        address.hostname = BackendOptions::get_localhost();
+        address.port = config::brpc_port;
+        _query = QueryContext::create(_query_id, ExecEnv::GetInstance(), 
_options, address, true,
+                                      address, QuerySource::INTERNAL_FRONTEND);
+        _scheduler = std::make_unique<RejectingSpillScheduler>();
+        _query->_task_scheduler = _scheduler.get();
+        _fragment = std::make_shared<PipelineFragmentContext>(_query_id, 
TPipelineFragmentParams(),
+                                                              _query, 
ExecEnv::GetInstance(),
+                                                              
[](RuntimeState*, Status*) {});
+        _state = std::make_unique<MockRuntimeState>(_query_id, 0, _options, 
_query->query_globals,
+                                                    ExecEnv::GetInstance(), 
_query.get());
+        _state->set_task_execution_context(
+                std::static_pointer_cast<TaskExecutionContext>(_fragment));
+        _state->resize_op_id_to_local_state(-1);
+        _pipeline = std::make_shared<Pipeline>(0, 1, 1);
+        _source = std::make_shared<CompletionFailureSource>();
+        _sink = std::make_shared<CompletionFailureSink>();
+        OperatorPtr source = _source;
+        DataSinkOperatorPtr sink = _sink;
+        ASSERT_TRUE(_pipeline->add_operator(source, 1).ok());
+        ASSERT_TRUE(_pipeline->set_sink(sink).ok());
+        _profile = std::make_unique<RuntimeProfile>("SpillCompletionFailure");
+        std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
+                                std::vector<std::shared_ptr<Dependency>>>>
+                shared_state_map;
+        _task = std::make_shared<ObservedSpillCompletionTask>(_pipeline, 0, 
_state.get(), _fragment,
+                                                              _profile.get(), 
shared_state_map, 0);
+        ASSERT_TRUE(_task->prepare({}, 0, TDataSink()).ok());
+        _task->_opened = true;
+        _query->get_execution_dependency()->set_ready();
+        _query->set_memory_sufficient(false);
+    }
+
+    void TearDown() override {
+        _scheduler.reset();
+        _extra_states.clear();
+        _task.reset();
+        _state.reset();
+        _fragment.reset();
+        _query.reset();
+        thread_context()->thread_mem_tracker_mgr = std::move(_old_tracker);
+    }
+
+    std::shared_ptr<SpillContext> context(int count = 1) {
+        return std::make_shared<SpillContext>(count, _query_id, 
[this](SpillContext*) {
+            ++_callbacks;
+            _query->set_memory_sufficient(true);
+        });
+    }
+
+    PipelineTaskSPtr make_task(int index) {
+        auto state =
+                std::make_unique<MockRuntimeState>(_query_id, 0, _options, 
_query->query_globals,
+                                                   ExecEnv::GetInstance(), 
_query.get());
+        state->set_task_execution_context(
+                std::static_pointer_cast<TaskExecutionContext>(_fragment));
+        state->resize_op_id_to_local_state(-1);
+        std::map<int, std::pair<std::shared_ptr<BasicSharedState>,
+                                std::vector<std::shared_ptr<Dependency>>>>
+                shared_state_map;
+        auto pipeline = std::make_shared<Pipeline>(1, 1, 1);
+        OperatorPtr source = std::make_shared<DummyOperator>();
+        DataSinkOperatorPtr sink = std::make_shared<DummySinkOperatorX>(1, 2, 
3);
+        EXPECT_TRUE(pipeline->add_operator(source, 1).ok());
+        EXPECT_TRUE(pipeline->set_sink(sink).ok());
+        auto task = std::make_shared<PipelineTask>(pipeline, index, 
state.get(), _fragment,
+                                                   _profile.get(), 
shared_state_map, index);
+        EXPECT_TRUE(task->prepare({}, 0, TDataSink()).ok());
+        task->_opened = true;
+        _extra_states.emplace_back(std::move(state));
+        return task;
+    }
+
+    PipelineTaskSPtr block_waiter() {
+        auto waiter = make_task(10);
+        auto* dep = _query->get_memory_sufficient_dependency();
+        EXPECT_EQ(dep->is_blocked_by(waiter), dep);
+        EXPECT_EQ(waiter->_exec_state, PipelineTask::State::BLOCKED);
+        return waiter;
+    }
+
+    void select_tasks(int count) {
+        _fragment->_tasks.resize(1);
+        _fragment->_tasks[0].emplace_back(_task, std::move(_state));
+        for (int i = 1; i < count; ++i) {
+            auto task = make_task(i);
+            _fragment->_tasks[0].emplace_back(std::move(task), 
std::move(_extra_states.back()));
+            _extra_states.pop_back();
+        }
+        _query->_fragment_id_to_pipeline_ctx[0] = _fragment;
+    }
+
+    void run_one(PipelineTaskSPtr task) {
+        std::promise<void> idle;
+        auto observed = idle.get_future();
+        _task->on_idle = [&idle]() { idle.set_value(); };
+        HybridTaskScheduler scheduler(1, 1, "spill_lifecycle_test", nullptr);
+        Defer stop_scheduler {[&]() { scheduler.stop(); }};
+        ASSERT_TRUE(scheduler.start().ok());
+        ASSERT_TRUE(scheduler.submit(std::move(task)).ok());
+        EXPECT_EQ(observed.wait_for(std::chrono::seconds(10)), 
std::future_status::ready);
+        scheduler.stop();
+        _task->on_idle = {};
+    }
+
+    void finalize_early_task() {
+        _pipeline->incr_created_tasks(0, _task.get());
+        _fragment->_pip_id_to_pipeline[0] = _pipeline.get();
+        _fragment->_total_tasks = 2;
+        _pipeline->make_all_runnable(1);
+        run_one(_task);
+        ASSERT_TRUE(_task->is_finalized());
+    }
+
+    void expect_status(const Status& actual, const Status& expected) {
+        EXPECT_EQ(actual.code(), expected.code());
+        EXPECT_EQ(actual.msg(), expected.msg());
+    }
+
+    std::vector<std::unique_ptr<MockRuntimeState>> _extra_states;
+    TUniqueId _query_id;
+    TQueryOptions _options;
+    std::unique_ptr<ThreadMemTrackerMgr> _old_tracker;
+    std::shared_ptr<QueryContext> _query;
+    std::unique_ptr<RejectingSpillScheduler> _scheduler;
+    std::shared_ptr<PipelineFragmentContext> _fragment;
+    std::unique_ptr<MockRuntimeState> _state;
+    PipelinePtr _pipeline;
+    std::shared_ptr<CompletionFailureSource> _source;
+    std::shared_ptr<CompletionFailureSink> _sink;
+    std::unique_ptr<RuntimeProfile> _profile;
+    std::shared_ptr<ObservedSpillCompletionTask> _task;
+    int _callbacks = 0;
+};
+
+// Keep the real timeout worker and timeout detection. Only omit IdManager 
cleanup,
+// which is unrelated to the query's memory dependency and absent in this 
fixture.
+class SpillTimeoutObserver final : public FragmentMgr {
+public:
+    SpillTimeoutObserver() : FragmentMgr(ExecEnv::GetInstance()) {}
+    void cancel_query(const TUniqueId query_id, const Status reason) override {
+        auto query = get_query_ctx(query_id);
+        blocked_until_timeout = query->exec_status().ok() &&
+                                
query->get_memory_sufficient_dependency()->is_blocked_by(nullptr);
+        query->cancel(reason);
+        remove_query_context(query_id);
+    }
+    bool blocked_until_timeout = false;
+};
+
+TEST_F(SpillCompletionFailureTest, 
EarlyFinishAcrossSecondPauseResumesLiveWaiter) {
+    auto wg = std::make_shared<WorkloadGroup>(WorkloadGroupInfo {.id = 12345});
+    _query->resource_ctx()->set_workload_group(wg);
+    _pipeline->incr_created_tasks(0, _task.get());
+    _fragment->_pip_id_to_pipeline[0] = _pipeline.get();
+    _fragment->_total_tasks = 2;
+    _fragment->_runtime_state = std::make_unique<MockRuntimeState>(
+            _query_id, 0, _options, _query->query_globals, 
ExecEnv::GetInstance(), _query.get());
+    auto waiter = make_task(10);
+    select_tasks(1);
+    _fragment->_tasks[0].emplace_back(waiter, std::move(_extra_states.back()));
+    _extra_states.pop_back();
+    waiter->_pipeline->incr_created_tasks(0, waiter.get());
+    _fragment->_pip_id_to_pipeline[1] = waiter->_pipeline.get();
+    auto* dependency = _query->get_memory_sufficient_dependency();
+    ASSERT_EQ(dependency->is_blocked_by(_task), dependency);
+
+    // A downstream early finish wakes A out of the first memory pause. A is
+    // queued normally but has not executed its early-wake termination yet.
+    _pipeline->make_all_runnable(1);
+    auto ordinary = _scheduler->_task_queue->take(0);
+    ASSERT_EQ(ordinary, _task);
+    ASSERT_EQ(_task->_exec_state, PipelineTask::State::RUNNABLE);
+    ASSERT_EQ(dependency->is_blocked_by(nullptr), nullptr);
+    _scheduler->waiter_submissions = 0;
+
+    WorkloadGroupMgr manager;
+    manager.add_paused_query(
+            _query->resource_ctx(), SpillFile::MIN_SPILL_WRITE_BATCH_MEM,
+            Status::Error<ErrorCode::QUERY_MEMORY_EXCEEDED>("second memory 
pause"));
+    ASSERT_EQ(dependency->is_blocked_by(waiter), dependency);
+    _scheduler->reject_spill = false;
+    auto tracker = _query->query_mem_tracker();
+    const auto consumption = 100 * SpillFile::MIN_SPILL_WRITE_BATCH_MEM;
+    tracker->consume(consumption);
+    Defer release_consumption {[&]() { tracker->release(consumption); }};
+    auto& paused = manager._paused_queries_list[wg];
+    auto paused_query = paused.begin();
+    EXPECT_FALSE(
+            manager.release_query_memory_(paused, paused_query, 
_query->resource_ctx(), false));
+    ASSERT_TRUE(paused.empty());
+    auto wrapper = _scheduler->_task_queue->take(0);
+    ASSERT_NE(std::dynamic_pointer_cast<RevokableTask>(wrapper), nullptr);
+
+    // Run the ordinary task first. Its real worker closes and finalizes A;
+    // the queued spill wrapper then encounters FINALIZED without test 
mutation.
+    run_one(std::move(ordinary));
+    ASSERT_TRUE(_task->is_finalized());
+    ASSERT_TRUE(_query->exec_status().ok());
+    ASSERT_EQ(dependency->is_blocked_by(nullptr), dependency);
+
+    std::promise<void> waiter_submitted;
+    auto resumed = waiter_submitted.get_future();
+    _scheduler->on_waiter_submission = [&]() { waiter_submitted.set_value(); };
+    Defer clear_observer {[&]() { _scheduler->on_waiter_submission = {}; }};
+    run_one(std::move(wrapper));
+
+    const auto previous_interval = 
config::fragment_mgr_cancel_worker_interval_seconds;
+    config::fragment_mgr_cancel_worker_interval_seconds = 1;
+    Defer restore_interval {
+            [&]() { config::fragment_mgr_cancel_worker_interval_seconds = 
previous_interval; }};
+    auto* exec_env = ExecEnv::GetInstance();
+    const bool need_load_stream_mgr = exec_env->new_load_stream_mgr() == 
nullptr;
+    if (need_load_stream_mgr) {
+        exec_env->set_new_load_stream_mgr(NewLoadStreamMgr::create_unique());
+    }
+    Defer clear_load_stream_mgr {[&]() {
+        if (need_load_stream_mgr) {
+            exec_env->clear_new_load_stream_mgr();
+        }
+    }};
+    SpillTimeoutObserver timeout_manager;
+    Defer stop_timeout_manager {[&]() { timeout_manager.stop(); }};
+    std::shared_ptr<QueryContext> registered;
+    ASSERT_TRUE(timeout_manager._query_ctx_map
+                        .apply_if_not_exists(_query_id, registered,

Review Comment:
   [P2] Exclude fixture setup from the query timeout window
   
   `SetUp()` creates this query with `execution_timeout=1`, starting its 
watcher before fixture setup and both `run_one()` scheduler lifecycles. If 
those steps cross two monotonic second boundaries, registering the query here 
lets the timeout worker cancel it even though the spill callback already 
resumed the waiter. A delayed worker still performs its first `do/while` scan 
after `stop()` signals the latch, so the success assertion at line 389 can fail 
solely because setup was slow. Reset/control the deadline around the observed 
pause and synchronize timeout observation with completion so a successful 
resume cannot be reported as a timeout.



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