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

llnl / dftracer-utils / 28982597416

08 Jul 2026 11:22PM UTC coverage: 50.709% (-1.9%) from 52.577%
28982597416

Pull #87

github

web-flow
Merge fdf73a826 into 4908d9921
Pull Request #87: fix(comparator): fix wrong counting files

16259 of 43579 branches covered (37.31%)

Branch coverage included in aggregate %.

37 of 38 new or added lines in 4 files covered. (97.37%)

616 existing lines in 111 files now uncovered.

21634 of 31148 relevant lines covered (69.46%)

13117.41 hits per line

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

66.34
/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
#include <zlib.h>
10

11
#include <chrono>
12
#include <coroutine>
13
#include <exception>
14
#include <mutex>
15
#include <vector>
16

17
namespace dftracer::utils {
18

19
namespace {
20

21
// Force zlib-ng's lazy CPU-feature functable init single-threaded before any
22
// worker spawns, so concurrent first-use does not race on the global table.
23
void warmup_vendored_libs() noexcept {
132✔
24
    unsigned char src[64];
25
    for (std::size_t i = 0; i < sizeof(src); ++i) {
8,580✔
26
        src[i] = static_cast<unsigned char>(i);
8,448✔
27
    }
28
    unsigned char comp[128];
29
    unsigned char back[64];
30

31
    z_stream def{};
132✔
32
    if (deflateInit2(&def, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
132✔
33
                     Z_DEFAULT_STRATEGY) == Z_OK) {
132!
34
        def.next_in = src;
132✔
35
        def.avail_in = sizeof(src);
132✔
36
        def.next_out = comp;
132✔
37
        def.avail_out = sizeof(comp);
132✔
38
        deflate(&def, Z_FINISH);
132✔
39
        uInt comp_len = static_cast<uInt>(sizeof(comp) - def.avail_out);
132✔
40
        deflateEnd(&def);
132✔
41

42
        z_stream inf{};
132✔
43
        if (inflateInit2(&inf, 31) == Z_OK) {
132!
44
            inf.next_in = comp;
132✔
45
            inf.avail_in = comp_len;
132✔
46
            inf.next_out = back;
132✔
47
            inf.avail_out = sizeof(back);
132✔
48
            inflate(&inf, Z_FINISH);
132✔
49
            inflateEnd(&inf);
132✔
50
        }
51
    }
52
}
132✔
53

54
}  // namespace
55

56
static thread_local void* tls_current_worker_context = nullptr;
57

58
void* get_current_worker_context() { return tls_current_worker_context; }
1,581✔
59

60
void set_current_worker_context(void* context) {
3,481✔
61
    tls_current_worker_context = context;
3,481✔
62
}
3,481✔
63

64
static thread_local Executor* tls_current_executor = nullptr;
65

66
Executor* Executor::current() noexcept { return tls_current_executor; }
356,722✔
67

68
Executor* Executor::set_current(Executor* e) noexcept {
711,329✔
69
    auto* old = tls_current_executor;
711,329✔
70
    tls_current_executor = e;
711,329✔
71
    return old;
711,329✔
72
}
73

74
// Thread-local list of coroutine handles to destroy after the current
75
// resume() returns.  FinalAwaiter pushes here instead of the shared
76
// destroy_queue_ to avoid another worker freeing the frame while
77
// the coroutine-suspend machinery is still accessing it.
78
static thread_local std::vector<std::coroutine_handle<>> tls_pending_destroys;
79

80
void schedule_thread_local_destroy(std::coroutine_handle<> h) {
5,270✔
81
    tls_pending_destroys.push_back(h);
5,270✔
82
}
5,143✔
83

84
void drain_thread_local_destroys() {
19,104✔
85
    Executor* exec = Executor::current();
19,104✔
86
    for (auto h : tls_pending_destroys) {
24,332✔
87
        if (!h) continue;
5,274!
88
        if (exec) {
5,224!
89
            exec->schedule_destroy(h);
5,224!
90
        } else {
91
            h.destroy();
×
92
        }
93
    }
94
    tls_pending_destroys.clear();
19,043✔
95
}
18,938✔
96

97
Executor::Executor(const ExecutorConfig& config)
549✔
98
    : num_threads_(config.num_threads == 0
1,098✔
99
                       ? dftracer_utils_hardware_concurrency()
549!
100
                       : config.num_threads),
101
      last_activity_ns_(
549✔
102
          std::chrono::steady_clock::now().time_since_epoch().count()),
549✔
103
      idle_timeout_(config.idle_timeout),
549✔
104
      deadlock_timeout_(config.deadlock_timeout),
549✔
105
      io_pool_size_(config.io_pool_size == 0
1,098✔
106
                        ? dftracer_utils_hardware_concurrency()
549✔
107
                        : config.io_pool_size),
108
      io_backend_type_(config.io_backend_type),
549✔
109
      io_batch_threshold_(config.io_batch_threshold) {
1,647!
110
    if (num_threads_ == 0) {
549!
111
        num_threads_ = 2;
×
112
    }
113
    if (io_pool_size_ == 0) {
549!
114
        io_pool_size_ = 2;
×
115
    }
116
#ifdef DFTRACER_UTILS_VALGRIND_MODE
117
    // Per-Executor thread churn dominates runtime when Valgrind serializes and
118
    // instruments every thread, so cap the pools.
119
    if (num_threads_ > 2) num_threads_ = 2;
120
    if (io_pool_size_ > 2) io_pool_size_ = 2;
121
#endif
122
    DFTRACER_UTILS_LOG_DEBUG(
549!
123
        "Executor created with %zu threads, idle_timeout=%lld s, "
124
        "deadlock_timeout=%lld s",
125
        num_threads_, static_cast<long long>(idle_timeout_.count()),
126
        static_cast<long long>(deadlock_timeout_.count()));
127
}
549✔
128

129
Executor::~Executor() {
549✔
130
    shutdown();
549✔
131
    drain_destroy_queue();
549✔
132
}
549✔
133

134
void Executor::start() {
544✔
135
    if (running_) {
544!
136
        DFTRACER_UTILS_LOG_WARN("%s", "Executor already running");
×
137
        return;
×
138
    }
139

140
    running_ = true;
544✔
141
    workers_.clear();
544✔
142
    workers_.reserve(num_threads_);
544✔
143

144
    static std::once_flag warmup_once;
145
    std::call_once(warmup_once, warmup_vendored_libs);
544✔
146

147
    timer_service_.start();
544✔
148

149
    // Create and start I/O backend before workers so workers
150
    // can use it immediately.
151
    io_backend_ = io::create_io_backend(*this, io_pool_size_, io_backend_type_,
1,088✔
152
                                        io_batch_threshold_);
544✔
153
    io_backend_->start();
544✔
154

155
    // Create all worker contexts first so workers_ is stable before any
156
    // worker thread can try to iterate/steal from it.
157
    for (std::size_t i = 0; i < num_threads_; ++i) {
2,289✔
158
        auto worker = std::make_unique<WorkerContext>(i);
1,745!
159
        worker->last_activity = std::chrono::steady_clock::now();
1,745✔
160
        workers_.push_back(std::move(worker));
1,745!
161
    }
1,745✔
162

163
    // Start worker threads after all contexts are in place.
164
    for (auto& worker : workers_) {
2,289✔
165
        worker->thread =
1,745✔
166
            std::thread(&Executor::worker_thread, this, worker.get());
3,490!
167
    }
168

169
    DFTRACER_UTILS_LOG_DEBUG("Executor started with %zu worker threads",
544✔
170
                             num_threads_);
171
}
172

173
void Executor::shutdown() {
1,404✔
174
    if (!running_) {
1,404✔
175
        return;
860✔
176
    }
177

178
    DFTRACER_UTILS_LOG_DEBUG("%s", "Shutting down executor");
544✔
179
    running_ = false;
544✔
180
    wake_all_workers();
544✔
181

182
    // Join all worker threads (must happen before io_backend_ is
183
    // destroyed, since workers call io_backend_->poll() when idle).
184
    for (auto& worker : workers_) {
2,289✔
185
        if (worker->thread.joinable()) {
1,745!
186
            worker->thread.join();
1,745!
187
        }
188
    }
189

190
    // Stop I/O backend AFTER joining workers (workers may poll the
191
    // backend) but BEFORE clearing workers_.  The I/O backend's
192
    // completion thread may still call enqueue() -> wake_all_workers()
193
    // which accesses WorkerContext cv/mutex, so workers_ must remain
194
    // alive until the completion thread has exited.
195
    if (io_backend_) {
544!
196
        io_backend_->stop();
544✔
197
        io_backend_.reset();
544✔
198
    }
199

200
    // Destroy deferred frames and orphaned run-queue entries BEFORE
201
    // clearing workers_. Frames may hold shared_ptr<Channel> whose
202
    // ConcurrentQueue has TLS producer tokens tied to worker threads.
203
    drain_destroy_queue();
544✔
204
    {
205
        RunQueueEntry orphan;
544✔
206
        while (run_queue_.try_dequeue(orphan)) {
559!
207
            if (orphan.handle) {
15!
208
                orphan.handle.destroy();
15!
209
            }
210
        }
211
    }
212

213
    workers_.clear();
544✔
214
    timer_service_.stop();
544✔
215

216
    // Drain the main thread's thread-local destroy list (for
217
    // coroutines whose FinalAwaiter ran on the main thread).
218
    drain_thread_local_destroys();
544✔
219

220
    DFTRACER_UTILS_LOG_DEBUG("%s", "Executor shutdown complete");
544✔
221
}
222

223
void Executor::reset() {
×
224
    // Queue will be reset by caller if needed
225
    DFTRACER_UTILS_LOG_DEBUG("%s", "Executor reset");
×
226
}
×
227

228
void Executor::set_completion_callback(CompletionCallback callback) {
323✔
229
    completion_callback_ = std::move(callback);
323✔
230
}
323✔
231

232
void Executor::worker_thread(WorkerContext* context) {
1,745✔
233
    DFTRACER_UTILS_LOG_DEBUG("Worker %zu started", context->worker_id);
1,745✔
234

235
    set_current_worker_context(context);
1,745✔
236
    tls_current_executor = this;
1,745✔
237
    coro::reset_timeslice();
1,745✔
238

239
    // Fixed for the process lifetime; read once to keep the resume loop cheap.
240
    const bool monitor = utilities::monitoring_enabled();
1,745✔
241
    if (monitor) {
1,745!
242
        utilities::monitor_set_worker(static_cast<int>(context->worker_id));
×
243
    }
244

245
    while (running_) {
49,765✔
246
        RunQueueEntry pending_entry;
47,950✔
247

248
        // Snapshot the work signal BEFORE checking any queues.
249
        // This ensures that any signal increment (from enqueue +
250
        // signal_global_work) that happens AFTER this load will be detected by
251
        // the wait predicate below, even if the actual queue check sees the
252
        // queue as empty. Loading it inside the else branch (after queue
253
        // checks) creates a race: work can arrive between the queue check and
254
        // the signal load, causing the worker to sleep with the updated signal
255
        // value while work sits in the queue.
256
        const std::uint64_t observed_signal =
257
            work_signal_.load(std::memory_order_acquire);
47,950✔
258

259
        // Run queue: coroutine handles from enqueue() and
260
        // schedule_coroutine_resumption().
261
        if (run_queue_.try_dequeue(pending_entry)) {
47,893!
262
            coro::reset_timeslice();
16,787✔
263
            context->is_idle.store(false, std::memory_order_relaxed);
16,750✔
264
            std::coroutine_handle<> pending_resume = pending_entry.handle;
16,849✔
265
            if (pending_resume && !pending_resume.done()) {
16,849!
266
                // Id comes from the entry, not the promise: foreign promise
267
                // types have no task_id field.
268
                TaskIndex tid = pending_entry.task_id;
16,812✔
269
                if (tid >= 0) {
16,812!
270
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
271
                    auto it = task_registry_.find(tid);
×
272
                    if (it != task_registry_.end() &&
×
273
                        it->second.state == TaskInfo::QUEUED) {
×
274
                        it->second.state = TaskInfo::RUNNING;
×
275
                        it->second.started_at =
×
276
                            std::chrono::steady_clock::now();
×
277
                        it->second.worker_id = context->worker_id;
×
278
                        it->second.location = TaskInfo::EXECUTING;
×
279
                        ++tasks_started_;
×
280
                    }
281
                }
×
282
                DFTRACER_TSAN_ACQUIRE(pending_resume.address());
283
                if (monitor) {
16,812!
284
                    utilities::monitor_resume_begin(pending_entry.monitor_id);
×
285
                }
286
                pending_resume.resume();
16,812!
287
                if (monitor) {
16,836!
288
                    utilities::monitor_resume_end(pending_resume.address(),
×
289
                                                  pending_resume.done());
×
290
                }
291
            }
292
            // Destroy coroutine frames that FinalAwaiter deferred to this
293
            // thread.  Safe: resume() has fully returned, so the frame
294
            // is suspended at final_suspend and no code references it.
295
            drain_thread_local_destroys();
16,837!
296
            drain_destroy_queue();
16,692!
297
        }
298
        // No work available -- sleep until signaled.
299
        else {
300
            context->is_idle.store(true, std::memory_order_relaxed);
31,113✔
301
            // Flush any batched I/O operations before sleeping.
302
            // This ensures pending SQEs are submitted even when no
303
            // new work is arriving (drain trigger).
304
            if (io_backend_) {
31,392!
305
                io_backend_->flush();
31,261!
306
            }
307
            // Opportunistic I/O polling before sleeping.
308
            // If the backend has completions, they'll enqueue new
309
            // work, so skip the sleep and retry the run queue.
310
            if (io_backend_) {
31,555✔
311
                auto reaped = io_backend_->poll(0);
31,539!
312
                if (reaped > 0) {
31,527!
313
                    drain_destroy_queue();
×
314
                    continue;
×
315
                }
316
            }
317
            drain_destroy_queue();
31,542!
318
            // Re-check after snapshotting the signal: shutdown()'s bump may
319
            // have landed post-snapshot, so wait() would park forever.
320
            if (!running_.load(std::memory_order_acquire)) {
31,463✔
321
                break;
9✔
322
            }
323
            work_signal_.wait(observed_signal, std::memory_order_acquire);
31,448✔
324
        }
325
    }
326

327
    // Final drain: destroy any frames deferred during the last resume().
328
    drain_thread_local_destroys();
1,591✔
329

330
    tls_current_executor = nullptr;
1,728✔
331
    set_current_worker_context(nullptr);
1,728✔
332

333
    DFTRACER_UTILS_LOG_DEBUG("Worker %zu terminated", context->worker_id);
1,731✔
334
}
1,698✔
335

336
void Executor::notify_completion(std::shared_ptr<Task> task) {
784✔
337
    // No mutex needed -- the callback is set exactly once during Scheduler
338
    // construction (before any task is submitted) and never modified after.
339
    // on_task_completed uses only atomics, lock-free queues, and properly-
340
    // locked shard mutexes, so concurrent calls from multiple workers are safe.
341
    if (completion_callback_) {
784!
342
        completion_callback_(task);
784!
343
    }
344
}
782✔
345

346
void Executor::request_shutdown() {
5✔
347
    if (shutdown_requested_.load()) {
5!
348
        return;  // Already requested
×
349
    }
350

351
    DFTRACER_UTILS_LOG_DEBUG("%s", "Shutdown requested for executor");
5!
352
    shutdown_requested_ = true;
5✔
353
}
354

355
void Executor::schedule_coroutine_resumption(std::coroutine_handle<> handle) {
6,932✔
356
    // Delegate to enqueue() -- unified path for all coroutine handles.
357
    enqueue(handle);
6,932✔
358
}
6,930✔
359

360
void Executor::signal_global_work() {
16,910✔
361
    work_signal_.fetch_add(1, std::memory_order_acq_rel);
16,910✔
362
    // Wake one worker, not all. Each enqueue adds one unit of work,
363
    // so one worker is sufficient. Avoids thundering herd where all
364
    // N threads wake, N-1 find no work, and go back to sleep.
365
    wake_one_worker();
16,910✔
366
}
16,909✔
367

368
void Executor::wake_one_worker() { work_signal_.notify_one(); }
16,912✔
369

370
void Executor::wake_all_workers() {
544✔
371
    work_signal_.fetch_add(1, std::memory_order_release);
544✔
372
    work_signal_.notify_all();
544✔
373
}
544✔
374

375
// Helper function for when_all.h (avoids circular dependency)
376
void schedule_coroutine_resumption_helper(Executor* executor,
6,932✔
377
                                          std::coroutine_handle<> handle) {
378
    if (executor) {
6,932!
379
        executor->schedule_coroutine_resumption(handle);
6,932✔
380
    }
381
}
6,933✔
382

383
// Helper function for when_any.h (avoids circular dependency)
384
void schedule_destroy_helper(Executor* executor,
7✔
385
                             std::coroutine_handle<> handle) {
386
    if (executor && handle) {
7!
387
        executor->schedule_destroy(handle);
7✔
388
    }
389
}
7✔
390

391
void Executor::enqueue(std::coroutine_handle<> handle, TaskIndex task_id) {
16,910✔
392
    if (!handle || handle.done()) {
16,910!
UNCOV
393
        return;  // Invalid or already completed
×
394
    }
395

396
    long long monitor_id = -1;
16,910✔
397
    if (utilities::monitoring_enabled()) {
16,910!
398
        // task_id >= 0 marks a tracked submitted task; otherwise it is spawn
399
        // fan-out (or a re-enqueue of an already-seen coroutine).
400
        monitor_id = utilities::monitor_enqueue(
×
401
            handle.address(), task_id >= 0 ? utilities::CoroKind::Task
×
402
                                           : utilities::CoroKind::Spawn);
403
    }
404
    DFTRACER_TSAN_RELEASE(handle.address());
405
    run_queue_.enqueue(RunQueueEntry{handle, task_id, monitor_id});
16,908!
406
    signal_global_work();
16,910✔
407
}
408

409
bool Executor::is_responsive() const {
2✔
410
    // If shutdown was requested, consider unresponsive
411
    if (shutdown_requested_.load()) {
2!
412
        return false;
×
413
    }
414

415
    // If not running, not responsive
416
    if (!running_.load()) {
2!
417
        return false;
×
418
    }
419

420
    // Check if all threads might be deadlocked
421
    // (all threads busy but no progress for a while)
422
    std::size_t started = tasks_started_.load();
2✔
423
    std::size_t completed = tasks_completed_.load();
2✔
424
    std::size_t active = started - completed;
2✔
425

426
    if (active >= num_threads_) {
2✔
427
        // All threads busy - check if making progress
428
        auto now = std::chrono::steady_clock::now();
1✔
429
        auto last_ns = last_activity_ns_.load(std::memory_order_acquire);
1✔
430
        auto last_tp = std::chrono::steady_clock::time_point(
431
            std::chrono::steady_clock::duration(last_ns));
1✔
432
        auto idle_time = now - last_tp;
1!
433

434
        // If all threads busy but no activity for deadlock_timeout,
435
        // likely deadlocked
436
        if (idle_time > deadlock_timeout_) {
1!
437
            DFTRACER_UTILS_LOG_WARN(
×
438
                "Executor appears deadlocked: %zu threads, %zu active "
439
                "tasks, idle for %lld ms",
440
                num_threads_, active,
441
                static_cast<long long>(
442
                    std::chrono::duration_cast<std::chrono::milliseconds>(
443
                        idle_time)
444
                        .count()));
445
            return false;
×
446
        }
447
    }
448

449
    return true;
2✔
450
}
451

452
void Executor::mark_activity() {
1,563✔
453
    last_activity_ns_.store(
1,552✔
454
        std::chrono::steady_clock::now().time_since_epoch().count(),
1,563✔
455
        std::memory_order_release);
456
}
1,565✔
457

458
void Executor::update_task_location(TaskIndex task_id,
×
459
                                    TaskInfo::Location location,
460
                                    std::size_t worker_id) {
461
    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
×
462
    auto it = task_registry_.find(task_id);
×
463
    if (it != task_registry_.end()) {
×
464
        it->second.location = location;
×
465
        if (location == TaskInfo::LOCAL_QUEUE ||
×
466
            location == TaskInfo::EXECUTING) {
467
            it->second.worker_id = worker_id;
×
468
        }
469
    }
470
}
×
471

472
ExecutorProgress Executor::get_progress() const {
21✔
473
    std::shared_lock<std::shared_mutex> lock(registry_mutex_);
21!
474
    ExecutorProgress progress;
21✔
475

476
    // Overall stats
477
    progress.total_tasks_submitted = total_tasks_submitted_.load();
21✔
478
    progress.tasks_completed = tasks_completed_.load();
21✔
479

480
    // Count task states
481
    progress.tasks_queued = 0;
21✔
482
    progress.tasks_running = 0;
21✔
483
    progress.tasks_failed = 0;
21✔
484

485
    for (const auto& [task_id, info] : task_registry_) {
69✔
486
        switch (info.state) {
48!
487
            case TaskInfo::QUEUED:
1✔
488
                progress.tasks_queued++;
1✔
489
                break;
1✔
UNCOV
490
            case TaskInfo::RUNNING:
×
491
            case TaskInfo::WAITING:
UNCOV
492
                progress.tasks_running++;
×
UNCOV
493
                break;
×
494
            case TaskInfo::COMPLETED:
47✔
495
                // Already counted
496
                break;
47✔
UNCOV
497
            case TaskInfo::FAILED:
×
498
                progress.tasks_failed++;
×
499
                break;
×
500
        }
501

502
        if (info.state == TaskInfo::FAILED && !info.error_message.empty()) {
48!
503
            progress.recent_errors.push_back({task_id, info.error_message});
×
504
        }
505
    }
506

507
    for (std::size_t i = 0; i < workers_.size(); ++i) {
59✔
508
        // No per-worker local queues anymore; report 0.
509
        progress.worker_queue_depths.push_back(0);
38!
510
    }
511

512
    // Build task trees (find root tasks)
513
    std::unordered_set<TaskIndex> processed;
42✔
514
    for (const auto& [task_id, info] : task_registry_) {
69✔
515
        if (info.parent_task_id == -1) {  // Root task
48✔
516
            auto task_progress = build_task_progress_tree(task_id, processed);
46!
517
            progress.root_tasks.push_back(task_progress);
46!
518
        }
46✔
519
    }
520

521
    // Worker states
522
    for (const auto& worker : workers_) {
59✔
523
        ExecutorProgress::WorkerStatus status;
38✔
524
        status.worker_id = worker->worker_id;
38✔
525
        status.is_idle = worker->is_idle.load();
38✔
526

527
        TaskIndex current_id = worker->current_task_id.load();
38✔
528
        if (current_id != -1) {
38✔
529
            status.current_task_id = current_id;
3✔
530
            std::lock_guard<std::mutex> name_lock(worker->task_name_mutex);
3!
531
            status.current_task_name = worker->current_task_name;
3!
532
        }
3✔
533

534
        status.local_queue_depth = 0;
38✔
535

536
        progress.workers.push_back(status);
38!
537
    }
38✔
538

539
    return progress;
42✔
540
}
21✔
541

542
TaskProgress Executor::build_task_progress_tree(
48✔
543
    TaskIndex task_id, std::unordered_set<TaskIndex>& processed) const {
544
    TaskProgress progress;
48✔
545

546
    if (processed.count(task_id)) {
48!
547
        // Avoid cycles
548
        progress.task_id = task_id;
×
549
        progress.name = "[Cycle Detected]";
×
550
        return progress;
×
551
    }
552
    processed.insert(task_id);
48!
553

554
    auto it = task_registry_.find(task_id);
48!
555
    if (it == task_registry_.end()) {
48!
556
        progress.task_id = task_id;
×
557
        progress.name = "[Not Found]";
×
558
        return progress;
×
559
    }
560

561
    const TaskInfo& info = it->second;
48✔
562
    progress.task_id = task_id;
48✔
563
    progress.name = info.name;
48!
564

565
    // State
566
    switch (info.state) {
48!
567
        case TaskInfo::QUEUED:
1✔
568
            progress.state = "queued";
1!
569
            break;
1✔
UNCOV
570
        case TaskInfo::RUNNING:
×
UNCOV
571
            progress.state = "running";
×
UNCOV
572
            break;
×
UNCOV
573
        case TaskInfo::WAITING:
×
574
            progress.state = "waiting";
×
575
            break;
×
576
        case TaskInfo::COMPLETED:
47✔
577
            progress.state = "completed";
47!
578
            break;
47✔
UNCOV
579
        case TaskInfo::FAILED:
×
580
            progress.state = "failed";
×
581
            break;
×
582
    }
583

584
    // Timing
585
    auto now = std::chrono::steady_clock::now();
48✔
586
    if (info.state == TaskInfo::QUEUED) {
48✔
587
        progress.queued_duration_ms =
1✔
588
            std::chrono::duration<double, std::milli>(now - info.queued_at)
1!
589
                .count();
1✔
590
        progress.execution_duration_ms = 0;
1✔
591
    } else if (info.state == TaskInfo::RUNNING ||
47!
592
               info.state == TaskInfo::WAITING) {
47!
UNCOV
593
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
×
UNCOV
594
                                          info.started_at - info.queued_at)
×
UNCOV
595
                                          .count();
×
UNCOV
596
        progress.execution_duration_ms =
×
UNCOV
597
            std::chrono::duration<double, std::milli>(now - info.started_at)
×
UNCOV
598
                .count();
×
599
    } else {  // COMPLETED or FAILED
600
        progress.queued_duration_ms = std::chrono::duration<double, std::milli>(
47!
601
                                          info.started_at - info.queued_at)
47!
602
                                          .count();
47✔
603
        progress.execution_duration_ms =
47✔
604
            std::chrono::duration<double, std::milli>(info.completed_at -
94!
605
                                                      info.started_at)
47!
606
                .count();
47✔
607
    }
608

609
    // Progress
610
    progress.total_subtasks = info.child_task_ids.size();
48✔
611
    progress.completed_subtasks = info.completed_children.load();
48✔
612
    if (progress.total_subtasks > 0) {
48✔
613
        progress.progress_percentage =
2✔
614
            (100.0 * static_cast<double>(progress.completed_subtasks)) /
2✔
615
            static_cast<double>(progress.total_subtasks);
2✔
616
    } else {
617
        progress.progress_percentage =
46✔
618
            (info.state == TaskInfo::COMPLETED) ? 100.0 : 0.0;
46✔
619
    }
620

621
    // Location
622
    switch (info.location) {
48!
623
        case TaskInfo::SHARED_QUEUE:
1✔
624
            progress.location = "shared_queue";
1!
625
            break;
1✔
UNCOV
626
        case TaskInfo::LOCAL_QUEUE:
×
627
            progress.location =
628
                "worker_" + std::to_string(info.worker_id) + "_local";
×
629
            break;
×
UNCOV
630
        case TaskInfo::EXECUTING:
×
631
            progress.location =
UNCOV
632
                "executing_on_worker_" + std::to_string(info.worker_id);
×
UNCOV
633
            break;
×
634
        case TaskInfo::DONE:
47✔
635
            progress.location = "done";
47!
636
            break;
47✔
637
    }
638

639
    // Build children recursively
640
    for (TaskIndex child_id : info.child_task_ids) {
50✔
641
        progress.children.push_back(
2!
642
            build_task_progress_tree(child_id, processed));
4!
643
    }
644

645
    return progress;
48✔
UNCOV
646
}
×
647

