• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

llnl / dftracer-utils / 28496595030

01 Jul 2026 05:50AM UTC coverage: 50.727% (-1.6%) from 52.278%
28496595030

Pull #83

github

web-flow
Merge 8f1ff4df5 into 2efed6649
Pull Request #83: refactor and improve code QoL

31872 of 80367 branches covered (39.66%)

Branch coverage included in aggregate %.

770 of 1591 new or added lines in 85 files covered. (48.4%)

5070 existing lines in 182 files now uncovered.

32742 of 47009 relevant lines covered (69.65%)

9887.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

63.39
/src/dftracer/utils/core/pipeline/executor.cpp
1
#include <dftracer/utils/core/common/logging.h>
2
#include <dftracer/utils/core/common/platform_compat.h>
3
#include <dftracer/utils/core/coro/yield.h>
4
#include <dftracer/utils/core/io/io_backend_factory.h>
5
#include <dftracer/utils/core/pipeline/executor.h>
6
#include <dftracer/utils/core/tasks/coro_scope.h>
7
#include <dftracer/utils/core/tasks/task.h>
8
#include <dftracer/utils/core/utilities/monitor.h>
9

10
#include <chrono>
11
#include <coroutine>
12
#include <exception>
13
#include <vector>
14

15
namespace dftracer::utils {
16

17
static thread_local void* tls_current_worker_context = nullptr;
18

19
void* get_current_worker_context() { return tls_current_worker_context; }
1,557✔
20

21
void set_current_worker_context(void* context) {
3,188✔
22
    tls_current_worker_context = context;
3,188✔
23
}
3,188✔
24

25
static thread_local Executor* tls_current_executor = nullptr;
26

27
Executor* Executor::current() noexcept { return tls_current_executor; }
363,642✔
28

29
Executor* Executor::set_current(Executor* e) noexcept {
716,949✔
30
    auto* old = tls_current_executor;
716,949✔
31
    tls_current_executor = e;
716,949✔
32
    return old;
716,949✔
33
}
34

35
// Thread-local list of coroutine handles to destroy after the current
36
// resume() returns.  FinalAwaiter pushes here instead of the shared
37
// destroy_queue_ to avoid another worker freeing the frame while
38
// the coroutine-suspend machinery is still accessing it.
39
static thread_local std::vector<std::coroutine_handle<>> tls_pending_destroys;
40

41
void schedule_thread_local_destroy(std::coroutine_handle<> h) {
5,125✔
42
    tls_pending_destroys.push_back(h);
5,125✔
43
}
5,125✔
44

45
void drain_thread_local_destroys() {
17,530✔
46
    Executor* exec = Executor::current();
17,530✔
47
    for (auto h : tls_pending_destroys) {
22,670✔
48
        if (!h) continue;
5,140!
49
        if (exec) {
5,140!
50
            exec->schedule_destroy(h);
5,140✔
51
        } else {
5,140✔
52
            h.destroy();
×
53
        }
54
    }
55
    tls_pending_destroys.clear();
17,530✔
56
}
17,530✔
57

58
Executor::Executor(const ExecutorConfig& config)
1,084!
59
    : num_threads_(config.num_threads == 0
60
                       ? dftracer_utils_hardware_concurrency()
61
                       : config.num_threads),
62
      last_activity_ns_(
63
          std::chrono::steady_clock::now().time_since_epoch().count()),
64
      idle_timeout_(config.idle_timeout),
65
      deadlock_timeout_(config.deadlock_timeout),
66
      io_pool_size_(config.io_pool_size == 0
67
                        ? dftracer_utils_hardware_concurrency()
68
                        : config.io_pool_size),
69
      io_backend_type_(config.io_backend_type),
70
      io_batch_threshold_(config.io_batch_threshold) {
542✔
71
    if (num_threads_ == 0) {
542!
72
        num_threads_ = 2;
×
UNCOV
73
    }
×
74
    if (io_pool_size_ == 0) {
542!
75
        io_pool_size_ = 2;
×
UNCOV
76
    }
×
77
#ifdef DFTRACER_UTILS_VALGRIND_MODE
78
    // Per-Executor thread churn dominates runtime when Valgrind serializes and
79
    // instruments every thread, so cap the pools.
80
    if (num_threads_ > 2) num_threads_ = 2;
81
    if (io_pool_size_ > 2) io_pool_size_ = 2;
82
#endif
83
    DFTRACER_UTILS_LOG_DEBUG(
542!
84
        "Executor created with %zu threads, idle_timeout=%lld s, "
85
        "deadlock_timeout=%lld s",
86
        num_threads_, idle_timeout_.count(), deadlock_timeout_.count());
87
}
542✔
88

89
Executor::~Executor() {
1,084✔
90
    shutdown();
542!
91
    drain_destroy_queue();
542!
92
}
1,084✔
93

94
void Executor::start() {
537✔
95
    if (running_) {
537!
96
        DFTRACER_UTILS_LOG_WARN("%s", "Executor already running");
×
97
        return;
×
98
    }
99

100
    running_ = true;
537✔
101
    workers_.clear();
537✔
102
    workers_.reserve(num_threads_);
537✔
103

104
    timer_service_.start();
537✔
105

106
    // Create and start I/O backend before workers so workers
107
    // can use it immediately.
108
    io_backend_ = io::create_io_backend(*this, io_pool_size_, io_backend_type_,
1,074✔
109
                                        io_batch_threshold_);
537✔
110
    io_backend_->start();
537✔
111

112
    // Create all worker contexts first so workers_ is stable before any
113
    // worker thread can try to iterate/steal from it.
114
    for (std::size_t i = 0; i < num_threads_; ++i) {
2,134✔
115
        auto worker = std::make_unique<WorkerContext>(i);
1,597✔
116
        worker->last_activity = std::chrono::steady_clock::now();
1,597✔
117
        workers_.push_back(std::move(worker));
1,597!
118
    }
1,597✔
119

120
    // Start worker threads after all contexts are in place.
121
    for (auto& worker : workers_) {
2,134✔
122
        worker->thread =
1,597✔
123
            std::thread(&Executor::worker_thread, this, worker.get());
1,597✔
124
    }
125

126
    DFTRACER_UTILS_LOG_DEBUG("Executor started with %zu worker threads",
537!
127
                             num_threads_);
128
}
537✔
129

130
void Executor::shutdown() {
1,384✔
131
    if (!running_) {
1,384✔
132
        return;
847✔
133
    }
134

135
    DFTRACER_UTILS_LOG_DEBUG("%s", "Shutting down executor");
537!
136
    running_ = false;
537✔
137
    wake_all_workers();
537✔
138

139
    // Join all worker threads (must happen before io_backend_ is
140
    // destroyed, since workers call io_backend_->poll() when idle).
141
    for (auto& worker : workers_) {
2,134✔
142
        if (worker->thread.joinable()) {
1,597!
143
            worker->thread.join();
1,597✔
144
        }
1,597✔
145
    }
146

147
    // Stop I/O backend AFTER joining workers (workers may poll the
148
    // backend) but BEFORE clearing workers_.  The I/O backend's
149
    // completion thread may still call enqueue() -> wake_all_workers()
150
    // which accesses WorkerContext cv/mutex, so workers_ must remain
151
    // alive until the completion thread has exited.
152
    if (io_backend_) {
537!
153
        io_backend_->stop();
537✔
154
        io_backend_.reset();
537✔
155
    }
537✔
156

157
    // Destroy deferred frames and orphaned run-queue entries BEFORE
158
    // clearing workers_. Frames may hold shared_ptr<Channel> whose
159
    // ConcurrentQueue has TLS producer tokens tied to worker threads.
160
    drain_destroy_queue();
537✔
161
    {
162
        RunQueueEntry orphan;
537✔
163
        while (run_queue_.try_dequeue(orphan)) {
552✔
164
            if (orphan.handle) {
15!
165
                orphan.handle.destroy();
15✔
166
            }
15✔
167
        }
168
    }
169

170
    workers_.clear();
537✔
171
    timer_service_.stop();
537✔
172

173
    // Drain the main thread's thread-local destroy list (for
174
    // coroutines whose FinalAwaiter ran on the main thread).
175
    drain_thread_local_destroys();
537✔
176

177
    DFTRACER_UTILS_LOG_DEBUG("%s", "Executor shutdown complete");
537!
178
}
1,384✔
179

180
void Executor::reset() {
×
181
    // Queue will be reset by caller if needed
UNCOV
182
    DFTRACER_UTILS_LOG_DEBUG("%s", "Executor reset");
×
183
}
×
184

185
void Executor::set_completion_callback(CompletionCallback callback) {
317✔
186
    completion_callback_ = std::move(callback);
317✔
187
}
317✔
188

189
void Executor::worker_thread(WorkerContext* context) {
1,593✔
190
    DFTRACER_UTILS_LOG_DEBUG("Worker %zu started", context->worker_id);
1,593!
191

192
    set_current_worker_context(context);
1,593✔
193
    tls_current_executor = this;
1,593✔
194
    coro::reset_timeslice();
1,593✔
195

196
    // Fixed for the process lifetime; read once to keep the resume loop cheap.
197
    const bool monitor = utilities::monitoring_enabled();
1,593✔
198
    if (monitor) {
1,593!
NEW
199
        utilities::monitor_set_worker(static_cast<int>(context->worker_id));
×
NEW
200
    }
×
201

202
    while (running_) {
34,080✔
203
        RunQueueEntry pending_entry;
32,493✔
204

205
        // Snapshot the work signal BEFORE checking any queues.
206
        // This ensures that any signal increment (from enqueue +
207
        // signal_global_work) that happens AFTER this load will be detected by
208
        // the wait predicate below, even if the actual queue check sees the
209
        // queue as empty. Loading it inside the else branch (after queue
210
        // checks) creates a race: work can arrive between the queue check and
211
        // the signal load, causing the worker to sleep with the updated signal
212
        // value while work sits in the queue.
213
        const std::uint64_t observed_signal =
32,493✔
214
            work_signal_.load(std::memory_order_acquire);
32,493✔
215

216
        // Run queue: coroutine handles from enqueue() and
217
        // schedule_coroutine_resumption().
218
        if (run_queue_.try_dequeue(pending_entry)) {
32,493✔
219
            coro::reset_timeslice();
15,418✔
220
            context->is_idle.store(false, std::memory_order_relaxed);
15,418✔
221
            std::coroutine_handle<> pending_resume = pending_entry.handle;
15,418✔
222
            if (pending_resume && !pending_resume.done()) {
15,418✔
223
                // Id comes from the entry, not the promise: foreign promise
224
                // types have no task_id field.
225
                TaskIndex tid = pending_entry.task_id;
15,413✔
226
                if (tid >= 0) {
15,413!
227
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
228
                    auto it = task_registry_.find(tid);
×
229
                    if (it != task_registry_.end() &&
×
230
                        it->second.state == TaskInfo::QUEUED) {
×
231
                        it->second.state = TaskInfo::RUNNING;
×
232
                        it->second.started_at =
×
233
                            std::chrono::steady_clock::now();
×
234
                        it->second.worker_id = context->worker_id;
×
235
                        it->second.location = TaskInfo::EXECUTING;
×
236
                        ++tasks_started_;
×
UNCOV
237
                    }
×
238
                }
×
239
                DFTRACER_TSAN_ACQUIRE(pending_resume.address());
240
                if (monitor) {
15,413!
NEW
241
                    utilities::monitor_resume_begin(pending_entry.monitor_id);
×
NEW
242
                }
×
243
                pending_resume.resume();
15,413✔
244
                if (monitor) {
15,413!
NEW
245
                    utilities::monitor_resume_end(pending_resume.address(),
×
NEW
246
                                                  pending_resume.done());
×
NEW
247
                }
×
248
            }
15,413✔
249
            // Destroy coroutine frames that FinalAwaiter deferred to this
250
            // thread.  Safe: resume() has fully returned, so the frame
251
            // is suspended at final_suspend and no code references it.
252
            drain_thread_local_destroys();
15,418✔
253
            drain_destroy_queue();
15,418✔
254
        }
15,418✔
255
        // No work available -- sleep until signaled.
256
        else {
257
            context->is_idle.store(true, std::memory_order_relaxed);
17,075✔
258
            // Flush any batched I/O operations before sleeping.
259
            // This ensures pending SQEs are submitted even when no
260
            // new work is arriving (drain trigger).
261
            if (io_backend_) {
17,075✔
262
                io_backend_->flush();
17,021✔
263
            }
17,021✔
264
            // Opportunistic I/O polling before sleeping.
265
            // If the backend has completions, they'll enqueue new
266
            // work, so skip the sleep and retry the run queue.
267
            if (io_backend_) {
17,075✔
268
                auto reaped = io_backend_->poll(0);
17,074✔
269
                if (reaped > 0) {
17,074!
270
                    drain_destroy_queue();
×
271
                    continue;
×
272
                }
273
            }
17,074✔
274
            drain_destroy_queue();
17,075✔
275
            work_signal_.wait(observed_signal, std::memory_order_acquire);
17,075✔
276
        }
277
    }
278

279
    // Final drain: destroy any frames deferred during the last resume().
280
    drain_thread_local_destroys();
1,587✔
281

282
    tls_current_executor = nullptr;
1,587✔
283
    set_current_worker_context(nullptr);
1,587✔
284

285
    DFTRACER_UTILS_LOG_DEBUG("Worker %zu terminated", context->worker_id);
1,587!
286
}
1,587✔
287

288
void Executor::notify_completion(std::shared_ptr<Task> task) {
772✔
289
    // No mutex needed -- the callback is set exactly once during Scheduler
290
    // construction (before any task is submitted) and never modified after.
291
    // on_task_completed uses only atomics, lock-free queues, and properly-
292
    // locked shard mutexes, so concurrent calls from multiple workers are safe.
293
    if (completion_callback_) {
772✔
294
        completion_callback_(task);
771!
295
    }
771✔
296
}
772✔
297

298
void Executor::request_shutdown() {
5✔
299
    if (shutdown_requested_.load()) {
5!
300
        return;  // Already requested
×
301
    }
302

303
    DFTRACER_UTILS_LOG_DEBUG("%s", "Shutdown requested for executor");
5!
304
    shutdown_requested_ = true;
5✔
305
}
5✔
306

307
void Executor::schedule_coroutine_resumption(std::coroutine_handle<> handle) {
5,690✔
308
    // Delegate to enqueue() -- unified path for all coroutine handles.
309
    enqueue(handle);
5,690✔
310
}
5,690✔
311

312
void Executor::signal_global_work() {
15,441✔
313
    work_signal_.fetch_add(1, std::memory_order_acq_rel);
15,441✔
314
    // Wake one worker, not all. Each enqueue adds one unit of work,
315
    // so one worker is sufficient. Avoids thundering herd where all
316
    // N threads wake, N-1 find no work, and go back to sleep.
317
    wake_one_worker();
15,441✔
318
}
15,441✔
319

320
void Executor::wake_one_worker() { work_signal_.notify_one(); }
15,452✔
321

322
void Executor::wake_all_workers() {
537✔
323
    work_signal_.fetch_add(1, std::memory_order_release);
537✔
324
    work_signal_.notify_all();
537✔
325
}
537✔
326

327
// Helper function for when_all.h (avoids circular dependency)
328
void schedule_coroutine_resumption_helper(Executor* executor,
5,691✔
329
                                          std::coroutine_handle<> handle) {
330
    if (executor) {
5,691!
331
        executor->schedule_coroutine_resumption(handle);
5,691✔
332
    }
5,691✔
333
}
5,691✔
334

335
// Helper function for when_any.h (avoids circular dependency)
336
void schedule_destroy_helper(Executor* executor,
6✔
337
                             std::coroutine_handle<> handle) {
338
    if (executor && handle) {
6!
339
        executor->schedule_destroy(handle);
6✔
340
    }
6✔
341
}
6✔
342

343
void Executor::enqueue(std::coroutine_handle<> handle, TaskIndex task_id) {
15,448✔
344
    if (!handle || handle.done()) {
15,448✔
345
        return;  // Invalid or already completed
2✔
346
    }
347

348
    long long monitor_id = -1;
15,446✔
349
    if (utilities::monitoring_enabled()) {
15,446!
350
        // task_id >= 0 marks a tracked submitted task; otherwise it is spawn
351
        // fan-out (or a re-enqueue of an already-seen coroutine).
NEW
352
        monitor_id = utilities::monitor_enqueue(
×
NEW
353
            handle.address(), task_id >= 0 ? utilities::CoroKind::Task
×
354
                                           : utilities::CoroKind::Spawn);
NEW
355
    }
×
356
    DFTRACER_TSAN_RELEASE(handle.address());
357
    run_queue_.enqueue(RunQueueEntry{handle, task_id, monitor_id});
15,446✔
358
    signal_global_work();
15,446✔
359
}
15,446✔
360

361
bool Executor::is_responsive() const {
2✔
362
    // If shutdown was requested, consider unresponsive
363
    if (shutdown_requested_.load()) {
2!
364
        return false;
×
365
    }
366

367
    // If not running, not responsive
368
    if (!running_.load()) {
2!
369
        return false;
×
370
    }
371

372
    // Check if all threads might be deadlocked
373
    // (all threads busy but no progress for a while)
374
    std::size_t started = tasks_started_.load();
2✔
375
    std::size_t completed = tasks_completed_.load();
2✔
376
    std::size_t active = started - completed;
2✔
377

378
    if (active >= num_threads_) {
2✔
379
        // All threads busy - check if making progress
380
        auto now = std::chrono::steady_clock::now();
1✔
381
        auto last_ns = last_activity_ns_.load(std::memory_order_acquire);
1✔
382
        auto last_tp = std::chrono::steady_clock::time_point(
1✔
383
            std::chrono::steady_clock::duration(last_ns));
1✔
384
        auto idle_time = now - last_tp;
1✔
385

386
        // If all threads busy but no activity for deadlock_timeout,
387
        // likely deadlocked
388
        if (idle_time > deadlock_timeout_) {
1!
389
            DFTRACER_UTILS_LOG_WARN(
×
390
                "Executor appears deadlocked: %zu threads, %zu active "
391
                "tasks, idle for %lld ms",
392
                num_threads_, active,
393
                std::chrono::duration_cast<std::chrono::milliseconds>(idle_time)
394
                    .count());
395
            return false;
×
396
        }
397
    }
1✔
398

399
    return true;
2✔
400
}
2✔
401

402
void Executor::mark_activity() {
1,544✔
403
    last_activity_ns_.store(
3,088✔
404
        std::chrono::steady_clock::now().time_since_epoch().count(),
1,544✔
405
        std::memory_order_release);
406
}
1,544✔
407

408
void Executor::update_task_location(TaskIndex task_id,
×
409
                                    TaskInfo::Location location,
410
                                    std::size_t worker_id) {
411
    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
412
    auto it = task_registry_.find(task_id);
×
413
    if (it != task_registry_.end()) {
×
414
        it->second.location = location;
×
415
        if (location == TaskInfo::LOCAL_QUEUE ||
×
UNCOV
416
            location == TaskInfo::EXECUTING) {
×
417
            it->second.worker_id = worker_id;
×
UNCOV
418
        }
×
UNCOV
419
    }
×
420
}
×
421

422
ExecutorProgress Executor::get_progress() const {
21✔
423
    std::shared_lock<std::shared_mutex> lock(registry_mutex_);
21✔
424
    ExecutorProgress progress;
21✔
425

426
    // Overall stats
427
    progress.total_tasks_submitted = total_tasks_submitted_.load();
21✔
428
    progress.tasks_completed = tasks_completed_.load();
21✔
429

430
    // Count task states
431
    progress.tasks_queued = 0;
21✔
432
    progress.tasks_running = 0;
21✔
433
    progress.tasks_failed = 0;
21✔
434

435
    for (const auto& [task_id, info] : task_registry_) {
69!
436
        switch (info.state) {
48!
437
            case TaskInfo::QUEUED:
438
                progress.tasks_queued++;
1✔
439
                break;
1✔
440
            case TaskInfo::RUNNING:
441
            case TaskInfo::WAITING:
442
                progress.tasks_running++;
×
443
                break;
×
444
            case TaskInfo::COMPLETED:
445
                // Already counted
446
                break;
47✔
447
            case TaskInfo::FAILED:
448
                progress.tasks_failed++;
×
449
                break;
×
450
        }
451

452
        if (info.state == TaskInfo::FAILED && !info.error_message.empty()) {
48!
453
            progress.recent_errors.push_back({task_id, info.error_message});
×
UNCOV
454
        }
×
455
    }
456

457
    for (std::size_t i = 0; i < workers_.size(); ++i) {
59✔
458
        // No per-worker local queues anymore; report 0.
459
        progress.worker_queue_depths.push_back(0);
38!
460
    }
38✔
461

462
    // Build task trees (find root tasks)
463
    std::unordered_set<TaskIndex> processed;
21✔
464
    for (const auto& [task_id, info] : task_registry_) {
69!
465
        if (info.parent_task_id == -1) {  // Root task
48✔
466
            auto task_progress = build_task_progress_tree(task_id, processed);
46!
467
            progress.root_tasks.push_back(task_progress);
46!
468
        }
46✔
469
    }
470

471
    // Worker states
472
    for (const auto& worker : workers_) {
59✔
473
        ExecutorProgress::WorkerStatus status;
38✔
474
        status.worker_id = worker->worker_id;
38✔
475
        status.is_idle = worker->is_idle.load();
38✔
476

477
        TaskIndex current_id = worker->current_task_id.load();
38✔
478
        if (current_id != -1) {
38✔
479
            status.current_task_id = current_id;
2!
480
            std::lock_guard<std::mutex> name_lock(worker->task_name_mutex);
2!
481
            status.current_task_name = worker->current_task_name;
2!
482
        }
2✔
483

484
        status.local_queue_depth = 0;
38✔
485

486
        progress.workers.push_back(status);
38!
487
    }
38✔
488

489
    return progress;
21✔
490
}
21!
491

492
TaskProgress Executor::build_task_progress_tree(
48✔
493
    TaskIndex task_id, std::unordered_set<TaskIndex>& processed) const {
494
    TaskProgress progress;
48✔
495

496
    if (processed.count(task_id)) {
48!
497
        // Avoid cycles
498
        progress.task_id = task_id;
×
499
        progress.name = "[Cycle Detected]";
×
500
        return progress;
×
501
    }
502
    processed.insert(task_id);
48!
503

504
    auto it = task_registry_.find(task_id);
48!
505
    if (it == task_registry_.end()) {
48!
506
        progress.task_id = task_id;
×
507
        progress.name = "[Not Found]";
×
508
        return progress;
×
509
    }
510

511
    const TaskInfo& info = it->second;
48!
512
    progress.task_id = task_id;
48✔
513
    progress.name = info.name;
48!
514

515
    // State
516
    switch (info.state) {
48!
517
        case TaskInfo::QUEUED:
518
            progress.state = "queued";
1!
519
            break;
1✔
520
        case TaskInfo::RUNNING:
521
            progress.state = "running";
×
522
            break;
×
523
        case TaskInfo::WAITING:
524
            progress.state = "waiting";
×
525
            break;
×
526
        case TaskInfo::COMPLETED:
527
            progress.state = "completed";
47!
528
            break;
47✔
529
        case TaskInfo::FAILED:
530
            progress.state = "failed";
×
531
            break;
×
532
    }
533

534
    // Timing
535
    auto now = std::chrono::steady_clock::now();
48✔
536
    if (info.state == TaskInfo::QUEUED) {
48✔
537
        progress.queued_duration_ms =
1✔
538
            std::chrono::duration<double, std::milli>(now - info.queued_at)
1!
539
                .count();
1!
540
        progress.execution_duration_ms = 0;
1✔
541
    } else if (info.state == TaskInfo::RUNNING ||
48!
542
               info.state == TaskInfo::WAITING) {
47✔
543
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
×
544
                                          info.started_at - info.queued_at)
×
545
                                          .count();
×
546
        progress.execution_duration_ms =
×
547
            std::chrono::duration<double, std::milli>(now - info.started_at)
×
548
                .count();
×
UNCOV
549
    } else {  // COMPLETED or FAILED
×
550
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
94!
551
                                          info.started_at - info.queued_at)
47!
552
                                          .count();
47!
553
        progress.execution_duration_ms =
47✔
554
            std::chrono::duration<double, std::milli>(info.completed_at -
94!
555
                                                      info.started_at)
47✔
556
                .count();
47!
557
    }
