Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::Executor Class Reference
Collaboration diagram for duckdb::Executor:

Public Member Functions

 Executor (ClientContext &context)
void Initialize (PhysicalOperator &physical_plan)
void Initialize (unique_ptr< PhysicalOperator > physical_plan)
void CancelTasks ()
PendingExecutionResult ExecuteTask (bool dry_run=false)
void WaitForTask ()
void SignalTaskRescheduled (lock_guard< mutex > &)
void Reset ()
vector< LogicalType > GetTypes ()
void PushError (ErrorData exception)
 Push a new error.
ErrorData GetError ()
bool HasError ()
 True if an error has been thrown.
void ThrowException ()
void WorkOnTasks ()
 Work on tasks for this specific executor, until there are no tasks remaining.
void Flush (ThreadContext &context)
 Flush a thread context into the client context.
void RescheduleTask (shared_ptr< Task > &task)
 Reschedules a task that was blocked.
void AddToBeRescheduled (shared_ptr< Task > &task)
 Add the task to be rescheduled.
idx_t GetPipelinesProgress (ProgressData &progress)
 Returns the progress of the pipelines.
void CompletePipeline ()
ProducerToken & GetToken ()
void AddEvent (shared_ptr< Event > event)
void AddRecursiveCTE (PhysicalOperator &rec_cte)
void ReschedulePipelines (const vector< shared_ptr< MetaPipeline > > &pipelines, vector< shared_ptr< Event > > &events)
bool HasResultCollector ()
 Whether or not the root of the pipeline is a result collector object.
bool HasStreamingResultCollector ()
 Whether or not the root of the pipeline is a streaming result collector object.
unique_ptr< QueryResult > GetResult ()
 Returns the query result - can only be used if HasResultCollector returns true.
bool ExecutionIsFinished ()
 Returns true if all pipelines have been completed.
void RegisterTask ()
void UnregisterTask ()
idx_t GetTotalPipelines () const
idx_t GetCompletedPipelines () const

Static Public Member Functions

static Executor & Get (ClientContext &context)

Public Attributes

ClientContext & context

Static Public Attributes

static constexpr idx_t WAIT_TIME = 20

Private Member Functions

bool ResultCollectorIsBlocked ()
 Check if the streaming query result is waiting to be fetched from, must hold the 'executor_lock'.
void InitializeInternal (PhysicalOperator &physical_plan)
void ScheduleEvents (const vector< shared_ptr< MetaPipeline > > &meta_pipelines)
void ScheduleEventsInternal (ScheduleEventData &event_data)
void SchedulePipeline (const shared_ptr< MetaPipeline > &pipeline, ScheduleEventData &event_data)
bool NextExecutor ()
shared_ptr< Pipeline > CreateChildPipeline (Pipeline &current, PhysicalOperator &op)
void VerifyPipeline (Pipeline &pipeline)
void VerifyPipelines ()

Static Private Member Functions

static void VerifyScheduledEvents (const ScheduleEventData &event_data)
static void VerifyScheduledEventsInternal (const idx_t i, const vector< reference< Event > > &vertices, vector< bool > &visited, vector< bool > &recursion_stack)

Private Attributes

optional_ptr< PhysicalOperator > physical_plan
unique_ptr< PhysicalOperator > owned_plan
mutex executor_lock
vector< shared_ptr< Pipeline > > pipelines
 All pipelines of the query plan.
vector< shared_ptr< Pipeline > > root_pipelines
 The root pipelines of the query.
vector< reference< PhysicalOperator > > recursive_ctes
 The recursive CTE's in this query plan.
unique_ptr< PipelineExecutor > root_executor
 The pipeline executor for the root pipeline.
idx_t root_pipeline_idx
 The current root pipeline index.
unique_ptr< ProducerToken > producer
 The producer of this query.
vector< shared_ptr< Event > > events
 List of events.
shared_ptr< QueryProfiler > profiler
 The query profiler.
TaskErrorManager error_manager
 Task error manager.
atomic< idx_t > completed_pipelines
 The amount of completed pipelines of the query.
idx_t total_pipelines
 The total amount of pipelines in the query.
bool cancelled
 Whether or not execution is cancelled.
PendingExecutionResult execution_result
 The last pending execution result (if any).
shared_ptr< Task > task
 The current task in process (if any).
unordered_map< Task *, shared_ptr< Task > > to_be_rescheduled_tasks
 Task that have been descheduled.
std::condition_variable task_reschedule
 The semaphore to signal task rescheduling.
atomic< idx_t > executor_tasks
 Currently alive executor tasks.
atomic< idx_t > blocked_thread_time
 Total time blocked while waiting on tasks. In ticks. One tick corresponds to WAIT_TIME.

Friends

class Pipeline
class PipelineTask
class PipelineBuildState

Constructor & Destructor Documentation

◆ Executor()

duckdb::Executor::Executor ( ClientContext & context)
explicit
328417 : context(context), executor_tasks(0), blocked_thread_time(0) {
328418}
atomic< idx_t > blocked_thread_time
Total time blocked while waiting on tasks. In ticks. One tick corresponds to WAIT_TIME.
Definition duckdb.hpp:27138
atomic< idx_t > executor_tasks
Currently alive executor tasks.
Definition duckdb.hpp:27135

