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

llnl / dftracer-utils / 28286012595

27 Jun 2026 10:04AM UTC coverage: 51.056% (-1.3%) from 52.356%
28286012595

Pull #79

github

web-flow
Merge 6c6535a19 into 8eb383f39
Pull Request #79: Add Valgrind memory checking (C++, Python, MPI) and fix the bugs it found

32079 of 80165 branches covered (40.02%)

Branch coverage included in aggregate %.

129 of 149 new or added lines in 11 files covered. (86.58%)

5116 existing lines in 181 files now uncovered.

32739 of 46790 relevant lines covered (69.97%)

9929.31 hits per line

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

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

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

14
namespace dftracer::utils {
15

16
static thread_local void* tls_current_worker_context = nullptr;
17

18
void* get_current_worker_context() { return tls_current_worker_context; }
1,559✔
19

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

24
static thread_local Executor* tls_current_executor = nullptr;
25

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

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

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

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

44
void drain_thread_local_destroys() {
19,096✔
45
    Executor* exec = Executor::current();
19,096✔
46
    for (auto h : tls_pending_destroys) {
24,205✔
47
        if (!h) continue;
5,109!
48
        if (exec) {
5,109!
49
            exec->schedule_destroy(h);
5,109✔
50
        } else {
5,109✔
51
            h.destroy();
×
52
        }
53
    }
54
    tls_pending_destroys.clear();
19,096✔
55
}
19,096✔
56

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

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

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

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

103
    timer_service_.start();
537✔
104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

195
    while (running_) {
42,116✔
196
        RunQueueEntry pending_entry;
40,553✔
197

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

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

265
    // Final drain: destroy any frames deferred during the last resume().
266
    drain_thread_local_destroys();
1,563✔
267

268
    tls_current_executor = nullptr;
1,563✔
269
    set_current_worker_context(nullptr);
1,563✔
270

271
    DFTRACER_UTILS_LOG_DEBUG("Worker %zu terminated", context->worker_id);
272
}
1,563✔
273

274
void Executor::notify_completion(std::shared_ptr<Task> task) {
773✔
275
    // No mutex needed -- the callback is set exactly once during Scheduler
276
    // construction (before any task is submitted) and never modified after.
277
    // on_task_completed uses only atomics, lock-free queues, and properly-
278
    // locked shard mutexes, so concurrent calls from multiple workers are safe.
279
    if (completion_callback_) {
773!
280
        completion_callback_(task);
773!
281
    }
773✔
282
}
773✔
283

284
void Executor::request_shutdown() {
5✔
285
    if (shutdown_requested_.load()) {
5!
286
        return;  // Already requested
×
287
    }
288

289
    DFTRACER_UTILS_LOG_DEBUG("%s", "Shutdown requested for executor");
290
    shutdown_requested_ = true;
5✔
291
}
5✔
292

293
void Executor::schedule_coroutine_resumption(std::coroutine_handle<> handle) {
7,256✔
294
    // Delegate to enqueue() -- unified path for all coroutine handles.
295
    enqueue(handle);
7,256✔
296
}
7,256✔
297

298
void Executor::signal_global_work() {
16,998✔
299
    work_signal_.fetch_add(1, std::memory_order_acq_rel);
16,998✔
300
    // Wake one worker, not all. Each enqueue adds one unit of work,
301
    // so one worker is sufficient. Avoids thundering herd where all
302
    // N threads wake, N-1 find no work, and go back to sleep.
303
    wake_one_worker();
16,998✔
304
}
16,998✔
305

306
void Executor::wake_one_worker() { work_signal_.notify_one(); }
17,012✔
307

308
void Executor::wake_all_workers() {
537✔
309
    work_signal_.fetch_add(1, std::memory_order_release);
537✔
310
    work_signal_.notify_all();
537✔
311
}
537✔
312

313
// Helper function for when_all.h (avoids circular dependency)
314
void schedule_coroutine_resumption_helper(Executor* executor,
7,255✔
315
                                          std::coroutine_handle<> handle) {
316
    if (executor) {
7,255!
317
        executor->schedule_coroutine_resumption(handle);
7,255✔
318
    }
7,255✔
319
}
7,255✔
320

321
// Helper function for when_any.h (avoids circular dependency)
322
void schedule_destroy_helper(Executor* executor,
6✔
323
                             std::coroutine_handle<> handle) {
324
    if (executor && handle) {
6!
325
        executor->schedule_destroy(handle);
6✔
326
    }
6✔
327
}
6✔
328

329
void Executor::enqueue(std::coroutine_handle<> handle, TaskIndex task_id) {
17,010✔
330
    if (!handle || handle.done()) {
17,010✔
331
        return;  // Invalid or already completed
2✔
332
    }
333

334
    DFTRACER_TSAN_RELEASE(handle.address());
335
    run_queue_.enqueue(RunQueueEntry{handle, task_id});
17,010✔
336
    signal_global_work();
17,010✔
337
}
17,010✔
338

339
bool Executor::is_responsive() const {
2✔
340
    // If shutdown was requested, consider unresponsive
341
    if (shutdown_requested_.load()) {
2!
342
        return false;
×
343
    }
344

345
    // If not running, not responsive
346
    if (!running_.load()) {
2!
347
        return false;
×
348
    }
349

350
    // Check if all threads might be deadlocked
351
    // (all threads busy but no progress for a while)
352
    std::size_t started = tasks_started_.load();
2✔
353
    std::size_t completed = tasks_completed_.load();
2✔
354
    std::size_t active = started - completed;
2✔
355

356
    if (active >= num_threads_) {
2✔
357
        // All threads busy - check if making progress
358
        auto now = std::chrono::steady_clock::now();
1✔
359
        auto last_ns = last_activity_ns_.load(std::memory_order_acquire);
1✔
360
        auto last_tp = std::chrono::steady_clock::time_point(
1✔
361
            std::chrono::steady_clock::duration(last_ns));
1✔
362
        auto idle_time = now - last_tp;
1✔
363

364
        // If all threads busy but no activity for deadlock_timeout,
365
        // likely deadlocked
366
        if (idle_time > deadlock_timeout_) {
1!
367
            DFTRACER_UTILS_LOG_WARN(
×
368
                "Executor appears deadlocked: %zu threads, %zu active "
369
                "tasks, idle for %lld ms",
370
                num_threads_, active,
371
                std::chrono::duration_cast<std::chrono::milliseconds>(idle_time)
372
                    .count());
373
            return false;
×
374
        }
375
    }
1✔
376

377
    return true;
2✔
378
}
2✔
379

380
void Executor::mark_activity() {
1,546✔
381
    last_activity_ns_.store(
3,092✔
382
        std::chrono::steady_clock::now().time_since_epoch().count(),
1,546✔
383
        std::memory_order_release);
384
}
1,546✔
385

386
void Executor::update_task_location(TaskIndex task_id,
×
387
                                    TaskInfo::Location location,
388
                                    std::size_t worker_id) {
389
    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
390
    auto it = task_registry_.find(task_id);
×
391
    if (it != task_registry_.end()) {
×
392
        it->second.location = location;
×
393
        if (location == TaskInfo::LOCAL_QUEUE ||
×
UNCOV
394
            location == TaskInfo::EXECUTING) {
×
395
            it->second.worker_id = worker_id;
×
UNCOV
396
        }
×
UNCOV
397
    }
×
398
}
×
399

400
ExecutorProgress Executor::get_progress() const {
21✔
401
    std::shared_lock<std::shared_mutex> lock(registry_mutex_);
21✔
402
    ExecutorProgress progress;
21✔
403

404
    // Overall stats
405
    progress.total_tasks_submitted = total_tasks_submitted_.load();
21✔
406
    progress.tasks_completed = tasks_completed_.load();
21✔
407

408
    // Count task states
409
    progress.tasks_queued = 0;
21✔
410
    progress.tasks_running = 0;
21✔
411
    progress.tasks_failed = 0;
21✔
412

413
    for (const auto& [task_id, info] : task_registry_) {
69!
414
        switch (info.state) {
48!
415
            case TaskInfo::QUEUED:
416
                progress.tasks_queued++;
1✔
417
                break;
1✔
418
            case TaskInfo::RUNNING:
419
            case TaskInfo::WAITING:
420
                progress.tasks_running++;
×
421
                break;
×
422
            case TaskInfo::COMPLETED:
423
                // Already counted
424
                break;
47✔
425
            case TaskInfo::FAILED:
426
                progress.tasks_failed++;
×
427
                break;
×
428
        }
429

430
        if (info.state == TaskInfo::FAILED && !info.error_message.empty()) {
48!
431
            progress.recent_errors.push_back({task_id, info.error_message});
×
UNCOV
432
        }
×
433
    }
434

435
    for (std::size_t i = 0; i < workers_.size(); ++i) {
59✔
436
        // No per-worker local queues anymore; report 0.
437
        progress.worker_queue_depths.push_back(0);
38!
438
    }
38✔
439

440
    // Build task trees (find root tasks)
441
    std::unordered_set<TaskIndex> processed;
21✔
442
    for (const auto& [task_id, info] : task_registry_) {
69!
443
        if (info.parent_task_id == -1) {  // Root task
48✔
444
            auto task_progress = build_task_progress_tree(task_id, processed);
46!
445
            progress.root_tasks.push_back(task_progress);
46!
446
        }
46✔
447
    }
448

449
    // Worker states
450
    for (const auto& worker : workers_) {
59✔
451
        ExecutorProgress::WorkerStatus status;
38✔
452
        status.worker_id = worker->worker_id;
38✔
453
        status.is_idle = worker->is_idle.load();
38✔
454

455
        TaskIndex current_id = worker->current_task_id.load();
38✔
456
        if (current_id != -1) {
38✔
457
            status.current_task_id = current_id;
3!
458
            std::lock_guard<std::mutex> name_lock(worker->task_name_mutex);
3!
459
            status.current_task_name = worker->current_task_name;
3!
460
        }
3✔
461

462
        status.local_queue_depth = 0;
38✔
463

464
        progress.workers.push_back(status);
38!
465
    }
38✔
466

467
    return progress;
21✔
468
}
21!
469

470
TaskProgress Executor::build_task_progress_tree(
48✔
471
    TaskIndex task_id, std::unordered_set<TaskIndex>& processed) const {
472
    TaskProgress progress;
48✔
473

474
    if (processed.count(task_id)) {
48!
475
        // Avoid cycles
476
        progress.task_id = task_id;
×
477
        progress.name = "[Cycle Detected]";
×
478
        return progress;
×
479
    }
480
    processed.insert(task_id);
48!
481

482
    auto it = task_registry_.find(task_id);
48!
483
    if (it == task_registry_.end()) {
48!
484
        progress.task_id = task_id;
×
485
        progress.name = "[Not Found]";
×
486
        return progress;
×
487
    }
488

489
    const TaskInfo& info = it->second;
48!
490
    progress.task_id = task_id;
48✔
491
    progress.name = info.name;
48!
492

493
    // State
494
    switch (info.state) {
48!
495
        case TaskInfo::QUEUED:
496
            progress.state = "queued";
1!
497
            break;
1✔
498
        case TaskInfo::RUNNING:
499
            progress.state = "running";
×
500
            break;
×
501
        case TaskInfo::WAITING:
502
            progress.state = "waiting";
×
503
            break;
×
504
        case TaskInfo::COMPLETED:
505
            progress.state = "completed";
47!
506
            break;
47✔
507
        case TaskInfo::FAILED:
508
            progress.state = "failed";
×
509
            break;
×
510
    }
511

512
    // Timing
513
    auto now = std::chrono::steady_clock::now();
48✔
514
    if (info.state == TaskInfo::QUEUED) {
48✔
515
        progress.queued_duration_ms =
1✔
516
            std::chrono::duration<double, std::milli>(now - info.queued_at)
1!
517
                .count();
1!
518
        progress.execution_duration_ms = 0;
1✔
519
    } else if (info.state == TaskInfo::RUNNING ||
48!
520
               info.state == TaskInfo::WAITING) {
47✔
521
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
×
522
                                          info.started_at - info.queued_at)
×
523
                                          .count();
×
524
        progress.execution_duration_ms =
×
525
            std::chrono::duration<double, std::milli>(now - info.started_at)
×
526
                .count();
×
UNCOV
527
    } else {  // COMPLETED or FAILED
×
528
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
94!
529
                                          info.started_at - info.queued_at)
47!
530
                                          .count();
47!
531
        progress.execution_duration_ms =
47✔
532
            std::chrono::duration<double, std::milli>(info.completed_at -
94!
533
                                                      info.started_at)
47✔
534
                .count();
47!
535
    }
