haz-dag 0.1.0

DAG construction and traversal for haz tasks.
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
//! Hard-edge graph traversal helpers for relational queries.
//!
//! Per `QRY-004`, the relational filters (`--child-of`,
//! `--parent-of`, `--depends-on`, `--ancestor-of`) operate on the
//! hard-edge graph of `DAG-008` only. Weak edges (`DAG-009`) and
//! producer-matching edges (`DAG-013`) MUST NOT contribute to any
//! relational filter.
//!
//! These helpers expose that hard-edge view as four primitives:
//! direct and transitive predecessor / successor sets. They operate
//! against a [`crate::graph::TaskGraph`] post-construction, so they
//! rely on `DAG-012` (no hard / soft self-loops) and `DAG-014` (no
//! cycles in the hard-edge subgraph) for termination.

use std::collections::{BTreeSet, VecDeque};

use haz_domain::task_id::TaskId;

use crate::edge::EdgeKind;
use crate::graph::TaskGraph;

/// Direct hard-edge predecessors of `node`: every task `B` such
/// that a hard edge `B -> node` exists in `graph`. Returns the
/// empty set when `node` has no hard-edge predecessors (or is not
/// present in `graph` at all).
#[must_use]
pub fn direct_predecessors(graph: &TaskGraph, node: &TaskId) -> BTreeSet<TaskId> {
    graph
        .edges
        .iter()
        .filter(|edge| edge.kind == EdgeKind::Hard && &edge.to == node)
        .map(|edge| edge.from.clone())
        .collect()
}

/// Direct hard-edge successors of `node`: every task `B` such that
/// a hard edge `node -> B` exists in `graph`. Returns the empty
/// set when `node` has no hard-edge successors (or is not present
/// in `graph` at all).
#[must_use]
pub fn direct_successors(graph: &TaskGraph, node: &TaskId) -> BTreeSet<TaskId> {
    graph
        .edges
        .iter()
        .filter(|edge| edge.kind == EdgeKind::Hard && &edge.from == node)
        .map(|edge| edge.to.clone())
        .collect()
}

/// Transitive hard-edge predecessors of `node`: every task
/// reachable from `node` by walking hard edges backwards. The
/// result does NOT contain `node` itself (the closure is strict,
/// not reflexive); callers that need a reflexive view union the
/// returned set with `{node}` themselves.
#[must_use]
pub fn transitive_predecessors(graph: &TaskGraph, node: &TaskId) -> BTreeSet<TaskId> {
    bfs(graph, node, EdgeDirection::Backward)
}

/// Transitive hard-edge successors of `node`: every task reachable
/// from `node` by walking hard edges forwards. The result does NOT
/// contain `node` itself (the closure is strict, not reflexive);
/// callers that need a reflexive view union the returned set with
/// `{node}` themselves.
#[must_use]
pub fn transitive_successors(graph: &TaskGraph, node: &TaskId) -> BTreeSet<TaskId> {
    bfs(graph, node, EdgeDirection::Forward)
}

#[derive(Clone, Copy)]
enum EdgeDirection {
    Forward,
    Backward,
}