◆ ~Executor()

duckdb::Executor::~Executor ( )
328420 {
328421 D_ASSERT(Exception::UncaughtException() || executor_tasks == 0);
328422}

Member Function Documentation

◆ Get()

Executor & duckdb::Executor::Get ( ClientContext & context)
static
328424 {
328425 return context.GetExecutor();
328426}

◆ Initialize() [1/2]

void duckdb::Executor::Initialize ( PhysicalOperator & physical_plan)
328773 {
328774 Reset();
328775 InitializeInternal(plan);
328776}

◆ Initialize() [2/2]

void duckdb::Executor::Initialize ( unique_ptr< PhysicalOperator > physical_plan)
328767 {
328768 Reset();
328769 owned_plan = std::move(physical_plan_p);
328770 InitializeInternal(*owned_plan);
328771}

◆ CancelTasks()

void duckdb::Executor::CancelTasks ( )
328820 {
328821 task.reset();
328822 {
328823 lock_guard<mutex> elock(executor_lock);
328824 // mark the query as cancelled so tasks will early-out
328825 cancelled = true;
328826 to_be_rescheduled_tasks.clear();
328827 }
328828 // Drain all tasks first — they hold references to pipelines/events/states,
328829 // so those must stay alive until all tasks have completed
328830 while (executor_tasks > 0) {
328831 WorkOnTasks();
328832 }
328833 // Now safe to destroy pipelines, events and states — no tasks reference them
328834 lock_guard<mutex> elock(executor_lock);
328835 for (auto &rec_cte_ref : recursive_ctes) {
328836 auto &rec_cte = rec_cte_ref.get().Cast<PhysicalRecursiveCTE>();
328837 rec_cte.recursive_meta_pipeline.reset();
328838 }
328839 pipelines.clear();
328840 root_pipelines.clear();
328841 to_be_rescheduled_tasks.clear();
328842 events.clear();
328843}
vector< reference< PhysicalOperator > > recursive_ctes
The recursive CTE's in this query plan.
Definition duckdb.hpp:27103
vector< shared_ptr< Pipeline > > root_pipelines
The root pipelines of the query.
Definition duckdb.hpp:27101
vector< shared_ptr< Event > > events
List of events.
Definition duckdb.hpp:27111
unordered_map< Task *, shared_ptr< Task > > to_be_rescheduled_tasks
Task that have been descheduled.
Definition duckdb.hpp:27130
void WorkOnTasks()
Work on tasks for this specific executor, until there are no tasks remaining.
Definition duckdb.cpp:328845
vector< shared_ptr< Pipeline > > pipelines
All pipelines of the query plan.
Definition duckdb.hpp:27099
bool cancelled
Whether or not execution is cancelled.
Definition duckdb.hpp:27122
shared_ptr< Task > task
The current task in process (if any).
Definition duckdb.hpp:27127

◆ ExecuteTask()