536

537
    // Progress
538
    progress.total_subtasks = info.child_task_ids.size();
48✔
539
    progress.completed_subtasks = info.completed_children.load();
48✔
540
    if (progress.total_subtasks > 0) {
48✔
541
        progress.progress_percentage =
2✔
542
            (100.0 * static_cast<double>(progress.completed_subtasks)) /
4✔
543
            static_cast<double>(progress.total_subtasks);
2✔
544
    } else {
2✔
545
        progress.progress_percentage =
46✔
546
            (info.state == TaskInfo::COMPLETED) ? 100.0 : 0.0;
46✔
547
    }
548

549
    // Location
550
    switch (info.location) {
48!
551
        case TaskInfo::SHARED_QUEUE:
552
            progress.location = "shared_queue";
1!
553
            break;
1✔
554
        case TaskInfo::LOCAL_QUEUE:
UNCOV
555
            progress.location =
×
556
                "worker_" + std::to_string(info.worker_id) + "_local";
×
557
            break;
×
558
        case TaskInfo::EXECUTING:
UNCOV
559
            progress.location =
×
560
                "executing_on_worker_" + std::to_string(info.worker_id);
×
561
            break;
×
562
        case TaskInfo::DONE:
563
            progress.location = "done";
47!
564
            break;
47✔
565
    }
