wrkflw-matrix 0.8.0

Matrix job parallelization for wrkflw workflow execution engine
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
// matrix crate

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use std::collections::HashMap;
use thiserror::Error;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MatrixConfig {
    #[serde(flatten)]
    pub parameters: IndexMap<String, Value>,
    #[serde(default)]
    pub include: Vec<HashMap<String, Value>>,
    #[serde(default)]
    pub exclude: Vec<HashMap<String, Value>>,
    #[serde(default, rename = "max-parallel")]
    pub max_parallel: Option<usize>,
    #[serde(default, rename = "fail-fast")]
    pub fail_fast: Option<bool>,
}

impl Default for MatrixConfig {
    fn default() -> Self {
        Self {
            parameters: IndexMap::new(),
            include: Vec::new(),
            exclude: Vec::new(),
            max_parallel: None,
            fail_fast: Some(true),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct MatrixCombination {
    pub values: HashMap<String, Value>,
    pub is_included: bool, // Whether this was added via the include section
}

impl MatrixCombination {
    pub fn new(values: HashMap<String, Value>) -> Self {
        Self {
            values,
            is_included: false,
        }
    }

    pub fn from_include(values: HashMap<String, Value>) -> Self {
        Self {
            values,
            is_included: true,
        }
    }
}

#[derive(Error, Debug)]
pub enum MatrixError {
    #[error("Invalid matrix parameter format: {0}")]
    InvalidParameterFormat(String),

    #[error("Failed to expand matrix: {0}")]
    ExpansionError(String),
}

/// Expands a matrix configuration into a list of all valid combinations
pub fn expand_matrix(matrix: &MatrixConfig) -> Result<Vec<MatrixCombination>, MatrixError> {
    let mut combinations = Vec::new();

    // Step 1: Generate base combinations from parameter arrays
    let param_combinations = generate_base_combinations(matrix)?;

    // Step 2: Filter out any combinations that match the exclude patterns
    let filtered_combinations = apply_exclude_filters(param_combinations, &matrix.exclude);
    combinations.extend(filtered_combinations);

    // Step 3: Process include entries per GitHub Actions semantics:
    // If an include entry matches all shared keys of an existing combination,
    // merge extra keys into it. Otherwise, add as a new standalone combination.
    for include_item in &matrix.include {
        let mut merged = false;
        for combo in &mut combinations {
            let all_shared_keys_match = include_item.iter().all(|(key, value)| {
                match combo.values.get(key) {
                    Some(existing_value) => existing_value == value,
                    None => true, // Key not in base combo = no conflict, it's a new key to add
                }
            });
            // Only merge if there's at least one matching key (not purely new keys)
            let has_matching_key = include_item
                .keys()
                .any(|key| combo.values.contains_key(key));
            if all_shared_keys_match && has_matching_key {
                // Merge extra keys into the existing combination.
                // or_insert_with is intentional: per GitHub Actions semantics, include
                // entries add new keys but do NOT override existing matrix values.
                for (key, value) in include_item {
                    combo
                        .values
                        .entry(key.clone())
                        .or_insert_with(|| value.clone());
                }
                merged = true;
                // Don't break — merge into ALL matching combinations per GitHub Actions semantics
            }
        }
        if !merged {
            combinations.push(MatrixCombination::from_include(include_item.clone()));
        }
    }

    if combinations.is_empty() {
        return Err(MatrixError::ExpansionError(
            "No valid combinations found after applying filters".to_string(),
        ));
    }

    Ok(combinations)
}

/// Generates all possible combinations of the base matrix parameters
fn generate_base_combinations(
    matrix: &MatrixConfig,
) -> Result<Vec<MatrixCombination>, MatrixError> {
    // Extract parameter arrays and prepare for combination generation
    let mut param_arrays: IndexMap<String, Vec<Value>> = IndexMap::new();

    for (param_name, param_value) in &matrix.parameters {
        match param_value {
            Value::Sequence(array) => {
                param_arrays.insert(param_name.clone(), array.clone());
            }
            _ => {
                // Handle non-array parameters
                let single_value = vec![param_value.clone()];
                param_arrays.insert(param_name.clone(), single_value);
            }
        }
    }

    if param_arrays.is_empty() {
        return Err(MatrixError::InvalidParameterFormat(
            "Matrix has no valid parameters".to_string(),
        ));
    }

    // Generate the Cartesian product of all parameter arrays
    let param_names: Vec<String> = param_arrays.keys().cloned().collect();
    let param_values: Vec<Vec<Value>> = param_arrays.values().cloned().collect();

    // Generate all combinations using itertools
    let combinations = if !param_values.is_empty() {
        generate_combinations(&param_names, &param_values, 0, &mut HashMap::new())?
    } else {
        vec![]
    };

    Ok(combinations)
}

/// Recursive function to generate combinations using depth-first approach
fn generate_combinations(
    param_names: &[String],
    param_values: &[Vec<Value>],
    current_depth: usize,
    current_combination: &mut HashMap<String, Value>,
) -> Result<Vec<MatrixCombination>, MatrixError> {
    if current_depth == param_names.len() {
        // We've reached a complete combination
        return Ok(vec![MatrixCombination::new(current_combination.clone())]);
    }

    let mut result = Vec::new();
    let param_name = &param_names[current_depth];
    let values = &param_values[current_depth];

    for value in values {
        current_combination.insert(param_name.clone(), value.clone());

        let mut new_combinations = generate_combinations(
            param_names,
            param_values,
            current_depth + 1,
            current_combination,
        )?;

        result.append(&mut new_combinations);
    }

    // Remove this level's parameter to backtrack
    current_combination.remove(param_name);

    Ok(result)
}

/// Filters out combinations that match any of the exclude patterns
fn apply_exclude_filters(
    combinations: Vec<MatrixCombination>,
    exclude_patterns: &[HashMap<String, Value>],
) -> Vec<MatrixCombination> {
    if exclude_patterns.is_empty() {
        return combinations;
    }

    combinations
        .into_iter()
        .filter(|combination| !is_excluded(combination, exclude_patterns))
        .collect()
}

/// Checks if a combination matches any exclude pattern
fn is_excluded(
    combination: &MatrixCombination,
    exclude_patterns: &[HashMap<String, Value>],
) -> bool {
    for exclude in exclude_patterns {
        let mut excluded = true;

        for (key, value) in exclude {
            match combination.values.get(key) {
                Some(combo_value) if combo_value == value => {
                    // This exclude condition matches
                    continue;
                }
                _ => {
                    // This exclude condition doesn't match
                    excluded = false;
                    break;
                }
            }
        }

        if excluded {
            return true;
        }
    }

    false
}

/// Formats a combination name for display, e.g. "test (ubuntu, node 14)"
pub fn format_combination_name(job_name: &str, combination: &MatrixCombination) -> String {
    let params = combination
        .values
        .iter()
        .map(|(k, v)| format!("{}: {}", k, value_to_string(v)))
        .collect::<Vec<_>>()
        .join(", ");

    format!("{} ({})", job_name, params)
}

/// Converts a serde_yaml::Value to a string for display
fn value_to_string(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Sequence(seq) => {
            let items = seq
                .iter()
                .map(value_to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{}]", items)
        }
        Value::Mapping(map) => {
            let items = map
                .iter()
                .map(|(k, v)| format!("{}: {}", value_to_string(k), value_to_string(v)))
                .collect::<Vec<_>>()
                .join(", ");
            format!("{{{}}}", items)
        }
        Value::Null => "null".to_string(),
        _ => "unknown".to_string(),
    }
}

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

    fn val(s: &str) -> Value {
        Value::String(s.to_string())
    }

    fn make_matrix(params: Vec<(&str, Vec<&str>)>) -> MatrixConfig {
        let mut parameters = IndexMap::new();
        for (name, values) in params {
            parameters.insert(
                name.to_string(),
                Value::Sequence(values.into_iter().map(val).collect()),
            );
        }
        MatrixConfig {
            parameters,
            include: Vec::new(),
            exclude: Vec::new(),
            max_parallel: None,
            fail_fast: Some(true),
        }
    }

    #[test]
    fn include_merges_into_matching_combination() {
        let mut matrix = make_matrix(vec![("os", vec!["ubuntu", "windows"])]);
        // Include entry that matches os=ubuntu and adds a new key
        let mut include_entry = HashMap::new();
        include_entry.insert("os".to_string(), val("ubuntu"));
        include_entry.insert("compiler".to_string(), val("gcc"));
        matrix.include.push(include_entry);

        let combos = expand_matrix(&matrix).unwrap();

        // Should have 2 combos: ubuntu (with compiler=gcc merged) and windows
        assert_eq!(combos.len(), 2);

        let ubuntu = combos
            .iter()
            .find(|c| c.values.get("os") == Some(&val("ubuntu")))
            .unwrap();
        assert_eq!(ubuntu.values.get("compiler"), Some(&val("gcc")));

        let windows = combos
            .iter()
            .find(|c| c.values.get("os") == Some(&val("windows")))
            .unwrap();
        assert_eq!(windows.values.get("compiler"), None);
    }

    #[test]
    fn include_adds_standalone_when_no_match() {
        let mut matrix = make_matrix(vec![("os", vec!["ubuntu", "windows"])]);
        // Include entry with a value that doesn't match any existing combo
        let mut include_entry = HashMap::new();
        include_entry.insert("os".to_string(), val("macos"));
        include_entry.insert("special".to_string(), val("true"));
        matrix.include.push(include_entry);

        let combos = expand_matrix(&matrix).unwrap();

        // Should have 3 combos: ubuntu, windows, macos (standalone)
        assert_eq!(combos.len(), 3);

        let macos = combos
            .iter()
            .find(|c| c.values.get("os") == Some(&val("macos")))
            .unwrap();
        assert_eq!(macos.values.get("special"), Some(&val("true")));
        assert!(macos.is_included);
    }

    #[test]
    fn include_merges_into_all_matching_combinations() {
        let mut matrix = make_matrix(vec![
            ("os", vec!["ubuntu", "windows"]),
            ("node", vec!["16", "18"]),
        ]);
        // Include entry matching os=ubuntu — should merge into both (ubuntu, 16) and (ubuntu, 18)
        let mut include_entry = HashMap::new();
        include_entry.insert("os".to_string(), val("ubuntu"));
        include_entry.insert("extra".to_string(), val("yes"));
        matrix.include.push(include_entry);

        let combos = expand_matrix(&matrix).unwrap();

        // 4 base combos, no new standalone (merged into 2 existing)
        assert_eq!(combos.len(), 4);

        let ubuntu_combos: Vec<_> = combos
            .iter()
            .filter(|c| c.values.get("os") == Some(&val("ubuntu")))
            .collect();
        assert_eq!(ubuntu_combos.len(), 2);
        for combo in &ubuntu_combos {
            assert_eq!(combo.values.get("extra"), Some(&val("yes")));
        }

        let windows_combos: Vec<_> = combos
            .iter()
            .filter(|c| c.values.get("os") == Some(&val("windows")))
            .collect();
        for combo in &windows_combos {
            assert_eq!(combo.values.get("extra"), None);
        }
    }

    #[test]
    fn include_with_only_new_keys_adds_standalone() {
        let mut matrix = make_matrix(vec![("os", vec!["ubuntu"])]);
        // Include entry with only keys that don't exist in base combos
        let mut include_entry = HashMap::new();
        include_entry.insert("arch".to_string(), val("arm64"));
        matrix.include.push(include_entry);

        let combos = expand_matrix(&matrix).unwrap();

        // Should have 2: the base ubuntu + standalone arm64
        assert_eq!(combos.len(), 2);
    }

    #[test]
    fn exclude_removes_matching_combinations() {
        let mut matrix = make_matrix(vec![
            ("os", vec!["ubuntu", "windows"]),
            ("node", vec!["16", "18"]),
        ]);
        let mut exclude_entry = HashMap::new();
        exclude_entry.insert("os".to_string(), val("windows"));
        exclude_entry.insert("node".to_string(), val("16"));
        matrix.exclude.push(exclude_entry);

        let combos = expand_matrix(&matrix).unwrap();

        // 4 - 1 excluded = 3
        assert_eq!(combos.len(), 3);
        assert!(!combos.iter().any(|c| {
            c.values.get("os") == Some(&val("windows")) && c.values.get("node") == Some(&val("16"))
        }));
    }
}