treadle 0.2.0

A persistent, resumable, human-in-the-loop workflow engine backed by a petgraph DAG
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
//! Pipeline status reporting and visualization.
//!
//! This module provides [`PipelineStatus`] for inspecting the current
//! state of a workflow for a work item.

use std::fmt;

use crate::{StageState, StageStatus, SubTask};
use chrono::{DateTime, Utc};

/// Status entry for a single stage within a pipeline.
#[derive(Debug, Clone)]
pub struct StageStatusEntry {
    /// The stage name.
    pub name: String,
    /// The current status of this stage.
    pub status: StageStatus,
    /// When this stage was first entered.
    pub started_at: Option<DateTime<Utc>>,
    /// When this stage completed.
    pub completed_at: Option<DateTime<Utc>>,
    /// Number of retry attempts for this stage.
    pub retry_count: u32,
    /// Error message if the stage failed.
    pub error: Option<String>,
    /// Subtasks for fan-out stages.
    pub subtasks: Vec<SubTask>,
}

impl StageStatusEntry {
    /// Creates a new pending status entry.
    pub fn pending(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: StageStatus::Pending,
            started_at: None,
            completed_at: None,
            retry_count: 0,
            error: None,
            subtasks: Vec::new(),
        }
    }

    /// Creates a status entry from a stored stage state.
    pub fn from_stage_state(name: impl Into<String>, state: &StageState) -> Self {
        Self {
            name: name.into(),
            status: state.status,
            started_at: state.started_at,
            completed_at: state.completed_at,
            retry_count: state.retry_count,
            error: state.error.clone(),
            subtasks: state.subtasks.clone(),
        }
    }

    /// Returns a status indicator character.
    pub fn status_char(&self) -> char {
        match self.status {
            StageStatus::Pending => '',     // Hourglass
            StageStatus::InProgress => '🔄', // Spinning arrows
            StageStatus::Complete => '',    // Green check
            StageStatus::Failed => '',      // Red X
            StageStatus::Paused => '👀',     // Eyes (awaiting review)
        }
    }

    /// Returns a status indicator for subtasks.
    pub fn subtask_status_char(status: &StageStatus) -> char {
        match status {
            StageStatus::Pending => '',
            StageStatus::InProgress => '🔄',
            StageStatus::Complete => '',
            StageStatus::Failed => '',
            StageStatus::Paused => '👀',
        }
    }
}

/// The complete status of a workflow pipeline for a work item.
///
/// This provides a snapshot of where a work item is in the workflow,
/// including the status of all stages and their subtasks.
#[derive(Debug, Clone)]
pub struct PipelineStatus {
    /// The work item's identifier.
    pub item_id: String,
    /// Status of each stage in topological order.
    pub stages: Vec<StageStatusEntry>,
}

impl PipelineStatus {
    /// Creates a new pipeline status.
    pub fn new(item_id: impl Into<String>, stages: Vec<StageStatusEntry>) -> Self {
        Self {
            item_id: item_id.into(),
            stages,
        }
    }

    /// Returns true if all stages are completed.
    pub fn is_complete(&self) -> bool {
        self.stages
            .iter()
            .all(|s| matches!(s.status, StageStatus::Complete))
    }

    /// Returns true if any stage has failed.
    pub fn has_failures(&self) -> bool {
        self.stages
            .iter()
            .any(|s| matches!(s.status, StageStatus::Failed))
    }

    /// Returns true if any stage is paused (awaiting review).
    pub fn has_pending_reviews(&self) -> bool {
        self.stages
            .iter()
            .any(|s| matches!(s.status, StageStatus::Paused))
    }

    /// Returns the names of stages that are currently running.
    pub fn running_stages(&self) -> Vec<&str> {
        self.stages
            .iter()
            .filter(|s| matches!(s.status, StageStatus::InProgress))
            .map(|s| s.name.as_str())
            .collect()
    }

    /// Returns the names of stages that have failed.
    pub fn failed_stages(&self) -> Vec<&str> {
        self.stages
            .iter()
            .filter(|s| matches!(s.status, StageStatus::Failed))
            .map(|s| s.name.as_str())
            .collect()
    }

    /// Returns the names of stages awaiting review.
    pub fn review_stages(&self) -> Vec<&str> {
        self.stages
            .iter()
            .filter(|s| matches!(s.status, StageStatus::Paused))
            .map(|s| s.name.as_str())
            .collect()
    }

    /// Returns the overall progress as a percentage.
    pub fn progress_percent(&self) -> f32 {
        if self.stages.is_empty() {
            return 100.0;
        }

        let completed = self
            .stages
            .iter()
            .filter(|s| matches!(s.status, StageStatus::Complete))
            .count();

        (completed as f32 / self.stages.len() as f32) * 100.0
    }
}

impl fmt::Display for PipelineStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Pipeline status for item \"{}\":", self.item_id)?;
        writeln!(f)?;

        for stage in &self.stages {
            // Main stage line
            let status_char = stage.status_char();
            let status_str = format!("{:?}", stage.status);
            let time_str = stage
                .completed_at
                .or(stage.started_at)
                .map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string())
                .unwrap_or_else(|| "-".to_string());

            write!(
                f,
                "  {} {:<15} {:<15} {}",
                status_char, stage.name, status_str, time_str
            )?;

            // Error message if present
            if let Some(ref error) = stage.error {
                write!(f, "  Error: {}", error)?;
            }

            // Retry count if > 0
            if stage.retry_count > 0 {
                write!(f, "  (retry {})", stage.retry_count)?;
            }

            writeln!(f)?;

            // Subtasks if present
            for subtask in &stage.subtasks {
                let sub_char = StageStatusEntry::subtask_status_char(&subtask.status);
                let sub_status = format!("{:?}", subtask.status);

                write!(
                    f,
                    "     └─ {} {:<12} {}",
                    sub_char, subtask.id, sub_status
                )?;

                if let Some(ref error) = subtask.error {
                    write!(f, "  Error: {}", error)?;
                }

                writeln!(f)?;
            }
        }

        // Summary line
        writeln!(f)?;
        writeln!(f, "Progress: {:.0}%", self.progress_percent())?;

        if self.is_complete() {
            writeln!(f, "Status: Complete")?;
        } else if self.has_failures() {
            writeln!(
                f,
                "Status: Failed ({} stage(s))",
                self.failed_stages().len()
            )?;
        } else if self.has_pending_reviews() {
            writeln!(
                f,
                "Status: Awaiting review ({} stage(s))",
                self.review_stages().len()
            )?;
        } else {
            writeln!(f, "Status: In progress")?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pipeline_status_empty() {
        let status = PipelineStatus::new("item-1", vec![]);
        assert!(status.is_complete());
        assert!(!status.has_failures());
        assert_eq!(status.progress_percent(), 100.0);
    }

    #[test]
    fn test_pipeline_status_all_pending() {
        let stages = vec![
            StageStatusEntry::pending("a"),
            StageStatusEntry::pending("b"),
            StageStatusEntry::pending("c"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        assert!(!status.is_complete());
        assert_eq!(status.progress_percent(), 0.0);
    }

    #[test]
    fn test_pipeline_status_partial_complete() {
        let mut state_a = StageState::new();
        state_a.mark_complete();

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::pending("b"),
            StageStatusEntry::pending("c"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        assert!(!status.is_complete());
        assert!((status.progress_percent() - 33.33).abs() < 1.0);
    }

    #[test]
    fn test_pipeline_status_complete() {
        let mut state_a = StageState::new();
        state_a.mark_complete();

        let mut state_b = StageState::new();
        state_b.mark_complete();

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::from_stage_state("b", &state_b),
        ];
        let status = PipelineStatus::new("item-1", stages);

        assert!(status.is_complete());
        assert_eq!(status.progress_percent(), 100.0);
    }

    #[test]
    fn test_pipeline_status_with_failure() {
        let mut state_a = StageState::new();
        state_a.mark_complete();

        let mut state_b = StageState::new();
        state_b.mark_failed("oops".to_string());

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::from_stage_state("b", &state_b),
            StageStatusEntry::pending("c"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        assert!(!status.is_complete());
        assert!(status.has_failures());
        assert_eq!(status.failed_stages(), vec!["b"]);
    }

    #[test]
    fn test_pipeline_status_with_review() {
        let mut state_a = StageState::new();
        state_a.mark_complete();

        let mut state_b = StageState::new();
        state_b.mark_paused();

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::from_stage_state("b", &state_b),
            StageStatusEntry::pending("c"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        assert!(status.has_pending_reviews());
        assert_eq!(status.review_stages(), vec!["b"]);
    }

    #[test]
    fn test_pipeline_status_display() {
        let mut state_scan = StageState::new();
        state_scan.mark_complete();

        let mut state_enrich = StageState::new();
        state_enrich.mark_in_progress();

        let stages = vec![
            StageStatusEntry::from_stage_state("scan", &state_scan),
            StageStatusEntry::from_stage_state("enrich", &state_enrich),
            StageStatusEntry::pending("review"),
        ];
        let status = PipelineStatus::new("doc-1", stages);

        let display = format!("{}", status);
        assert!(display.contains("doc-1"));
        assert!(display.contains("scan"));
        assert!(display.contains("enrich"));
        assert!(display.contains("review"));
        assert!(display.contains("In progress"));
    }

    #[test]
    fn test_stage_status_chars() {
        assert_eq!(StageStatusEntry::pending("a").status_char(), '');

        let mut completed = StageState::new();
        completed.mark_complete();
        let completed_entry = StageStatusEntry::from_stage_state("a", &completed);
        assert_eq!(completed_entry.status_char(), '');

        let mut failed = StageState::new();
        failed.mark_failed("err".to_string());
        let failed_entry = StageStatusEntry::from_stage_state("a", &failed);
        assert_eq!(failed_entry.status_char(), '');
    }

    #[test]
    fn test_progress_percent_calculation() {
        let mut state_a = StageState::new();
        state_a.mark_complete();

        let mut state_b = StageState::new();
        state_b.mark_complete();

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::from_stage_state("b", &state_b),
            StageStatusEntry::pending("c"),
            StageStatusEntry::pending("d"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        // 2 out of 4 = 50%
        assert_eq!(status.progress_percent(), 50.0);
    }

    #[test]
    fn test_running_stages() {
        let mut state_a = StageState::new();
        state_a.mark_in_progress();

        let mut state_b = StageState::new();
        state_b.mark_in_progress();

        let stages = vec![
            StageStatusEntry::from_stage_state("a", &state_a),
            StageStatusEntry::from_stage_state("b", &state_b),
            StageStatusEntry::pending("c"),
        ];
        let status = PipelineStatus::new("item-1", stages);

        let running = status.running_stages();
        assert_eq!(running.len(), 2);
        assert!(running.contains(&"a"));
        assert!(running.contains(&"b"));
    }
}