fn bfs(graph: &TaskGraph, seed: &TaskId, direction: EdgeDirection) -> BTreeSet<TaskId> {
    let mut visited: BTreeSet<TaskId> = BTreeSet::new();
    let mut queue: VecDeque<TaskId> = VecDeque::new();
    queue.push_back(seed.clone());
    while let Some(current) = queue.pop_front() {
        let neighbours = match direction {
            EdgeDirection::Forward => direct_successors(graph, &current),
            EdgeDirection::Backward => direct_predecessors(graph, &current),
        };
        for neighbour in neighbours {
            if &neighbour == seed {
                continue;
            }
            if visited.insert(neighbour.clone()) {
                queue.push_back(neighbour);
            }
        }
    }
    visited
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;
    use std::str::FromStr;

    use haz_domain::name::{ProjectName, TaskName};
    use haz_domain::task_id::TaskId;

    use crate::edge::{Edge, EdgeKind};
    use crate::graph::TaskGraph;
    use crate::traversal::{
        direct_predecessors, direct_successors, transitive_predecessors, transitive_successors,
    };

    fn id(project: &str, task: &str) -> TaskId {
        TaskId {
            project: ProjectName::from_str(project).unwrap(),
            task: TaskName::from_str(task).unwrap(),
        }
    }

    fn graph_with(nodes: &[TaskId], edges: &[Edge]) -> TaskGraph {
        TaskGraph {
            nodes: nodes.iter().cloned().collect(),
            edges: edges.iter().cloned().collect(),
        }
    }

    fn ids(items: &[(&str, &str)]) -> BTreeSet<TaskId> {
        items.iter().map(|(p, t)| id(p, t)).collect()
    }

    // --- direct_predecessors / direct_successors ----------------

    #[test]
    fn direct_predecessors_returns_empty_for_isolated_node() {
        let a = id("p", "a");
        let graph = graph_with(std::slice::from_ref(&a), &[]);
        assert!(direct_predecessors(&graph, &a).is_empty());
    }

    #[test]
    fn direct_predecessors_returns_only_immediate_hard_predecessors() {
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b.clone(),
                    to: c.clone(),
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(direct_predecessors(&graph, &c), ids(&[("p", "b")]));
        assert_eq!(direct_predecessors(&graph, &b), ids(&[("p", "a")]));
        assert!(direct_predecessors(&graph, &a).is_empty());
    }

    #[test]
    fn direct_successors_returns_only_immediate_hard_successors() {
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: a.clone(),
                    to: c.clone(),
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(
            direct_successors(&graph, &a),
            ids(&[("p", "b"), ("p", "c")])
        );
        assert!(direct_successors(&graph, &b).is_empty());
        assert!(direct_successors(&graph, &c).is_empty());
    }

    #[test]
    fn direct_predecessors_ignores_soft_edges() {
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with(
            &[a.clone(), b.clone()],
            &[Edge {
                from: a,
                to: b.clone(),
                kind: EdgeKind::Soft,
            }],
        );
        assert!(direct_predecessors(&graph, &b).is_empty());
    }

    #[test]
    fn direct_predecessors_ignores_producer_matching_edges() {
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with(
            &[a.clone(), b.clone()],
            &[Edge {
                from: a,
                to: b.clone(),
                kind: EdgeKind::ProducerMatching,
            }],
        );
        assert!(direct_predecessors(&graph, &b).is_empty());
    }

    #[test]
    fn direct_successors_ignores_soft_and_producer_edges() {
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b,
                    kind: EdgeKind::Soft,
                },
                Edge {
                    from: a.clone(),
                    to: c,
                    kind: EdgeKind::ProducerMatching,
                },
            ],
        );
        assert!(direct_successors(&graph, &a).is_empty());
    }

    // --- transitive_predecessors / transitive_successors --------

    #[test]
    fn transitive_predecessors_walks_chain_backwards() {
        // a -> b -> c -> d
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let d = id("p", "d");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone(), d.clone()],
            &[
                Edge {
                    from: a,
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b,
                    to: c.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: c,
                    to: d.clone(),
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(
            transitive_predecessors(&graph, &d),
            ids(&[("p", "a"), ("p", "b"), ("p", "c")]),
        );
    }

    #[test]
    fn transitive_successors_walks_chain_forwards() {
        // a -> b -> c -> d
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let d = id("p", "d");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone(), d.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b,
                    to: c.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: c,
                    to: d,
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(
            transitive_successors(&graph, &a),
            ids(&[("p", "b"), ("p", "c"), ("p", "d")]),
        );
    }

    #[test]
    fn transitive_closure_handles_diamond_without_duplicates() {
        // a -> b, a -> c, b -> d, c -> d
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let d = id("p", "d");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone(), d.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: a.clone(),
                    to: c.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b,
                    to: d.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: c,
                    to: d.clone(),
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(
            transitive_successors(&graph, &a),
            ids(&[("p", "b"), ("p", "c"), ("p", "d")]),
        );
        assert_eq!(
            transitive_predecessors(&graph, &d),
            ids(&[("p", "a"), ("p", "b"), ("p", "c")]),
        );
    }

    #[test]
    fn transitive_closure_excludes_starting_node() {
        // a -> b -> a is impossible per DAG-012 / DAG-014, but the
        // helper still treats the seed itself as "outside" the
        // closure so the caller is responsible for any reflexive
        // semantics.
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with(
            &[a.clone(), b.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b,
                    to: a.clone(),
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(transitive_successors(&graph, &a), ids(&[("p", "b")]));
    }

    #[test]
    fn transitive_closure_ignores_soft_edges() {
        // a -> b is soft; transitive_successors(a) is empty.
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with(
            &[a.clone(), b.clone()],
            &[Edge {
                from: a.clone(),
                to: b,
                kind: EdgeKind::Soft,
            }],
        );
        assert!(transitive_successors(&graph, &a).is_empty());
    }

    #[test]
    fn transitive_closure_ignores_producer_matching_edges() {
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with(
            &[a.clone(), b.clone(), c.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b.clone(),
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: b,
                    to: c,
                    kind: EdgeKind::ProducerMatching,
                },
            ],
        );
        assert_eq!(transitive_successors(&graph, &a), ids(&[("p", "b")]));
    }

    #[test]
    fn transitive_closure_handles_unrelated_subgraphs() {
        // Component 1: a -> b. Component 2: x -> y.
        let a = id("p", "a");
        let b = id("p", "b");
        let x = id("p", "x");
        let y = id("p", "y");
        let graph = graph_with(
            &[a.clone(), b.clone(), x.clone(), y.clone()],
            &[
                Edge {
                    from: a.clone(),
                    to: b,
                    kind: EdgeKind::Hard,
                },
                Edge {
                    from: x.clone(),
                    to: y,
                    kind: EdgeKind::Hard,
                },
            ],
        );
        assert_eq!(transitive_successors(&graph, &a), ids(&[("p", "b")]));
        assert_eq!(transitive_successors(&graph, &x), ids(&[("p", "y")]));
    }

    #[test]
    fn transitive_closure_returns_empty_for_dead_end() {
        // a is a sink; transitive_successors(a) is empty.
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with(
            &[a.clone(), b.clone()],
            &[Edge {
                from: b,
                to: a.clone(),
                kind: EdgeKind::Hard,
            }],
        );
        assert!(transitive_successors(&graph, &a).is_empty());
    }

    #[test]
    fn transitive_closure_returns_empty_for_isolated_node() {
        let a = id("p", "a");
        let graph = graph_with(std::slice::from_ref(&a), &[]);
        assert!(transitive_successors(&graph, &a).is_empty());
        assert!(transitive_predecessors(&graph, &a).is_empty());
    }
}