566

567
    // Build children recursively
568
    for (TaskIndex child_id : info.child_task_ids) {
50✔
569
        progress.children.push_back(
2!
570
            build_task_progress_tree(child_id, processed));
2!
571
    }
572

573
    return progress;
48✔
574
}
48!
575

576
// ============================================================================
577
// Phase 3: Coro-based task execution
578
// ============================================================================
579

580
coro::Coro Executor::run_task(std::shared_ptr<Task> task,
8,466!
581
                              std::shared_ptr<std::any> input) {
787!
582
    // Get worker context from TLS (set by worker_thread at start).
583
    auto* context = static_cast<WorkerContext*>(get_current_worker_context());
2,288✔
584

585
    if (!context || !task) {
2,288✔
586
        co_return;
3,819✔
587
    }
588

589
    // Update worker context
590
    context->current_task_id = task->get_id();
2,288✔
591
    {
592
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
773!
593
        context->current_task_name = task->get_name();
773✔
594
    }
775✔
595
    context->last_activity = std::chrono::steady_clock::now();
773✔
596

597
    // Mark task start
598
    mark_activity();
773!
599
    ++tasks_started_;
773✔
600

601
    // Update task registry to RUNNING
602
    {
603
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
773!
604
        auto it = task_registry_.find(task->get_id());
773!
605
        if (it != task_registry_.end()) {
773!
606
            it->second.state = TaskInfo::RUNNING;
773!
607
            it->second.started_at = std::chrono::steady_clock::now();
773!
608
            it->second.worker_id = context->worker_id;
773!
609
            it->second.location = TaskInfo::EXECUTING;
773!
610
        }
773✔
611
    }
773✔
612

613
    task->result().mark_running();
773!
614

615
    {
616
        CoroScope scope(this);
2,288!
617
        std::exception_ptr task_error;
2,288✔
618

619
        DFTRACER_UTILS_LOG_DEBUG("Worker %zu executing task ID %ld ('%s')",
620
                                 context->worker_id, task->get_id(),
621
                                 task->get_name());
622

623
        try {
624
            auto coro_task = task->execute(scope, *input);
2,288!
625
            // Propagate executor to the CoroTask's PromiseBase so that
626
            // nested awaitables (when_any, channel, etc.) can schedule
627
            // resumptions.  run_task() is a Coro (CoroPromise, not
628
            // PromiseBase), so the normal PromiseBase propagation in
629
            // CoroTask::await_suspend doesn't fire.
630
            coro_task.handle().promise().set_executor(this);
2,288✔
631
            std::any result = co_await std::move(coro_task);
3,060!
632

633
            // Set result via TaskResult
634
            task->set_result(std::move(result));
757!
635
        } catch (...) {
770✔
636
            task_error = std::current_exception();
13✔
637
        }
13!
638

639
        // Always join scope to wait for any sub-spawned coroutines.
640
        // Without this, the scope's JoinHandle would be destroyed
641
        // while FinalAwaiters still reference it (use-after-free).
642
        co_await scope.join();
3,078!
643

644
        if (!task_error) {
773✔
645
            DFTRACER_UTILS_LOG_DEBUG(
646
                "Task ID %ld ('%s') completed successfully", task->get_id(),
647
                task->get_name());
648

649
            // Mark task completion
650
            mark_activity();
760!
651
            ++tasks_completed_;
760✔
652
            context->tasks_executed++;
760✔
653

654
            // Update task registry to COMPLETED
655
            {
656
                std::unique_lock<std::shared_mutex> lock(registry_mutex_);
760!
657
                auto it = task_registry_.find(task->get_id());
760!
658
                if (it != task_registry_.end()) {
760!
659
                    it->second.state = TaskInfo::COMPLETED;
760!
660
                    it->second.completed_at = std::chrono::steady_clock::now();
760!
661
                    it->second.location = TaskInfo::DONE;
760!
662

663
                    // Update parent's completed children count
664
                    if (it->second.parent_task_id != -1) {
760!
665
                        auto parent_it =
416✔
666
                            task_registry_.find(it->second.parent_task_id);
416!
667
                        if (parent_it != task_registry_.end()) {
416!
668
                            parent_it->second.completed_children++;
412!
669
                        }
412✔
670
                    }
416✔
671
                }
760✔
672
            }
760✔
673

674
            // Notify scheduler
675
            notify_completion(task);
760!
676

677
        } else {
760✔
678
            try {
679
                std::rethrow_exception(task_error);
13!
680
            } catch (const std::exception& e) {
13!
681
                DFTRACER_UTILS_LOG_ERROR("Task ID %ld ('%s') failed: %s",
13!
682
                                         task->get_id(), task->get_name(),
683
                                         e.what());
684

685
                task->set_exception(task_error);
13!
686

687
                mark_activity();
13!
688
                ++tasks_completed_;
13✔
689
                context->tasks_executed++;
13✔
690

691
                {
692
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
13!
693
                    auto it = task_registry_.find(task->get_id());
13!
694
                    if (it != task_registry_.end()) {
13!
695
                        it->second.state = TaskInfo::FAILED;
13!
696
                        it->second.completed_at =
13!
697
                            std::chrono::steady_clock::now();
13✔
698
                        it->second.error_message = e.what();
13!
699
                        it->second.location = TaskInfo::DONE;
13!
700
                    }
13✔
701
                }
13✔
702

703
                notify_completion(task);
13!
704

705
            } catch (...) {
13!
UNCOV
706
                DFTRACER_UTILS_LOG_ERROR(
×
707
                    "Task ID %ld ('%s') failed with unknown exception",
708
                    task->get_id(), task->get_name());
709

UNCOV
710
                task->set_exception(task_error);
×
711

UNCOV
712
                mark_activity();
×
UNCOV
713
                ++tasks_completed_;
×
UNCOV
714
                context->tasks_executed++;
×
715

716
                {
UNCOV
717
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
UNCOV
718
                    auto it = task_registry_.find(task->get_id());
×
UNCOV
719
                    if (it != task_registry_.end()) {
×
UNCOV
720
                        it->second.state = TaskInfo::FAILED;
×
UNCOV
721
                        it->second.completed_at =
×
UNCOV
722
                            std::chrono::steady_clock::now();
×
UNCOV
723
                        it->second.error_message = "Unknown exception";
×
UNCOV
724
                        it->second.location = TaskInfo::DONE;
×
UNCOV
725
                    }
×
UNCOV
726
                }
×
727

UNCOV
728
                notify_completion(task);
×
729
            }
13!
730
        }
731
    }
2,310✔
732

733
    // Clear current task info
734
    context->current_task_id = -1;
772✔
735
    {
736
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
772!
737
        context->current_task_name.clear();
772✔
738
    }
772✔
739

740
    co_return;
772✔
741
}
11,450✔
742