648
// ============================================================================
649
// Phase 3: Coro-based task execution
650
// ============================================================================
651

652
coro::Coro Executor::run_task(std::shared_ptr<Task> task,
799!
653
                              std::shared_ptr<std::any> input) {
654
    // Get worker context from TLS (set by worker_thread at start).
655
    auto* context = static_cast<WorkerContext*>(get_current_worker_context());
656

657
    if (!context || !task) {
658
        co_return;
659
    }
660

661
    // Update worker context
662
    context->current_task_id = task->get_id();
663
    {
664
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
665
        context->current_task_name = task->get_name();
666
    }
667
    context->last_activity = std::chrono::steady_clock::now();
668

669
    // Mark task start
670
    mark_activity();
671
    ++tasks_started_;
672

673
    // Update task registry to RUNNING
674
    {
675
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
676
        auto it = task_registry_.find(task->get_id());
677
        if (it != task_registry_.end()) {
678
            it->second.state = TaskInfo::RUNNING;
679
            it->second.started_at = std::chrono::steady_clock::now();
680
            it->second.worker_id = context->worker_id;
681
            it->second.location = TaskInfo::EXECUTING;
682
        }
683
    }
684

685
    task->result().mark_running();
686

687
    {
688
        CoroScope scope(this);
689
        std::exception_ptr task_error;
690

691
        DFTRACER_UTILS_LOG_DEBUG("Worker %zu executing task ID %ld ('%s')",
692
                                 context->worker_id, task->get_id(),
693
                                 task->get_name());
694

695
        try {
696
            auto coro_task = task->execute(scope, *input);
697
            // Propagate executor to the CoroTask's PromiseBase so that
698
            // nested awaitables (when_any, channel, etc.) can schedule
699
            // resumptions.  run_task() is a Coro (CoroPromise, not
700
            // PromiseBase), so the normal PromiseBase propagation in
701
            // CoroTask::await_suspend doesn't fire.
702
            coro_task.handle().promise().set_executor(this);
703
            std::any result = co_await std::move(coro_task);
704

705
            // Set result via TaskResult
706
            task->set_result(std::move(result));
707
        } catch (...) {
708
            task_error = std::current_exception();
709
        }
710

711
        // Always join scope to wait for any sub-spawned coroutines.
712
        // Without this, the scope's JoinHandle would be destroyed
713
        // while FinalAwaiters still reference it (use-after-free).
714
        co_await scope.join();
715

716
        if (!task_error) {
717
            DFTRACER_UTILS_LOG_DEBUG(
718
                "Task ID %ld ('%s') completed successfully", task->get_id(),
719
                task->get_name());
720

721
            // Mark task completion
722
            mark_activity();
723
            ++tasks_completed_;
724
            context->tasks_executed++;
725

726
            // Update task registry to COMPLETED
727
            {
728
                std::unique_lock<std::shared_mutex> lock(registry_mutex_);
729
                auto it = task_registry_.find(task->get_id());
730
                if (it != task_registry_.end()) {
731
                    it->second.state = TaskInfo::COMPLETED;
732
                    it->second.completed_at = std::chrono::steady_clock::now();
733
                    it->second.location = TaskInfo::DONE;
734

735
                    // Update parent's completed children count
736
                    if (it->second.parent_task_id != -1) {
737
                        auto parent_it =
738
                            task_registry_.find(it->second.parent_task_id);
739
                        if (parent_it != task_registry_.end()) {
740
                            parent_it->second.completed_children++;
741
                        }
742
                    }
743
                }
744
            }
745

746
            // Notify scheduler
747
            notify_completion(task);
748

749
        } else {
750
            try {
751
                std::rethrow_exception(task_error);
752
            } catch (const std::exception& e) {
753
                DFTRACER_UTILS_LOG_ERROR("Task ID %ld ('%s') failed: %s",
754
                                         task->get_id(), task->get_name(),
755
                                         e.what());
756

757
                task->set_exception(task_error);
758

759
                mark_activity();
760
                ++tasks_completed_;
761
                context->tasks_executed++;
762

763
                {
764
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
765
                    auto it = task_registry_.find(task->get_id());
766
                    if (it != task_registry_.end()) {
767
                        it->second.state = TaskInfo::FAILED;
768
                        it->second.completed_at =
769
                            std::chrono::steady_clock::now();
770
                        it->second.error_message = e.what();
771
                        it->second.location = TaskInfo::DONE;
772
                    }
773
                }
774

775
                notify_completion(task);
776

777
            } catch (...) {
778
                DFTRACER_UTILS_LOG_ERROR(
779
                    "Task ID %ld ('%s') failed with unknown exception",
780
                    task->get_id(), task->get_name());
781

782
                task->set_exception(task_error);
783

784
                mark_activity();
785
                ++tasks_completed_;
786
                context->tasks_executed++;
787

788
                {
789
                    std::unique_lock<std::shared_mutex> lock(registry_mutex_);
790
                    auto it = task_registry_.find(task->get_id());
791
                    if (it != task_registry_.end()) {
792
                        it->second.state = TaskInfo::FAILED;
793
                        it->second.completed_at =
794
                            std::chrono::steady_clock::now();
795
                        it->second.error_message = "Unknown exception";
796
                        it->second.location = TaskInfo::DONE;
797
                    }
798
                }
799

800
                notify_completion(task);
801
            }
802
        }
803
    }
804

805
    // Clear current task info
806
    context->current_task_id = -1;
807
    {
808
        std::lock_guard<std::mutex> lock(context->task_name_mutex);
809
        context->current_task_name.clear();
810
    }
811

812
    co_return;
813
}
1,598!
814

