taskflowrs 0.1.1

A Rust implementation of TaskFlow — task-parallel programming with heterogeneous GPU support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# TaskFlow-RS

<p align="center">
  <b>A high-performance task graph runtime for Rust</b>
  <br>
  Build and execute dependency-based task graphs with parallel scheduling.
</p>

<p align="center">
  <a href="https://crates.io/crates/taskflowrs">
    <img src="https://img.shields.io/crates/v/taskflowrs.svg">
  </a>
  <a href="https://docs.rs/taskflowrs">
    <img src="https://docs.rs/taskflowrs/badge.svg">
  </a>
  <a href="https://github.com/ZigRazor/taskflow-rs/actions">
    <img src="https://github.com/ZigRazor/taskflow-rs/actions/workflows/ci.yml/badge.svg">
  </a>
  <a href="https://opensource.org/licenses/MIT">
    <img src="https://img.shields.io/badge/license-MIT-blue.svg">
  </a>
</p>

---

A Rust implementation of [TaskFlow](https://taskflow.github.io/) — a general-purpose
task-parallel programming library with heterogeneous CPU/GPU support.

## Features

- **Task Graph Construction** — DAGs with flexible dependency management
-**Lock-Free Work-Stealing Executor** — Per-worker queues, near-linear scalability
-**Subflows** — Nested task graphs for recursive parallelism
-**Condition Tasks** — Conditional branching and loop constructs
-**Cycle Detection** — Catches cycles at graph construction time
-**Parallel Algorithms**`for_each`, `reduce`, `transform`, `sort`, `scan`
-**Async Task Support** — Full `async`/`await` integration with Tokio
-**Pipeline Support** — Stream processing with parallel/serial stages and backpressure
-**Composition** — Reusable, parameterized task graph components
-**GPU Support** — CUDA, OpenCL, and ROCm/HIP with async transfers and multiple streams
-**Task Priorities** — Static `Low / Normal / High / Critical` priority levels
-**Preemptive Cancellation** — Watchdog timeouts, RAII deadline guards, signal preemption
-**Dynamic Priority Adjustment** — O(log n) live reprioritization of queued tasks
-**Hardware Topology Integration** — hwloc2 / sysfs cache hierarchy, NUMA binding, CPU affinity
-**Real-time Dashboard** — HTTP server with SSE; live throughput chart and worker utilisation bars
-**Flamegraph Generation** — Interactive SVG flamegraphs from profiles or folded stacks
-**Automated Regression Detection** — Statistical baseline comparison with JSON persistence
-**Tooling** — Profiler, DOT/SVG/HTML visualization, performance monitoring, debug logging

---

## Quick Start

```toml
[dependencies]
taskflowrs = "0.1.0"
```

### Basic task graph

```rust
use taskflowrs::{Executor, Taskflow};

fn main() {
    let mut executor = Executor::new(4);
    let mut taskflow = Taskflow::new();

    let a = taskflow.emplace(|| println!("A")).name("A");
    let b = taskflow.emplace(|| println!("B")).name("B");
    let c = taskflow.emplace(|| println!("C")).name("C");
    let d = taskflow.emplace(|| println!("D")).name("D");

    a.precede(&b);  // A → B
    a.precede(&c);  // A → C
    d.succeed(&b);  // B → D
    d.succeed(&c);  // C → D

    executor.run(&taskflow).wait();
    // Execution: A → {B, C} → D
}
```

---

## Preemptive Cancellation

TaskFlow-RS provides three escalating levels of cancellation, all sharing the same
`PreemptiveCancellationToken` type.

```rust
use taskflowrs::preemptive::PreemptiveCancellationToken;
use std::time::Duration;

let token = PreemptiveCancellationToken::new();

// Layer 1 — cooperative: task checks the flag manually
token.check()?;

// Layer 2 — watchdog: fires automatically after a deadline
token.cancel_after(Duration::from_millis(500));

// Layer 3 — RAII deadline guard (scope-bound)
let _guard = token.deadline_guard(Duration::from_secs(2));
```

---

## Real-time Dashboard

`DashboardServer` starts an HTTP server that streams live metrics to any browser via
Server-Sent Events. No external JavaScript libraries or CDN required — the page is
entirely self-contained.

```rust
use std::sync::Arc;
use taskflowrs::{
    monitoring::PerformanceMetrics,
    dashboard::{DashboardServer, DashboardConfig},
};

let metrics = Arc::new(PerformanceMetrics::new(4));
metrics.start();

let server = DashboardServer::new(
    Arc::clone(&metrics),
    4, // num_workers
    DashboardConfig { port: 9090, ..Default::default() },
);
let handle = server.start(); // non-blocking

println!("Dashboard → http://localhost:9090");

// … run your executor, record metrics …

handle.stop();
```

The dashboard provides:
- **Live throughput chart** (tasks/sec over a rolling 60 s window)
- **Worker utilisation bars** (colour-coded: green > 80%, yellow > 40%, red otherwise)
- **Stat cards** — tasks completed, throughput, avg task duration, steal rate
- **SSE history replay** — new clients immediately receive the full history buffer

---

## Flamegraph Generation

`FlamegraphGenerator` produces fully interactive SVG flamegraphs with zero external
dependencies. The output opens in any browser and supports click-to-zoom, search/highlight,
and hover tooltips.

### From an `ExecutionProfile`

```rust
use taskflowrs::flamegraph::{FlamegraphGenerator, FlamegraphConfig};

let gen = FlamegraphGenerator::new(FlamegraphConfig {
    title: "My Taskflow Run".to_string(),
    palette: "cool".to_string(), // "hot" | "cool" | "purple"
    ..Default::default()
});

gen.save_from_profile(&profile, "flamegraph.svg")?;
// open flamegraph.svg in any browser
```

### From folded stacks (perf / dtrace compatible)

```rust
// Standard "stack;frame N" format — compatible with perf-script | stackcollapse-perf
let folded = std::fs::read_to_string("perf.folded")?;
gen.save_from_folded(&folded, "flamegraph.svg")?;
```

SVG features:
- **Click** a frame to zoom into its subtree
- **Ctrl+click** (or press Reset) to restore the full view
- **Search box** dims non-matching frames in real time
- **Deterministic colours** — same frame name always gets the same colour

---

## Automated Regression Detection

`RegressionDetector` compares a finished `ExecutionProfile` against a stored `Baseline`
and produces a structured `RegressionReport` suitable for CI pipelines.

```rust
use taskflowrs::regression::{Baseline, RegressionDetector, RegressionThresholds};

// ── First run: record the baseline ──────────────────────────────────────────
let baseline = Baseline::from_profile(&profile, "v1.2.0");
baseline.save("perf_baseline.json")?;

// ── Subsequent runs: detect regressions ─────────────────────────────────────
let baseline = Baseline::load("perf_baseline.json")?;
let detector = RegressionDetector::new(baseline, RegressionThresholds::default());
let report   = detector.detect(&current_profile);

println!("{}", report.report());

// Fail CI on any regression
assert!(report.passed, "Performance regression detected!");

// Save JSON artefact for diff tracking
std::fs::write("regression_report.json", report.to_json())?;
```

### Threshold presets

| Preset | Total | Avg | P95 | P99 | Notes |
|---|---|---|---|---|---|
| `default()` | 10% | 10% | 15% | 20% | Balanced — recommended starting point |
| `strict()` | 5% | 5% | 8% | 10% | Critical paths; fail on small regressions |
| `lenient()` | 20% | 20% | 30% | 40% | Nightly builds; noise-tolerant |

Violations are classified as **WARNING** (> threshold) or **CRITICAL** (> 2× threshold).

---

## GPU Support

TaskFlow-RS provides a **backend-agnostic GPU API** supporting CUDA (NVIDIA), OpenCL
(NVIDIA/AMD/Intel), and ROCm/HIP (AMD).

### Building

```bash
# CUDA (NVIDIA) — default CUDA 12.0
cargo build --features gpu

# OpenCL (NVIDIA / AMD / Intel)
# Ubuntu: sudo apt install ocl-icd-opencl-dev
cargo build --features opencl

# ROCm / HIP (AMD) — requires ROCm ≥ 5.0
ROCM_PATH=/opt/rocm cargo build --features rocm

# All backends
cargo build --features all-gpu

# Stub backend (always available, no flags needed)
cargo build
```

### Usage

```rust
use taskflowrs::{GpuDevice, GpuBuffer, BackendKind};

// Auto-select: CUDA → ROCm → OpenCL → Stub
let device = GpuDevice::new(0)?;

// Allocate and transfer
let mut buf: GpuBuffer<f32> = GpuBuffer::allocate(&device, 1024)?;
buf.copy_from_host(&vec![1.0f32; 1024])?;

// Async transfer via stream
let stream = device.create_stream("compute")?;
unsafe { buf.copy_from_host_async(&src, &stream)?; }
stream.synchronize()?;
```

---

## Async Support

```toml
[dependencies]
taskflowrs = { version = "0.1", features = ["async"] }
tokio = { version = "1", features = ["full"] }
```

```rust
use taskflowrs::{AsyncExecutor, Taskflow};

#[tokio::main]
async fn main() {
    let executor = AsyncExecutor::new(4);
    let mut taskflow = Taskflow::new();

    taskflow.emplace_async(|| async {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        println!("async task done");
    });

    executor.run_async(&taskflow).await;
}
```

---

## Tooling

```rust
use taskflowrs::{Profiler, generate_dot_graph, PerformanceMetrics};

// Profiling
let profiler = Profiler::new(4);
profiler.enable();
executor.run(&taskflow).wait();
let profile = profiler.get_profile().unwrap();
println!("{}", profile.summary());

// DOT / SVG / HTML visualization
generate_dot_graph(&tasks, &deps, "taskflow.dot");
// dot -Tsvg taskflow.dot -o taskflow.svg

// Flamegraph (new)
use taskflowrs::flamegraph::{FlamegraphGenerator, FlamegraphConfig};
FlamegraphGenerator::new(FlamegraphConfig::default())
    .save_from_profile(&profile, "flamegraph.svg")?;

// Real-time dashboard (new)
use taskflowrs::dashboard::{DashboardServer, DashboardConfig};
let handle = DashboardServer::new(metrics, 4, DashboardConfig::default()).start();
// → http://localhost:9090

// Regression detection (new)
use taskflowrs::regression::{Baseline, RegressionDetector, RegressionThresholds};
let baseline = Baseline::from_profile(&profile, "v1.0");
baseline.save("baseline.json")?;
let report = RegressionDetector::new(
    Baseline::load("baseline.json")?,
    RegressionThresholds::default(),
).detect(&new_profile);
assert!(report.passed);
```

---

## Building

```bash
# Core (no GPU, no hwloc)
cargo build

# With hwloc topology
cargo build --features hwloc

# With CUDA GPU
cargo build --features gpu

# Everything
cargo build --features hwloc,all-gpu,async

# Release
cargo build --release

# Tests
cargo test
cargo test --features hwloc
```

## Examples

```bash
# New tooling features
cargo run --example advanced_tooling_demo    # dashboard + flamegraph + regression

# Advanced scheduling
cargo run --example preemptive_cancellation
cargo run --example dynamic_priority
cargo run --example hardware_topology
cargo run --features hwloc --example hardware_topology

# Advanced features (priorities, cooperative cancellation, NUMA)
cargo run --example advanced_features

# Async
cargo run --features async --example async_tasks
cargo run --features async --example async_parallel

# GPU (stub — no hardware required)
cargo run --example gpu_tasks
cargo run --example gpu_async_streams

# GPU with hardware
cargo run --features gpu --example gpu_tasks
cargo run --features gpu --example gpu_pipeline
```

---

## Architecture

### Work-stealing executor

```
Worker 0: [Task] [Task] [Task]  ← push/pop own queue (LIFO, cache-warm)
                ↓ steal (FIFO)
Worker 1: [Task] [Task]         ← idle workers steal from busy ones
```

### Scheduling layer

```
SharedDynamicScheduler
  ├── index:   BTreeMap<(RevPriority, SeqNum), TaskId>   O(log n) pop
  └── reverse: HashMap<TaskId, (RevPriority, SeqNum)>    O(1) lookup

PriorityHandle ──weak──► SharedDynamicScheduler
                          reprioritize() / cancel() without owning the queue

EscalationPolicy ──tick──► sched.reprioritize(id, bumped_priority)
                            anti-starvation for Low / Normal tasks
```

### Tooling layer

```
DashboardServer ──SSE──► browser (live charts, no CDN)
  └── DashboardConfig { port, push_interval_ms, history_len, title }

FlamegraphGenerator
  ├── from_profile(ExecutionProfile) → interactive SVG
  └── from_folded("a;b;c N")        → compatible with perf / dtrace

RegressionDetector
  ├── Baseline { total_us, avg_us, P50/P95/P99, efficiency } ← JSON file
  └── detect(profile) → RegressionReport { violations, summary, to_json }
```

---

## Documentation

| Document | Contents |
|---|---|
| [DESIGN.md]DESIGN.md | Architecture, implementation status, design decisions |
| [ADVANCED_FEATURES.md]ADVANCED_FEATURES.md | Priorities, cancellation, schedulers, NUMA |
| [GPU.md]GPU.md | Full GPU API: backends, streams, async transfers |
| [GPU_SETUP.md]GPU_SETUP.md | CUDA version config, ROCm install, troubleshooting |
| [ASYNC_TASKS.md]ASYNC_TASKS.md | Async executor and task documentation |
| [PIPELINE.md]PIPELINE.md | Concurrent pipeline documentation |
| [TOOLING.md]TOOLING.md | Profiler, visualization, monitoring, dashboard, flamegraphs, regression |

## License

MIT