558

559
    // Progress
560
    progress.total_subtasks = info.child_task_ids.size();
48✔
561
    progress.completed_subtasks = info.completed_children.load();
48✔
562
    if (progress.total_subtasks > 0) {
48✔
563
        progress.progress_percentage =
2✔
564
            (100.0 * static_cast<double>(progress.completed_subtasks)) /
4✔
565
            static_cast<double>(progress.total_subtasks);
2✔
566
    } else {
2✔
567
        progress.progress_percentage =
46✔
568
            (info.state == TaskInfo::COMPLETED) ? 100.0 : 0.0;
46✔
569
    }
570

571
    // Location
572
    switch (info.location) {
48!
573
        case TaskInfo::SHARED_QUEUE:
574
            progress.location = "shared_queue";
1!
575
            break;
1✔
576
        case TaskInfo::LOCAL_QUEUE:
UNCOV
577
            progress.location =
×
578
                "worker_" + std::to_string(info.worker_id) + "_local";
×
579
            break;
×
580
        case TaskInfo::EXECUTING:
UNCOV
581
            progress.location =
×
582
                "executing_on_worker_" + std::to_string(info.worker_id);
×
583
            break;
×
584
        case TaskInfo::DONE:
585
            progress.location = "done";
47!
586
            break;
47✔
587
    }