815
void Executor::submit_task(std::shared_ptr<Task> task,
798✔
816
                           std::shared_ptr<std::any> input,
817
                           TaskIndex parent_task_id) {
818
    // Register in task registry
819
    {
820
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
798!
821

822
        auto [it, inserted] = task_registry_.emplace(
1,598!
823
            std::piecewise_construct, std::forward_as_tuple(task->get_id()),
799✔
824
            std::forward_as_tuple());
1,598✔
825

826
        if (inserted) {
799!
827
            it->second.task_id = task->get_id();
799✔
828
            it->second.parent_task_id = parent_task_id;
799✔
829
            it->second.name = task->get_name();
799!
830
            it->second.state = TaskInfo::QUEUED;
799✔
831
            it->second.queued_at = std::chrono::steady_clock::now();
799✔
832
            it->second.location = TaskInfo::SHARED_QUEUE;
799✔
833
            it->second.worker_id = static_cast<std::size_t>(-1);
799✔
834

835
            if (parent_task_id != -1) {
799✔
836
                auto parent_it = task_registry_.find(parent_task_id);
439!
837
                if (parent_it != task_registry_.end()) {
439✔
838
                    parent_it->second.child_task_ids.push_back(task->get_id());
435!
839
                }
840
            }
841
        }
842
    }
799✔
843

844
    ++total_tasks_submitted_;
799✔
845

846
    // Create Coro, set executor on promise, enqueue released handle
847
    auto coro = run_task(std::move(task), std::move(input));
1,598!
848
    coro.handle().promise().executor = this;
799✔
849
    enqueue(coro.release());
799!
850
}
799✔
851