743
void Executor::submit_task(std::shared_ptr<Task> task,
787✔
744
                           std::shared_ptr<std::any> input,
745
                           TaskIndex parent_task_id) {
746
    // Register in task registry
747
    {
748
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
787✔
749

750
        auto [it, inserted] = task_registry_.emplace(
3,148!
751
            std::piecewise_construct, std::forward_as_tuple(task->get_id()),
787!
752
            std::forward_as_tuple());
787✔
753

754
        if (inserted) {
787!
755
            it->second.task_id = task->get_id();
787!
756
            it->second.parent_task_id = parent_task_id;
1,574!
757
            it->second.name = task->get_name();
787!
758
            it->second.state = TaskInfo::QUEUED;
787!
759
            it->second.queued_at = std::chrono::steady_clock::now();
1,574!
760
            it->second.location = TaskInfo::SHARED_QUEUE;
787!
761
            it->second.worker_id = static_cast<std::size_t>(-1);
787!
762

763
            if (parent_task_id != -1) {
787✔
764
                auto parent_it = task_registry_.find(parent_task_id);
441!
765
                if (parent_it != task_registry_.end()) {
441!
766
                    parent_it->second.child_task_ids.push_back(task->get_id());
437!
767
                }
437✔
768
            }
441✔
769
        }
787✔
770
    }
787✔
771

772
    ++total_tasks_submitted_;
787✔
773

774
    // Create Coro, set executor on promise, enqueue released handle
775
    auto coro = run_task(std::move(task), std::move(input));
787!
776
    coro.handle().promise().executor = this;
787!
777
    enqueue(coro.release());
787!
778
}
787✔
779