588

589
    // Build children recursively
590
    for (TaskIndex child_id : info.child_task_ids) {
50✔
591
        progress.children.push_back(
2!
592
            build_task_progress_tree(child_id, processed));
2!
593
    }
594

595
    return progress;
48✔
596
}
48!
597

598
// ============================================================================
599
// Phase 3: Coro-based task execution
600
// ============================================================================
601

602
coro::Coro Executor::run_task(std::shared_ptr<Task> task,
8,485!
603
                              std::shared_ptr<std::any> input) {
787!
604
    // Get worker context from TLS (set by worker_thread at start).
605
    auto* context = static_cast<WorkerContext*>(get_current_worker_context());
2,290✔
606

607
    if (!context || !task) {
2,290✔
608
        co_return;
3,823✔
609
    }
610

611
    // Update worker context
612
    context->current_task_id = task->get_id();
2,290✔
613
    {
614
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
773!
615
        context->current_task_name = task->get_name();
773✔
616
    }
773✔
617
    context->last_activity = std::chrono::steady_clock::now();
771✔
618

619
    // Mark task start
620
    mark_activity();
771✔
621
    ++tasks_started_;
772✔
622

623
    // Update task registry to RUNNING
624
    {
625
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
772!
626
        auto it = task_registry_.find(task->get_id());
772!
627
        if (it != task_registry_.end()) {
772!
628
            it->second.state = TaskInfo::RUNNING;
772!
629
            it->second.started_at = std::chrono::steady_clock::now();
772!
630
            it->second.worker_id = context->worker_id;
772!
631
            it->second.location = TaskInfo::EXECUTING;
772!
632
        }
772✔
633
    }
772✔
634

635
    task->result().mark_running();
772!
636

637
    {
638
        CoroScope scope(this);
2,288!
639
        std::exception_ptr task_error;
2,288✔
640

641
        DFTRACER_UTILS_LOG_DEBUG("Worker %zu executing task ID %ld ('%s')",
2,288!
642
                                 context->worker_id, task->get_id(),
643
                                 task->get_name());
644

645
        try {
646
            auto coro_task = task->execute(scope, *input);
2,288!
647
            // Propagate executor to the CoroTask's PromiseBase so that
648
            // nested awaitables (when_any, channel, etc.) can schedule
649
            // resumptions.  run_task() is a Coro (CoroPromise, not
650
            // PromiseBase), so the normal PromiseBase propagation in
651
            // CoroTask::await_suspend doesn't fire.
652
            coro_task.handle().promise().set_executor(this);
2,288✔
653
            std::any result = co_await std::move(coro_task);
3,060!
654

655
            // Set result via TaskResult
656
            task->set_result(std::move(result));
757!
657
        } catch (...) {
770✔
658
            task_error = std::current_exception();
13✔
659
        }
13!
660

661
        // Always join scope to wait for any sub-spawned coroutines.
662
        // Without this, the scope's JoinHandle would be destroyed
663
        // while FinalAwaiters still reference it (use-after-free).
664
        co_await scope.join();
3,088!
665

666
        if (!task_error) {
773✔
667
            DFTRACER_UTILS_LOG_DEBUG(
760!
668
                "Task ID %ld ('%s') completed successfully", task->get_id(),
669
                task->get_name());
670

671
            // Mark task completion
672
            mark_activity();
760!
673
            ++tasks_completed_;
760✔
674
            context->tasks_executed++;
760✔
675

676
            // Update task registry to COMPLETED
677
            {
678
                std::unique_lock<std::shared_mutex> lock(registry_mutex_);
760!
679
                auto it = task_registry_.find(task->get_id());
760✔
680
                if (it != task_registry_.end()) {
760!
681
                    it->second.state = TaskInfo::COMPLETED;
759!
682
                    it->second.completed_at = std::chrono::steady_clock::now();
759!
683
                    it->second.location = TaskInfo::DONE;
759!
684

685
                    // Update parent's completed children count
686
                    if (it->second.parent_task_id != -1) {
759!
687
                        auto parent_it =
409✔
688
                            task_registry_.find(it->second.parent_task_id);
409!
689
                        if (parent_it != task_registry_.end()) {
409!
690
                            parent_it->second.completed_children++;
405!
691
                        }
405✔
692
                    }
409✔
693
                }
759✔
694
            }
760✔
695

696
            // Notify scheduler
697
            notify_completion(task);
760!
698

699
        } else {
758✔
700
            try {
701
                std::rethrow_exception(task_error);
13!
702
            } catch (const std::exception& e) {
13!
703
                DFTRACER_UTILS_LOG_ERROR("Task ID %ld ('%s') failed: %s",
13!
704
                                         task->get_id(), task->get_name(),
705
                                         e.what());
706

707
                task->set_exception(task_error);
13!
708

709
                mark_activity();
13!
710
                ++tasks_completed_;
13✔
711
                context->tasks_executed++;
13✔
712

713
                {
714
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
13!
715
                    auto it = task_registry_.find(task->get_id());
13!
716
                    if (it != task_registry_.end()) {
13!
717
                        it->second.state = TaskInfo::FAILED;
13!
718
                        it->second.completed_at =
13!
719
                            std::chrono::steady_clock::now();
13✔
720
                        it->second.error_message = e.what();
13!
721
                        it->second.location = TaskInfo::DONE;
13!
722
                    }
13✔
723
                }
13✔
724

725
                notify_completion(task);
13!
726

727
            } catch (...) {
13!
UNCOV
728
                DFTRACER_UTILS_LOG_ERROR(
×
729
                    "Task ID %ld ('%s') failed with unknown exception",
730
                    task->get_id(), task->get_name());
731

UNCOV
732
                task->set_exception(task_error);
×
733

UNCOV
734
                mark_activity();
×
UNCOV
735
                ++tasks_completed_;
×
UNCOV
736
                context->tasks_executed++;
×
737

738
                {
UNCOV
739
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
UNCOV
740
                    auto it = task_registry_.find(task->get_id());
×
UNCOV
741
                    if (it != task_registry_.end()) {
×
UNCOV
742
                        it->second.state = TaskInfo::FAILED;
×
UNCOV
743
                        it->second.completed_at =
×
UNCOV
744
                            std::chrono::steady_clock::now();
×
UNCOV
745
                        it->second.error_message = "Unknown exception";
×
UNCOV
746
                        it->second.location = TaskInfo::DONE;
×
UNCOV
747
                    }
×
UNCOV
748
                }
×
749

UNCOV
750
                notify_completion(task);
×
751
            }
13!
752
        }
753
    }
2,318✔
754

755
    // Clear current task info
756
    context->current_task_id = -1;
770✔
757
    {
758
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
770!
759
        context->current_task_name.clear();
770✔
760
    }
770✔
761

762
    co_return;
770✔
763
}
14,514✔
764