852
TaskIndex Executor::enqueue_tracked(
572✔
853
    coro::Coro coro, std::string name,
854
    std::shared_ptr<std::atomic<TaskIndex>> tid_out) {
855
    TaskIndex id = next_coro_task_id_.fetch_sub(1, std::memory_order_relaxed);
572✔
856
    coro.handle().promise().task_id = id;
572✔
857
    coro.handle().promise().executor = this;
572✔
858

859
    {
860
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
572!
861
        auto [it, inserted] = task_registry_.emplace(std::piecewise_construct,
1,144!
862
                                                     std::forward_as_tuple(id),
572✔
863
                                                     std::forward_as_tuple());
1,144✔
864
        if (inserted) {
572!
865
            auto now = std::chrono::steady_clock::now();
572✔
866
            it->second.task_id = id;
572✔
867
            it->second.parent_task_id = -1;
572✔
868
            it->second.name = std::move(name);
572✔
869
            it->second.state = TaskInfo::QUEUED;
572✔
870
            it->second.queued_at = now;
572✔
871
            it->second.location = TaskInfo::SHARED_QUEUE;
572✔
872
            it->second.worker_id = static_cast<std::size_t>(-1);
572✔
873
        }
874
    }
572✔
875
    ++total_tasks_submitted_;
572✔
876

877
    if (tid_out) {
572!
878
        tid_out->store(id, std::memory_order_release);
572✔
879
    }
880

881
    auto handle = coro.release();
572!
882
    enqueue(handle, id);
572!
883
    return id;
572✔
884
}
885