PendingExecutionResult duckdb::Executor::ExecuteTask ( bool dry_run = false)
328944 {
328945 // Only executor should return NO_TASKS_AVAILABLE
328946 D_ASSERT(execution_result != PendingExecutionResult::NO_TASKS_AVAILABLE);
328947 if (execution_result != PendingExecutionResult::RESULT_NOT_READY && ExecutionIsFinished()) {
328948 return execution_result;
328949 }
328950 // check if there are any incomplete pipelines
328951 auto &scheduler = TaskScheduler::GetScheduler(context);
328953 // there are! if we don't already have a task, fetch one
328954 auto current_task = task.get();
328955 if (dry_run) {
328956 // Pretend we have no task, we don't want to execute anything
328957 current_task = nullptr;
328958 } else {
328959 if (!task) {
328960 scheduler.GetTaskFromProducer(*producer, task);
328961 }
328962 current_task = task.get();
328963 }
328964
328965 if (!current_task && !HasError()) {
328966 // there are no tasks to be scheduled and there are tasks blocked
328967 lock_guard<mutex> l(executor_lock);
328968 if (to_be_rescheduled_tasks.empty()) {
328969 return PendingExecutionResult::NO_TASKS_AVAILABLE;
328970 }
328971 // At least one task is blocked
328972 if (ResultCollectorIsBlocked()) {
328973 return PendingExecutionResult::RESULT_READY;
328974 }
328975 return PendingExecutionResult::BLOCKED;
328976 }
328977
328978 if (current_task) {
328979 // if we have a task, partially process it
328980 auto result = task->Execute(TaskExecutionMode::PROCESS_PARTIAL);
328981 if (result == TaskExecutionResult::TASK_BLOCKED) {
328982 task->Deschedule();
328983 task.reset();
328984 } else if (result == TaskExecutionResult::TASK_FINISHED) {
328985 // if the task is finished, clean it up
328986 task.reset();
328987 } else if (result == TaskExecutionResult::TASK_ERROR) {
328988 if (!HasError()) {
328989 // This is very much unexpected, TASK_ERROR means this executor should have an Error
328990 throw InternalException("A task executed within Executor::ExecuteTask, from own producer, returned "
328991 "TASK_ERROR without setting error on the Executor");
328992 }
328993 }
328994 }
328995 if (!HasError()) {
328996 // we (partially) processed a task and no exceptions were thrown
328997 // give back control to the caller
328998 if (task && Settings::Get<SchedulerProcessPartialSetting>(context)) {
328999 auto &token = *task->token;
329000 TaskScheduler::GetScheduler(context).ScheduleTask(token, task);
329001 task.reset();
329002 }
329003 return PendingExecutionResult::RESULT_NOT_READY;
329004 }
329005 execution_result = PendingExecutionResult::EXECUTION_ERROR;
329006
329007 // an exception has occurred executing one of the pipelines
329008 // we need to cancel all tasks associated with this executor
329009 CancelTasks();
329010 ThrowException();
329011 }
329012 D_ASSERT(!task);
329013
329014 lock_guard<mutex> elock(executor_lock);
329015 pipelines.clear();
329016 NextExecutor();
329017 if (HasError()) { // LCOV_EXCL_START
329018 // an exception has occurred executing one of the pipelines
329019 execution_result = PendingExecutionResult::EXECUTION_ERROR;
329020 ThrowException();
329021 } // LCOV_EXCL_STOP
329022 execution_result = PendingExecutionResult::EXECUTION_FINISHED;
329023 return execution_result;
329024}
unique_ptr< ProducerToken > producer
The producer of this query.
Definition duckdb.hpp:27109
PendingExecutionResult execution_result
The last pending execution result (if any).
Definition duckdb.hpp:27125
idx_t total_pipelines
The total amount of pipelines in the query.
Definition duckdb.hpp:27120
bool HasError()
True if an error has been thrown.
Definition duckdb.cpp:329074
bool ResultCollectorIsBlocked()
Check if the streaming query result is waiting to be fetched from, must hold the 'executor_lock'.
Definition duckdb.cpp:328903
bool ExecutionIsFinished()
Returns true if all pipelines have been completed.
Definition duckdb.cpp:328940
void ThrowException()
Definition duckdb.cpp:329082
atomic< idx_t > completed_pipelines
The amount of completed pipelines of the query.
Definition duckdb.hpp:27118

◆ WaitForTask()

void duckdb::Executor::WaitForTask ( )
328862 {
328863#ifndef DUCKDB_NO_THREADS
328864 static constexpr std::chrono::microseconds WAIT_TIME_MS = std::chrono::microseconds(WAIT_TIME * 1000);
328865 auto begin = std::chrono::high_resolution_clock::now();
328866 std::unique_lock<mutex> l(executor_lock);
328867 auto end = std::chrono::high_resolution_clock::now();
328868 auto dur = end - begin;
328869 auto ms = NumericCast<idx_t>(std::chrono::duration_cast<std::chrono::microseconds>(dur).count());
328870 if (to_be_rescheduled_tasks.empty()) {
328871 blocked_thread_time += ms;
328872 return;
328873 }
328874 if (ResultCollectorIsBlocked()) {
328875 // If the result collector is blocked, it won't get unblocked until the connection calls Fetch
328876 blocked_thread_time += ms;
328877 return;
328878 }
328879
328880 blocked_thread_time += ms + WAIT_TIME_MS.count();
328881 task_reschedule.wait_for(l, WAIT_TIME_MS);
328882#endif
328883}
std::condition_variable task_reschedule
The semaphore to signal task rescheduling.
Definition duckdb.hpp:27132

◆ SignalTaskRescheduled()

void duckdb::Executor::SignalTaskRescheduled ( lock_guard< mutex > & )
328858 {
328859 task_reschedule.notify_one();
328860}

◆ Reset()

void duckdb::Executor::Reset ( )
329026 {
329027 lock_guard<mutex> elock(executor_lock);
329028 physical_plan = nullptr;
329029 cancelled = false;
329030 root_executor.reset();
329031 root_pipelines.clear();
329032 root_pipeline_idx = 0;
329034 total_pipelines = 0;
329035 error_manager.Reset();
329036 pipelines.clear();
329037 events.clear();
329038 to_be_rescheduled_tasks.clear();
329039 execution_result = PendingExecutionResult::RESULT_NOT_READY;
329040}
TaskErrorManager error_manager
Task error manager.
Definition duckdb.hpp:27115
unique_ptr< PipelineExecutor > root_executor
The pipeline executor for the root pipeline.
Definition duckdb.hpp:27105
idx_t root_pipeline_idx
The current root pipeline index.
Definition duckdb.hpp:27107

◆ GetTypes()

vector< LogicalType > duckdb::Executor::GetTypes ( )
329062 {
329063 D_ASSERT(physical_plan);
329064 return physical_plan->GetTypes();
329065}

◆ PushError()

void duckdb::Executor::PushError ( ErrorData exception)

Push a new error.

329067 {
329068 // push the exception onto the stack
329069 error_manager.PushError(std::move(exception));
329070 // interrupt execution of any other pipelines that belong to this executor
329071 context.interrupted = true;
329072}

◆ GetError()

ErrorData duckdb::Executor::GetError ( )
329078 {
329079 return error_manager.GetError();
329080}