780
TaskIndex Executor::enqueue_tracked(
570✔
781
    coro::Coro coro, std::string name,
782
    std::shared_ptr<std::atomic<TaskIndex>> tid_out) {
783
    TaskIndex id = next_coro_task_id_.fetch_sub(1, std::memory_order_relaxed);
570✔
784
    coro.handle().promise().task_id = id;
570✔
785
    coro.handle().promise().executor = this;
570✔
786

787
    {
788
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
570✔
789
        auto [it, inserted] = task_registry_.emplace(std::piecewise_construct,
1,140!
790
                                                     std::forward_as_tuple(id),
570✔
791
                                                     std::forward_as_tuple());
570✔
792
        if (inserted) {
570!
793
            auto now = std::chrono::steady_clock::now();
570✔
794
            it->second.task_id = id;
1,140!
795
            it->second.parent_task_id = -1;
570!
796
            it->second.name = std::move(name);
570!
797
            it->second.state = TaskInfo::QUEUED;
570!
798
            it->second.queued_at = now;
570!
799
            it->second.location = TaskInfo::SHARED_QUEUE;
570!
800
            it->second.worker_id = static_cast<std::size_t>(-1);
570!
801
        }
570✔
802
    }
570✔
803
    ++total_tasks_submitted_;
570✔
804

805
    if (tid_out) {
570!
806
        tid_out->store(id, std::memory_order_release);
570✔
807
    }
570✔
808

809
    auto handle = coro.release();
570✔
810
    enqueue(handle, id);
570✔
811
    return id;
570✔
UNCOV
812
}
×
813