886
void Executor::mark_coro_completed(TaskIndex id) {
1,144✔
887
    bool was_new = false;
1,144✔
888
    {
889
        std::unique_lock<std::shared_mutex> lock(registry_mutex_);
1,144!
890
        auto it = task_registry_.find(id);
1,144!
891
        if (it != task_registry_.end() &&
2,288!
892
            it->second.state != TaskInfo::COMPLETED) {
1,144✔
893
            auto now = std::chrono::steady_clock::now();
572✔
894
            if (it->second.started_at.time_since_epoch().count() == 0) {
572!
895
                it->second.started_at = now;
572✔
896
            }
897
            it->second.state = TaskInfo::COMPLETED;
572✔
898
            it->second.completed_at = now;
572✔
899
            it->second.location = TaskInfo::DONE;
572✔
900
            was_new = true;
572✔
901
        }
902
    }
1,144✔
903
    if (was_new) ++tasks_completed_;
1,144✔
904
}
1,144✔
905

906
void Executor::schedule_destroy(std::coroutine_handle<> handle) {
5,212✔
907
    if (handle) {
5,212!
908
        destroy_queue_.enqueue(handle);
5,191✔
909
    }
910
}
5,275✔
911

912
void Executor::drain_destroy_queue() {
49,344✔
913
    std::coroutine_handle<> to_destroy;
49,344✔
914
    while (destroy_queue_.try_dequeue(to_destroy)) {
54,684!
915
        if (to_destroy) {
5,300!
916
            to_destroy.destroy();
5,303!
917
        }
918
    }
919
}
49,271✔
920

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

© 2026 Coveralls, Inc