◆ HasError()

bool duckdb::Executor::HasError ( )

True if an error has been thrown.

329074 {
329075 return error_manager.HasError();
329076}
Here is the caller graph for this function:

◆ ThrowException()

void duckdb::Executor::ThrowException ( )

Throw the exception that was pushed using PushError. Should only be called if HasError returns true

329082 {
329083 error_manager.ThrowException();
329084}

◆ WorkOnTasks()

void duckdb::Executor::WorkOnTasks ( )

Work on tasks for this specific executor, until there are no tasks remaining.

328845 {
328846 auto &scheduler = TaskScheduler::GetScheduler(context);
328847
328848 shared_ptr<Task> task_from_producer;
328849 while (scheduler.GetTaskFromProducer(*producer, task_from_producer)) {
328850 auto res = task_from_producer->Execute(TaskExecutionMode::PROCESS_ALL);
328851 if (res == TaskExecutionResult::TASK_BLOCKED) {
328852 task_from_producer->Deschedule();
328853 }
328854 task_from_producer.reset();
328855 }
328856}

◆ Flush()

void duckdb::Executor::Flush ( ThreadContext & context)

Flush a thread context into the client context.

329086 {
329087 auto global_profiler = profiler;
329088 if (global_profiler) {
329089 global_profiler->Flush(thread_context.profiler);
329090
329091 auto blocked_time = blocked_thread_time.load();
329092 global_profiler->SetBlockedTime(double(blocked_time) / 1000.0 / 1000.0);
329093 }
329094}
shared_ptr< QueryProfiler > profiler
The query profiler.
Definition duckdb.hpp:27113

◆ RescheduleTask()

void duckdb::Executor::RescheduleTask ( shared_ptr< Task > & task)

Reschedules a task that was blocked.

328885 {
328886 // This function will spin lock until the task provided is added to the to_be_rescheduled_tasks
328887 while (true) {
328888 lock_guard<mutex> l(executor_lock);
328889 if (cancelled) {
328890 return;
328891 }
328892 auto entry = to_be_rescheduled_tasks.find(task_p.get());
328893 if (entry != to_be_rescheduled_tasks.end()) {
328894 auto &scheduler = TaskScheduler::GetScheduler(context);
328895 to_be_rescheduled_tasks.erase(task_p.get());
328896 scheduler.ScheduleTask(GetToken(), task_p);
328897 SignalTaskRescheduled(l);
328898 break;
328899 }
328900 }
328901}

◆ AddToBeRescheduled()

void duckdb::Executor::AddToBeRescheduled ( shared_ptr< Task > & task)

Add the task to be rescheduled.

328927 {
328928 lock_guard<mutex> l(executor_lock);
328929 if (cancelled) {
328930 return;
328931 }
328932 if (to_be_rescheduled_tasks.find(task_p.get()) != to_be_rescheduled_tasks.end()) {
328933 return;
328934 }
328935 // Save raw pointer before move — evaluation order of operator[] key and assignment value is unspecified pre-C++17
328936 auto raw_ptr = task_p.get();
328937 to_be_rescheduled_tasks[raw_ptr] = std::move(task_p);
328938}

◆ GetPipelinesProgress()

idx_t duckdb::Executor::GetPipelinesProgress ( ProgressData & progress)

Returns the progress of the pipelines.

329096 { // LCOV_EXCL_START
329097 lock_guard<mutex> elock(executor_lock);
329098
329099 progress.done = 0;
329100 progress.total = 0;
329101 idx_t count_invalid = 0;
329102 for (auto &pipeline : pipelines) {
329103 ProgressData p;
329104 if (!pipeline->GetProgress(p)) {
329105 count_invalid++;
329106 } else {
329107 progress.Add(p);
329108 }
329109 }
329110 return count_invalid;
329111} // LCOV_EXCL_STOP
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ CompletePipeline()

void duckdb::Executor::CompletePipeline ( )
inline
27036 {
27038 }

◆ GetToken()

ProducerToken & duckdb::Executor::GetToken ( )
inline
27039 {
27040 return *producer;
27041 }

◆ AddEvent()

void duckdb::Executor::AddEvent ( shared_ptr< Event > event)
328428 {
328429 lock_guard<mutex> elock(executor_lock);
328430 if (cancelled) {
328431 return;
328432 }
328433 events.push_back(std::move(event));
328434}

◆ AddRecursiveCTE()

void duckdb::Executor::AddRecursiveCTE ( PhysicalOperator & rec_cte)
328720 {
328721 recursive_ctes.push_back(rec_cte);
328722}

◆ ReschedulePipelines()

void duckdb::Executor::ReschedulePipelines ( const vector< shared_ptr< MetaPipeline > > & pipelines,
vector< shared_ptr< Event > > & events )
328725 {
328726 ScheduleEventData event_data(pipelines_p, events_p, false);
328727 ScheduleEventsInternal(event_data);
328728}

◆ HasResultCollector()

bool duckdb::Executor::HasResultCollector ( )

Whether or not the root of the pipeline is a result collector object.

329113 {
329114 return physical_plan->type == PhysicalOperatorType::RESULT_COLLECTOR;
329115}
Here is the caller graph for this function:

◆ HasStreamingResultCollector()

bool duckdb::Executor::HasStreamingResultCollector ( )

Whether or not the root of the pipeline is a streaming result collector object.

329117 {
329118 if (!HasResultCollector()) {
329119 return false;
329120 }
329121 auto &result_collector = physical_plan->Cast<PhysicalResultCollector>();
329122 return result_collector.IsStreaming();
329123}
bool HasResultCollector()
Whether or not the root of the pipeline is a result collector object.
Definition duckdb.cpp:329113
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetResult()

unique_ptr< QueryResult > duckdb::Executor::GetResult ( )

Returns the query result - can only be used if HasResultCollector returns true.

329125 {
329126 D_ASSERT(HasResultCollector());
329127 auto &result_collector = physical_plan->Cast<PhysicalResultCollector>();
329128 D_ASSERT(result_collector.sink_state);
329129 return result_collector.GetResult(*result_collector.sink_state);
329130}
Here is the call graph for this function:

◆ ExecutionIsFinished()

bool duckdb::Executor::ExecutionIsFinished ( )

Returns true if all pipelines have been completed.

328940 {
328942}
Here is the call graph for this function:

◆ RegisterTask()

void duckdb::Executor::RegisterTask ( )
inline
27057 {
27059 }

◆ UnregisterTask()

void duckdb::Executor::UnregisterTask ( )
inline
27060 {
27062 }

◆ GetTotalPipelines()

idx_t duckdb::Executor::GetTotalPipelines ( ) const
inline
27064 {
27065 return total_pipelines;
27066 }

◆ GetCompletedPipelines()

idx_t duckdb::Executor::GetCompletedPipelines ( ) const
inline
27068 {
27069 return completed_pipelines.load();
27070 }

◆ ResultCollectorIsBlocked()

bool duckdb::Executor::ResultCollectorIsBlocked ( )
private

Check if the streaming query result is waiting to be fetched from, must hold the 'executor_lock'.

328903 {
328905 return false;
328906 }
328908 // The result collector is always in the last pipeline
328909 return false;
328910 }
328911 if (to_be_rescheduled_tasks.empty()) {
328912 return false;
328913 }
328914 for (auto &kv : to_be_rescheduled_tasks) {
328915 auto &task = kv.second;
328916 if (task->TaskBlockedOnResult()) {
328917 // At least one of the blocked tasks is connected to a result collector
328918 // This task could be the only task that could unblock the other non-result-collector tasks
328919 // To prevent a scenario where we halt indefinitely, we return here so it can be unblocked by a call to
328920 // Fetch
328921 return true;
328922 }
328923 }
328924 return false;
328925}
bool HasStreamingResultCollector()
Whether or not the root of the pipeline is a streaming result collector object.
Definition duckdb.cpp:329117
Here is the call graph for this function:

◆ InitializeInternal()

void duckdb::Executor::InitializeInternal ( PhysicalOperator & physical_plan)
private
328778 {
328779 auto &scheduler = TaskScheduler::GetScheduler(context);
328780 {
328781 lock_guard<mutex> elock(executor_lock);
328782 physical_plan = &plan;
328783
328784 this->profiler = ClientData::Get(context).profiler;
328785 profiler->Initialize(plan);
328786 this->producer = scheduler.CreateProducer();
328787
328788 // build and ready the pipelines
328789 PipelineBuildState state;
328790 auto root_pipeline = make_shared_ptr<MetaPipeline>(*this, state, nullptr);
328791 root_pipeline->Build(*physical_plan);
328792 root_pipeline->Ready();
328793
328794 // ready recursive cte pipelines too
328795 for (auto &rec_cte_ref : recursive_ctes) {
328796 auto &rec_cte = rec_cte_ref.get().Cast<PhysicalRecursiveCTE>();
328797 rec_cte.recursive_meta_pipeline->Ready();
328798 }
328799
328800 // set root pipelines, i.e., all pipelines that end in the final sink
328801 root_pipeline->GetPipelines(root_pipelines, false);
328802 root_pipeline_idx = 0;
328803
328804 // collect all meta-pipelines from the root pipeline
328805 vector<shared_ptr<MetaPipeline>> to_schedule;
328806 root_pipeline->GetMetaPipelines(to_schedule, true, true);
328807
328808 // number of 'PipelineCompleteEvent's is equal to the number of meta pipelines, so we have to set it here
328809 total_pipelines = to_schedule.size();
328810
328811 // collect all pipelines from the root pipelines (recursively) for the progress bar and verify them
328812 root_pipeline->GetPipelines(pipelines, true);
328813
328814 // finally, verify and schedule
328815 VerifyPipelines();
328816 ScheduleEvents(to_schedule);
328817 }
328818}

◆ ScheduleEvents()

void duckdb::Executor::ScheduleEvents ( const vector< shared_ptr< MetaPipeline > > & meta_pipelines)
private
328660 {
328661 ScheduleEventData event_data(meta_pipelines, events, true);
328662 ScheduleEventsInternal(event_data);
328663}

◆ ScheduleEventsInternal()