814
void Executor::mark_coro_completed(TaskIndex id) {
1,140✔
815
    bool was_new = false;
1,140✔
816
    {
817
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
1,140✔
818
        auto it = task_registry_.find(id);
1,140!
819
        if (it != task_registry_.end() &&
2,280!
820
            it->second.state != TaskInfo::COMPLETED) {
1,140!
821
            auto now = std::chrono::steady_clock::now();
570✔
822
            if (it->second.started_at.time_since_epoch().count() == 0) {
570!
823
                it->second.started_at = now;
570!
824
            }
570✔
825
            it->second.state = TaskInfo::COMPLETED;
570!
826
            it->second.completed_at = now;
570!
827
            it->second.location = TaskInfo::DONE;
570!
828
            was_new = true;
570✔
829
        }
570✔
830
    }
1,140✔
831
    if (was_new) ++tasks_completed_;
1,140✔
832
}
1,140✔
833

834
void Executor::schedule_destroy(std::coroutine_handle<> handle) {
5,111✔
835
    if (handle) {
5,111✔
836
        destroy_queue_.enqueue(handle);
5,121✔
837
    }
5,121✔
838
}
5,131✔
839

840
void Executor::drain_destroy_queue() {
41,549✔
841
    std::coroutine_handle<> to_destroy;
41,549✔
842
    while (destroy_queue_.try_dequeue(to_destroy)) {
46,704✔
843
        if (to_destroy) {
5,155✔
844
            to_destroy.destroy();
5,144✔
845
        }
5,144✔
846
    }
847
}
41,549✔
848

849
}  // 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