765
void Executor::submit_task(std::shared_ptr<Task> task,
787✔
766
                           std::shared_ptr<std::any> input,
767
                           TaskIndex parent_task_id) {
768
    // Register in task registry
769
    {
770
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
787✔
771

772
        auto [it, inserted] = task_registry_.emplace(
3,148!
773
            std::piecewise_construct, std::forward_as_tuple(task->get_id()),
787!
774
            std::forward_as_tuple());
787✔
775

776
        if (inserted) {
787!
777
            it->second.task_id = task->get_id();
787!
778
            it->second.parent_task_id = parent_task_id;
1,574!
779
            it->second.name = task->get_name();
787!
780
            it->second.state = TaskInfo::QUEUED;
787!
781
            it->second.queued_at = std::chrono::steady_clock::now();
1,574!
782
            it->second.location = TaskInfo::SHARED_QUEUE;
787!
783
            it->second.worker_id = static_cast<std::size_t>(-1);
787!
784

785
            if (parent_task_id != -1) {
787✔
786
                auto parent_it = task_registry_.find(parent_task_id);
435!
787
                if (parent_it != task_registry_.end()) {
435!
788
                    parent_it->second.child_task_ids.push_back(task->get_id());
431!
789
                }
431✔
790
            }
435✔
791
        }
787✔
792
    }
787✔
793

794
    ++total_tasks_submitted_;
787✔
795

796
    // Create Coro, set executor on promise, enqueue released handle
797
    auto coro = run_task(std::move(task), std::move(input));
787!
798
    coro.handle().promise().executor = this;
787!
799
    enqueue(coro.release());
787!
800
}
787✔
801