void duckdb::Executor::ScheduleEventsInternal ( ScheduleEventData & event_data)
private
328569 {
328570 auto &events = event_data.events;
328571 D_ASSERT(events.empty());
328572
328573 // create all the required pipeline events
328574 for (auto &meta_pipeline : event_data.meta_pipelines) {
328575 SchedulePipeline(meta_pipeline, event_data);
328576 }
328577
328578 // set up the dependencies for complete event
328579 auto &event_map = event_data.event_map;
328580 for (auto &entry : event_map) {
328581 auto &pipeline = entry.first.get();
328582 for (auto &dependency : pipeline.dependencies) {
328583 auto dep = dependency.lock();
328584 D_ASSERT(dep);
328585 auto event_map_entry = event_map.find(*dep);
328586 if (event_map_entry == event_map.end()) {
328587 continue;
328588 }
328589 D_ASSERT(event_map_entry != event_map.end());
328590 auto &dep_entry = event_map_entry->second;
328591 entry.second.pipeline_event.AddDependency(dep_entry.pipeline_complete_event);
328592 }
328593 }
328594
328595 // set the dependencies for pipeline event
328596 for (auto &meta_pipeline : event_data.meta_pipelines) {
328597 for (auto &entry : meta_pipeline->GetDependencies()) {
328598 auto &pipeline = entry.first.get();
328599 auto root_entry = event_map.find(pipeline);
328600 D_ASSERT(root_entry != event_map.end());
328601 auto &pipeline_stack = root_entry->second;
328602 for (auto &dependency : entry.second) {
328603 auto event_entry = event_map.find(dependency);
328604 D_ASSERT(event_entry != event_map.end());
328605 auto &dependency_stack = event_entry->second;
328606 pipeline_stack.pipeline_event.AddDependency(dependency_stack.pipeline_event);
328607 }
328608 }
328609 }
328610
328611 // these dependencies make it so that things happen in this order:
328612 // 1. all join build child pipelines run until Combine
328613 // 2. all join build child pipeline PrepareFinalize
328614 // 3. all join build child pipelines Finalize
328615 // operators communicate their memory usage through the TemporaryMemoryManger (TMM) in PrepareFinalize
328616 // then, when the child pipelines Finalize, all required memory is known, and TMM can make an informed decision
328617 for (auto &meta_pipeline : event_data.meta_pipelines) {
328618 vector<shared_ptr<MetaPipeline>> children;
328619 meta_pipeline->GetMetaPipelines(children, false, true);
328620 for (auto &child1 : children) {
328621 if (child1->Type() != MetaPipelineType::JOIN_BUILD) {
328622 continue; // We only want to do this for join builds
328623 }
328624 auto &child1_base = *child1->GetBasePipeline();
328625 auto child1_entry = event_map.find(child1_base);
328626 D_ASSERT(child1_entry != event_map.end());
328627
328628 for (auto &child2 : children) {
328629 if (child2->Type() != MetaPipelineType::JOIN_BUILD || RefersToSameObject(*child1, *child2)) {
328630 continue; // We don't want to depend on itself
328631 }
328632 if (!RefersToSameObject(*child1->GetParent(), *child2->GetParent())) {
328633 continue; // Different parents, skip
328634 }
328635
328636 auto &child2_base = *child2->GetBasePipeline();
328637 auto child2_entry = event_map.find(child2_base);
328638 D_ASSERT(child2_entry != event_map.end());
328639
328640 // all children PrepareFinalize must wait until all Combine
328641 child1_entry->second.pipeline_prepare_finish_event.AddDependency(child2_entry->second.pipeline_event);
328642 // all children Finalize must wait until all PrepareFinalize
328643 child1_entry->second.pipeline_finish_event.AddDependency(
328644 child2_entry->second.pipeline_prepare_finish_event);
328645 }
328646 }
328647 }
328648
328649 // verify that we have no cyclic dependencies
328650 VerifyScheduledEvents(event_data);
328651
328652 // schedule the pipelines that do not have dependencies
328653 for (auto &event : events) {
328654 if (!event->HasDependencies()) {
328655 event->Schedule();
328656 }
328657 }
328658}
@ JOIN_BUILD
The shared sink is regular.
Definition duckdb.cpp:60634
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191

◆ VerifyScheduledEvents()

void duckdb::Executor::VerifyScheduledEvents ( const ScheduleEventData & event_data)
staticprivate
328665 {
328666#ifdef DEBUG
328667 const idx_t count = event_data.events.size();
328668 vector<reference<Event>> vertices;
328669 vertices.reserve(count);
328670 for (const auto &event : event_data.events) {
328671 vertices.push_back(*event);
328672 }
328673 vector<bool> visited(count, false);
328674 vector<bool> recursion_stack(count, false);
328675 for (idx_t i = 0; i < count; i++) {
328676 VerifyScheduledEventsInternal(i, vertices, visited, recursion_stack);
328677 }
328678#endif
328679}

◆ VerifyScheduledEventsInternal()

void duckdb::Executor::VerifyScheduledEventsInternal ( const idx_t i,
const vector< reference< Event > > & vertices,
vector< bool > & visited,
vector< bool > & recursion_stack )
staticprivate
328682 {
328683 D_ASSERT(!recursion_stack[vertex]); // this vertex is in the recursion stack: circular dependency!
328684 if (visited[vertex]) {
328685 return; // early out: we already visited this vertex
328686 }
328687
328688 auto &parents = vertices[vertex].get().GetParentsVerification();
328689 if (parents.empty()) {
328690 return; // early out: outgoing edges
328691 }
328692
328693 // create a vector the indices of the adjacent events
328694 vector<idx_t> adjacent;
328695 const idx_t count = vertices.size();
328696 for (auto parent : parents) {
328697 idx_t i;
328698 for (i = 0; i < count; i++) {
328699 if (RefersToSameObject(vertices[i], parent)) {
328700 adjacent.push_back(i);
328701 break;
328702 }
328703 }
328704 D_ASSERT(i != count); // dependency must be in there somewhere
328705 }
328706
328707 // mark vertex as visited and add to recursion stack
328708 visited[vertex] = true;
328709 recursion_stack[vertex] = true;
328710
328711 // recurse into adjacent vertices
328712 for (const auto &i : adjacent) {
328713 VerifyScheduledEventsInternal(i, vertices, visited, recursion_stack);
328714 }
328715
328716 // remove vertex from recursion stack
328717 recursion_stack[vertex] = false;
328718}

◆ SchedulePipeline()

void duckdb::Executor::SchedulePipeline ( const shared_ptr< MetaPipeline > & pipeline,
ScheduleEventData & event_data )
private
328465 {
328466 D_ASSERT(meta_pipeline);
328467 auto &events = event_data.events;
328468 auto &event_map = event_data.event_map;
328469
328470 // create events/stack for the base pipeline
328471 auto base_pipeline = meta_pipeline->GetBasePipeline();
328472 auto base_initialize_event = make_shared_ptr<PipelineInitializeEvent>(base_pipeline);
328473 auto base_event = make_shared_ptr<PipelineEvent>(base_pipeline);
328474 auto base_prepare_finish_event = make_shared_ptr<PipelinePrepareFinishEvent>(base_pipeline);
328475 auto base_finish_event = make_shared_ptr<PipelineFinishEvent>(base_pipeline);
328476 auto base_complete_event =
328477 make_shared_ptr<PipelineCompleteEvent>(base_pipeline->executor, event_data.initial_schedule);
328478 PipelineEventStack base_stack(*base_initialize_event, *base_event, *base_prepare_finish_event, *base_finish_event,
328479 *base_complete_event);
328480 events.push_back(std::move(base_initialize_event));
328481 events.push_back(std::move(base_event));
328482 events.push_back(std::move(base_prepare_finish_event));
328483 events.push_back(std::move(base_finish_event));
328484 events.push_back(std::move(base_complete_event));
328485
328486 // dependencies: initialize -> event -> prepare finish -> finish -> complete
328487 base_stack.pipeline_event.AddDependency(base_stack.pipeline_initialize_event);
328488 base_stack.pipeline_prepare_finish_event.AddDependency(base_stack.pipeline_event);
328489 base_stack.pipeline_finish_event.AddDependency(base_stack.pipeline_prepare_finish_event);
328490 base_stack.pipeline_complete_event.AddDependency(base_stack.pipeline_finish_event);
328491
328492 // create an event and stack for all pipelines in the MetaPipeline
328493 vector<shared_ptr<Pipeline>> pipelines;
328494 meta_pipeline->GetPipelines(pipelines, false);
328495 for (idx_t i = 1; i < pipelines.size(); i++) { // loop starts at 1 because 0 is the base pipeline
328496 auto &pipeline = pipelines[i];
328497 D_ASSERT(pipeline);
328498
328499 // create events/stack for this pipeline
328500 auto pipeline_event = make_shared_ptr<PipelineEvent>(pipeline);
328501
328502 auto finish_group = meta_pipeline->GetFinishGroup(*pipeline);
328503 if (finish_group) {
328504 // this pipeline is part of a finish group
328505 const auto group_entry = event_map.find(*finish_group.get());
328506 D_ASSERT(group_entry != event_map.end());
328507 auto &group_stack = group_entry->second;
328508 PipelineEventStack pipeline_stack(base_stack.pipeline_initialize_event, *pipeline_event,
328509 group_stack.pipeline_prepare_finish_event,
328510 group_stack.pipeline_finish_event, base_stack.pipeline_complete_event);
328511
328512 // dependencies: base_finish -> pipeline_event -> group_prepare_finish
328513 pipeline_stack.pipeline_event.AddDependency(base_stack.pipeline_finish_event);
328514 group_stack.pipeline_prepare_finish_event.AddDependency(pipeline_stack.pipeline_event);
328515
328516 // add pipeline stack to event map
328517 event_map.insert(make_pair(reference<Pipeline>(*pipeline), pipeline_stack));
328518 } else if (meta_pipeline->HasFinishEvent(*pipeline)) {
328519 // this pipeline has its own finish event (despite going into the same sink - Finalize twice!)
328520 auto pipeline_prepare_finish_event = make_shared_ptr<PipelinePrepareFinishEvent>(pipeline);
328521 auto pipeline_finish_event = make_shared_ptr<PipelineFinishEvent>(pipeline);
328522 PipelineEventStack pipeline_stack(base_stack.pipeline_initialize_event, *pipeline_event,
328523 *pipeline_prepare_finish_event, *pipeline_finish_event,
328524 base_stack.pipeline_complete_event);
328525 events.push_back(std::move(pipeline_prepare_finish_event));
328526 events.push_back(std::move(pipeline_finish_event));
328527
328528 // dependencies:
328529 // base_finish -> pipeline_event -> pipeline_prepare_finish -> pipeline_finish -> base_complete
328530 pipeline_stack.pipeline_event.AddDependency(base_stack.pipeline_finish_event);
328531 pipeline_stack.pipeline_prepare_finish_event.AddDependency(pipeline_stack.pipeline_event);
328532 pipeline_stack.pipeline_finish_event.AddDependency(pipeline_stack.pipeline_prepare_finish_event);
328533 base_stack.pipeline_complete_event.AddDependency(pipeline_stack.pipeline_finish_event);
328534
328535 // add pipeline stack to event map
328536 event_map.insert(make_pair(reference<Pipeline>(*pipeline), pipeline_stack));
328537 } else {
328538 // no additional finish event
328539 PipelineEventStack pipeline_stack(base_stack.pipeline_initialize_event, *pipeline_event,
328540 base_stack.pipeline_prepare_finish_event,
328541 base_stack.pipeline_finish_event, base_stack.pipeline_complete_event);
328542
328543 // dependencies: base_initialize -> pipeline_event -> base_prepare_finish
328544 pipeline_stack.pipeline_event.AddDependency(base_stack.pipeline_initialize_event);
328545 base_stack.pipeline_prepare_finish_event.AddDependency(pipeline_stack.pipeline_event);
328546
328547 // add pipeline stack to event map
328548 event_map.insert(make_pair(reference<Pipeline>(*pipeline), pipeline_stack));
328549 }
328550 events.push_back(std::move(pipeline_event));
328551 }
328552
328553 // add base stack to the event data too
328554 event_map.insert(make_pair(reference<Pipeline>(*base_pipeline), base_stack));
328555
328556 for (auto &pipeline : pipelines) {
328557 auto source = pipeline->GetSource();
328558 if (source->type == PhysicalOperatorType::TABLE_SCAN) {
328559 auto &table_function = source->Cast<PhysicalTableScan>();
328560 if (table_function.function.global_initialization == TableFunctionInitialization::INITIALIZE_ON_SCHEDULE) {
328561 // certain functions have to be eagerly initialized during scheduling
328562 // if that is the case - initialize the function here
328563 pipeline->ResetSource(true);
328564 }
328565 }
328566 }
328567}

◆ NextExecutor()

bool duckdb::Executor::NextExecutor ( )
private
328730 {
328731 if (root_pipeline_idx >= root_pipelines.size()) {
328732 return false;
328733 }
328735 root_executor = make_uniq<PipelineExecutor>(context, *root_pipelines[root_pipeline_idx]);
328737 return true;
328738}

◆ CreateChildPipeline()

shared_ptr< Pipeline > duckdb::Executor::CreateChildPipeline ( Pipeline & current,
PhysicalOperator & op )
private
329042 {
329043 D_ASSERT(!current.operators.empty());
329044 D_ASSERT(op.IsSource());
329045 // found another operator that is a source, schedule a child pipeline
329046 // 'op' is the source, and the sink is the same
329047 auto child_pipeline = make_shared_ptr<Pipeline>(*this);
329048 child_pipeline->sink = current.sink;
329049 child_pipeline->source = &op;
329050
329051 // the child pipeline has the same operators up until 'op'
329052 for (auto current_op : current.operators) {
329053 if (&current_op.get() == &op) {
329054 break;
329055 }
329056 child_pipeline->operators.push_back(current_op);
329057 }
329058
329059 return child_pipeline;
329060}

◆ VerifyPipeline()

void duckdb::Executor::VerifyPipeline ( Pipeline & pipeline)
private
328740 {
328741 D_ASSERT(!pipeline.ToString().empty());
328742 auto operators = pipeline.GetOperators();
328743 for (auto &other_pipeline : pipelines) {
328744 auto other_operators = other_pipeline->GetOperators();
328745 for (idx_t op_idx = 0; op_idx < operators.size(); op_idx++) {
328746 for (idx_t other_idx = 0; other_idx < other_operators.size(); other_idx++) {
328747 auto &left = operators[op_idx].get();
328748 auto &right = other_operators[other_idx].get();
328749 if (left.Equals(right)) {
328750 D_ASSERT(right.Equals(left));
328751 } else {
328752 D_ASSERT(!right.Equals(left));
328753 }
328754 }
328755 }
328756 }
328757}

◆ VerifyPipelines()

void duckdb::Executor::VerifyPipelines ( )
private
328759 {
328760#ifdef DEBUG
328761 for (auto &pipeline : pipelines) {
328762 VerifyPipeline(*pipeline);
328763 }
328764#endif
328765}

The documentation for this class was generated from the following files: