wrkflw-executor 0.8.0

Workflow execution engine for wrkflw
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use std::collections::{HashMap, HashSet, VecDeque};
use wrkflw_parser::workflow::{Job, WorkflowDefinition};

pub fn resolve_dependencies(workflow: &WorkflowDefinition) -> Result<Vec<Vec<String>>, String> {
    let jobs = &workflow.jobs;

    // Build adjacency list with String keys
    let mut dependencies: HashMap<String, HashSet<String>> = HashMap::new();
    let mut dependents: HashMap<String, HashSet<String>> = HashMap::new();

    // Initialize with empty dependencies
    for job_name in jobs.keys() {
        dependencies.insert(job_name.clone(), HashSet::new());
        dependents.insert(job_name.clone(), HashSet::new());
    }

    // Populate dependencies
    for (job_name, job) in jobs {
        if let Some(needs) = &job.needs {
            for needed_job in needs {
                if !jobs.contains_key(needed_job) {
                    return Err(format!(
                        "Job '{}' depends on non-existent job '{}'",
                        job_name, needed_job
                    ));
                }
                // Get mutable reference to the dependency set for this job, with error handling
                if let Some(deps) = dependencies.get_mut(job_name) {
                    deps.insert(needed_job.clone());
                } else {
                    return Err(format!(
                        "Internal error: Failed to update dependencies for job '{}'",
                        job_name
                    ));
                }

                // Get mutable reference to the dependents set for the needed job, with error handling
                if let Some(deps) = dependents.get_mut(needed_job) {
                    deps.insert(job_name.clone());
                } else {
                    return Err(format!(
                        "Internal error: Failed to update dependents for job '{}'",
                        needed_job
                    ));
                }
            }
        }
    }

    // Implement topological sort for execution ordering
    let mut result = Vec::new();
    let mut no_dependencies: HashSet<String> = dependencies
        .iter()
        .filter(|(_, deps)| deps.is_empty())
        .map(|(job, _)| job.clone())
        .collect();

    // Process levels of the dependency graph
    while !no_dependencies.is_empty() {
        // Current level becomes a batch of jobs that can run in parallel
        let current_level: Vec<String> = no_dependencies.iter().cloned().collect();
        result.push(current_level);

        // For the next level
        let mut next_no_dependencies = HashSet::new();

        for job in &no_dependencies {
            // For each dependent job of the current job
            // Get the set of dependents with error handling
            let dependent_jobs = match dependents.get(job) {
                Some(deps) => deps.clone(),
                None => {
                    return Err(format!(
                        "Internal error: Failed to find dependents for job '{}'",
                        job
                    ));
                }
            };

            for dependent in dependent_jobs {
                // Remove the current job from its dependencies
                if let Some(deps) = dependencies.get_mut(&dependent) {
                    deps.remove(job);

                    // Check if it's empty now to determine if it should be in the next level
                    if deps.is_empty() {
                        next_no_dependencies.insert(dependent);
                    }
                } else {
                    return Err(format!(
                        "Internal error: Failed to find dependencies for job '{}'",
                        dependent
                    ));
                }
            }
        }

        no_dependencies = next_no_dependencies;
    }

    // Check for circular dependencies
    let processed_jobs: HashSet<String> = result
        .iter()
        .flat_map(|level| level.iter().cloned())
        .collect();

    if processed_jobs.len() < jobs.len() {
        let unprocessed: Vec<&String> = jobs
            .keys()
            .filter(|j| !processed_jobs.contains(*j))
            .collect();
        return Err(format!(
            "Circular dependency detected in workflow jobs: {}",
            unprocessed
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    Ok(result)
}

/// Collect a job and all its transitive dependencies via `needs` edges.
pub fn collect_transitive_deps(target_job: &str, jobs: &HashMap<String, Job>) -> HashSet<String> {
    let mut deps = HashSet::new();
    let mut queue = VecDeque::new();

    deps.insert(target_job.to_string());
    queue.push_back(target_job.to_string());

    while let Some(job_name) = queue.pop_front() {
        if let Some(job) = jobs.get(&job_name) {
            if let Some(needs) = &job.needs {
                for needed in needs {
                    if deps.insert(needed.clone()) {
                        queue.push_back(needed.clone());
                    }
                }
            }
        }
    }

    deps
}

/// Filter an execution plan to only include a target job and its transitive
/// dependencies. Returns an error if the target job doesn't exist.
pub fn filter_plan_to_job(
    plan: Vec<Vec<String>>,
    target_job: &str,
    jobs: &HashMap<String, Job>,
    kind: &str,
) -> Result<Vec<Vec<String>>, String> {
    if !jobs.contains_key(target_job) {
        return Err(job_not_found_error(target_job, jobs, kind));
    }

    let needed = collect_transitive_deps(target_job, jobs);

    Ok(plan
        .into_iter()
        .map(|batch| {
            batch
                .into_iter()
                .filter(|j| needed.contains(j))
                .collect::<Vec<_>>()
        })
        .filter(|batch| !batch.is_empty())
        .collect())
}

/// Filter a stage-ordered execution plan to only include the target job and all
/// jobs in preceding stages (implicit dependencies). This is appropriate for
/// GitLab CI/CD where stage ordering defines implicit dependencies — all jobs in
/// earlier stages must complete before later stages run.
///
/// In the target job's own stage batch, only the target job is kept; all earlier
/// stage batches are preserved in full.
pub fn filter_plan_to_job_by_stage(
    plan: Vec<Vec<String>>,
    target_job: &str,
    jobs: &HashMap<String, Job>,
    kind: &str,
) -> Result<Vec<Vec<String>>, String> {
    if !jobs.contains_key(target_job) {
        return Err(job_not_found_error(target_job, jobs, kind));
    }

    let mut result = Vec::new();
    for batch in plan {
        if batch.contains(&target_job.to_string()) {
            // Target's stage: only keep the target job itself
            result.push(vec![target_job.to_string()]);
            break;
        }
        // Earlier stage: keep all jobs (implicit dependencies)
        result.push(batch);
    }

    Ok(result)
}

fn job_not_found_error(target_job: &str, jobs: &HashMap<String, Job>, kind: &str) -> String {
    let mut available: Vec<&String> = jobs.keys().collect();
    available.sort();
    format!(
        "Job '{}' not found in {}. Available jobs: {}",
        target_job,
        kind,
        available
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

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

    fn job_with_needs(needs: Option<Vec<&str>>) -> Job {
        Job {
            runs_on: None,
            needs: needs.map(|v| v.into_iter().map(String::from).collect()),
            container: None,
            steps: vec![],
            env: HashMap::new(),
            strategy: None,
            services: HashMap::new(),
            if_condition: None,
            outputs: None,
            permissions: None,
            uses: None,
            with: None,
            secrets: None,
            timeout_minutes: None,
            defaults: None,
        }
    }

    #[test]
    fn test_collect_transitive_deps_no_deps() {
        let mut jobs = HashMap::new();
        jobs.insert("build".to_string(), job_with_needs(None));
        jobs.insert("test".to_string(), job_with_needs(None));

        let deps = collect_transitive_deps("build", &jobs);
        assert_eq!(deps, HashSet::from(["build".to_string()]));
    }

    #[test]
    fn test_collect_transitive_deps_linear_chain() {
        let mut jobs = HashMap::new();
        jobs.insert("setup".to_string(), job_with_needs(None));
        jobs.insert("build".to_string(), job_with_needs(Some(vec!["setup"])));
        jobs.insert("deploy".to_string(), job_with_needs(Some(vec!["build"])));

        let deps = collect_transitive_deps("deploy", &jobs);
        assert_eq!(
            deps,
            HashSet::from([
                "setup".to_string(),
                "build".to_string(),
                "deploy".to_string(),
            ])
        );
    }

    #[test]
    fn test_collect_transitive_deps_diamond() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("b".to_string(), job_with_needs(Some(vec!["a"])));
        jobs.insert("c".to_string(), job_with_needs(Some(vec!["a"])));
        jobs.insert("d".to_string(), job_with_needs(Some(vec!["b", "c"])));

        let deps = collect_transitive_deps("d", &jobs);
        assert_eq!(
            deps,
            HashSet::from([
                "a".to_string(),
                "b".to_string(),
                "c".to_string(),
                "d".to_string(),
            ])
        );
    }

    #[test]
    fn test_collect_transitive_deps_partial_graph() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("b".to_string(), job_with_needs(Some(vec!["a"])));
        jobs.insert("unrelated".to_string(), job_with_needs(None));

        let deps = collect_transitive_deps("b", &jobs);
        assert_eq!(deps, HashSet::from(["a".to_string(), "b".to_string()]));
        assert!(!deps.contains("unrelated"));
    }

    #[test]
    fn test_filter_plan_to_job_not_found() {
        let jobs = HashMap::new();
        let plan = vec![vec!["a".to_string()]];

        let result = filter_plan_to_job(plan, "missing", &jobs, "workflow");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("missing"));
        assert!(err.contains("workflow"));
    }

    #[test]
    fn test_filter_plan_to_job_not_found_lists_available() {
        let mut jobs = HashMap::new();
        jobs.insert("build".to_string(), job_with_needs(None));
        jobs.insert("test".to_string(), job_with_needs(None));
        let plan = vec![vec!["build".to_string(), "test".to_string()]];

        let err = filter_plan_to_job(plan, "deploy", &jobs, "pipeline").unwrap_err();
        assert!(err.contains("build"));
        assert!(err.contains("test"));
        assert!(err.contains("pipeline"));
    }

    #[test]
    fn test_filter_plan_to_job_with_deps() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("x".to_string(), job_with_needs(None));
        jobs.insert("b".to_string(), job_with_needs(Some(vec!["a"])));
        jobs.insert("y".to_string(), job_with_needs(Some(vec!["x"])));
        jobs.insert("c".to_string(), job_with_needs(Some(vec!["b"])));

        // Plan: [a, x] -> [b, y] -> [c]
        let plan = vec![
            vec!["a".to_string(), "x".to_string()],
            vec!["b".to_string(), "y".to_string()],
            vec!["c".to_string()],
        ];

        let filtered = filter_plan_to_job(plan, "c", &jobs, "workflow").unwrap();
        // Should keep a, b, c but drop x and y
        assert_eq!(
            filtered,
            vec![
                vec!["a".to_string()],
                vec!["b".to_string()],
                vec!["c".to_string()],
            ]
        );
    }

    #[test]
    fn test_filter_plan_to_job_no_deps() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("b".to_string(), job_with_needs(None));

        let plan = vec![vec!["a".to_string(), "b".to_string()]];

        let filtered = filter_plan_to_job(plan, "a", &jobs, "workflow").unwrap();
        assert_eq!(filtered, vec![vec!["a".to_string()]]);
    }

    #[test]
    fn test_filter_plan_to_job_removes_empty_batches() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("x".to_string(), job_with_needs(None));
        jobs.insert("y".to_string(), job_with_needs(Some(vec!["x"])));

        // Plan: [a, x] -> [y]
        // Targeting "a" should produce [[a]] — batch [y] is entirely removed
        let plan = vec![
            vec!["a".to_string(), "x".to_string()],
            vec!["y".to_string()],
        ];

        let filtered = filter_plan_to_job(plan, "a", &jobs, "workflow").unwrap();
        assert_eq!(filtered, vec![vec!["a".to_string()]]);
    }

    // --- filter_plan_to_job_by_stage tests (GitLab stage-based filtering) ---

    #[test]
    fn test_filter_by_stage_not_found() {
        let jobs = HashMap::new();
        let plan = vec![vec!["a".to_string()]];

        let result = filter_plan_to_job_by_stage(plan, "missing", &jobs, "pipeline");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("missing"));
        assert!(err.contains("pipeline"));
    }

    #[test]
    fn test_filter_by_stage_target_in_first_stage() {
        let mut jobs = HashMap::new();
        jobs.insert("build".to_string(), job_with_needs(None));
        jobs.insert("lint".to_string(), job_with_needs(None));
        jobs.insert("test".to_string(), job_with_needs(None));
        jobs.insert("deploy".to_string(), job_with_needs(None));

        // Stages: [build, lint] -> [test] -> [deploy]
        let plan = vec![
            vec!["build".to_string(), "lint".to_string()],
            vec!["test".to_string()],
            vec!["deploy".to_string()],
        ];

        let filtered = filter_plan_to_job_by_stage(plan, "build", &jobs, "pipeline").unwrap();
        // Only the first stage, filtered to just "build"
        assert_eq!(filtered, vec![vec!["build".to_string()]]);
    }

    #[test]
    fn test_filter_by_stage_target_in_middle_stage() {
        let mut jobs = HashMap::new();
        jobs.insert("build".to_string(), job_with_needs(None));
        jobs.insert("lint".to_string(), job_with_needs(None));
        jobs.insert("test".to_string(), job_with_needs(None));
        jobs.insert("deploy".to_string(), job_with_needs(None));

        // Stages: [build, lint] -> [test] -> [deploy]
        let plan = vec![
            vec!["build".to_string(), "lint".to_string()],
            vec!["test".to_string()],
            vec!["deploy".to_string()],
        ];

        let filtered = filter_plan_to_job_by_stage(plan, "test", &jobs, "pipeline").unwrap();
        // Keep all of stage 1, then just "test" from stage 2, drop stage 3
        assert_eq!(
            filtered,
            vec![
                vec!["build".to_string(), "lint".to_string()],
                vec!["test".to_string()],
            ]
        );
    }

    #[test]
    fn test_filter_by_stage_target_in_last_stage() {
        let mut jobs = HashMap::new();
        jobs.insert("build".to_string(), job_with_needs(None));
        jobs.insert("test".to_string(), job_with_needs(None));
        jobs.insert("deploy".to_string(), job_with_needs(None));

        // Stages: [build] -> [test] -> [deploy]
        let plan = vec![
            vec!["build".to_string()],
            vec!["test".to_string()],
            vec!["deploy".to_string()],
        ];

        let filtered = filter_plan_to_job_by_stage(plan, "deploy", &jobs, "pipeline").unwrap();
        assert_eq!(
            filtered,
            vec![
                vec!["build".to_string()],
                vec!["test".to_string()],
                vec!["deploy".to_string()],
            ]
        );
    }

    #[test]
    fn test_filter_by_stage_filters_peers_in_target_stage() {
        let mut jobs = HashMap::new();
        jobs.insert("a".to_string(), job_with_needs(None));
        jobs.insert("b".to_string(), job_with_needs(None));
        jobs.insert("c".to_string(), job_with_needs(None));

        // All in same stage: [a, b, c]
        let plan = vec![vec!["a".to_string(), "b".to_string(), "c".to_string()]];

        let filtered = filter_plan_to_job_by_stage(plan, "b", &jobs, "pipeline").unwrap();
        // Only the target job from its stage
        assert_eq!(filtered, vec![vec!["b".to_string()]]);
    }

    #[test]
    fn test_filter_by_stage_drops_later_stages() {
        let mut jobs = HashMap::new();
        jobs.insert("compile".to_string(), job_with_needs(None));
        jobs.insert("unit_test".to_string(), job_with_needs(None));
        jobs.insert("integration_test".to_string(), job_with_needs(None));
        jobs.insert("deploy_staging".to_string(), job_with_needs(None));
        jobs.insert("deploy_prod".to_string(), job_with_needs(None));

        // Stages: [compile] -> [unit_test, integration_test] -> [deploy_staging, deploy_prod]
        let plan = vec![
            vec!["compile".to_string()],
            vec!["unit_test".to_string(), "integration_test".to_string()],
            vec!["deploy_staging".to_string(), "deploy_prod".to_string()],
        ];

        let filtered = filter_plan_to_job_by_stage(plan, "unit_test", &jobs, "pipeline").unwrap();
        assert_eq!(
            filtered,
            vec![vec!["compile".to_string()], vec!["unit_test".to_string()],]
        );
    }
}