802
TaskIndex Executor::enqueue_tracked(
570✔
803
    coro::Coro coro, std::string name,
804
    std::shared_ptr<std::atomic<TaskIndex>> tid_out) {
805
    TaskIndex id = next_coro_task_id_.fetch_sub(1, std::memory_order_relaxed);
570✔
806
    coro.handle().promise().task_id = id;
570✔
807
    coro.handle().promise().executor = this;
570✔
808

809
    {
810
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
570✔
811
        auto [it, inserted] = task_registry_.emplace(std::piecewise_construct,
1,140!
812
                                                     std::forward_as_tuple(id),
570✔
813
                                                     std::forward_as_tuple());
570✔
814
        if (inserted) {
570!
815
            auto now = std::chrono::steady_clock::now();
570✔
816
            it->second.task_id = id;
1,140!
817
            it->second.parent_task_id = -1;
570!
818
            it->second.name = std::move(name);
570!
819
            it->second.state = TaskInfo::QUEUED;
570!
820
            it->second.queued_at = now;
570!
821
            it->second.location = TaskInfo::SHARED_QUEUE;
570!
822
            it->second.worker_id = static_cast<std::size_t>(-1);
570!
823
        }
570✔
824
    }
570✔
825
    ++total_tasks_submitted_;
570✔
826

827
    if (tid_out) {
570!
828
        tid_out->store(id, std::memory_order_release);
570✔
829
    }
570✔
830

831
    auto handle = coro.release();
570✔
832
    enqueue(handle, id);
570✔
833
    return id;
570✔
UNCOV
834
}
×
835

836
void Executor::mark_coro_completed(TaskIndex id) {
1,140✔
837
    bool was_new = false;
1,140✔
838
    {
839
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
1,140✔
840
        auto it = task_registry_.find(id);
1,140!
841
        if (it != task_registry_.end() &&
2,280!
842
            it->second.state != TaskInfo::COMPLETED) {
1,140!
843
            auto now = std::chrono::steady_clock::now();
570✔
844
            if (it->second.started_at.time_since_epoch().count() == 0) {
570!
845
                it->second.started_at = now;
570!
846
            }
570✔
847
            it->second.state = TaskInfo::COMPLETED;
570!
848
            it->second.completed_at = now;
570!
849
            it->second.location = TaskInfo::DONE;
570!
850
            was_new = true;
570✔
851
        }
570✔
852
    }
1,140✔
853
    if (was_new) ++tasks_completed_;
1,140✔
854
}
1,140✔
855

856
void Executor::schedule_destroy(std::coroutine_handle<> handle) {
5,140✔
857
    if (handle) {
5,140✔
858
        destroy_queue_.enqueue(handle);
5,139✔
859
    }
5,139✔
860
}
5,140✔
861

862
void Executor::drain_destroy_queue() {
33,526✔
863
    std::coroutine_handle<> to_destroy;
33,526✔
864
    while (destroy_queue_.try_dequeue(to_destroy)) {
38,690✔
865
        if (to_destroy) {
5,164✔
866
            to_destroy.destroy();
5,162✔
867
        }
5,162✔
868
    }
869
}
33,526✔
870

871
}  // namespace dftracer::utils
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc