haz-query 0.1.0

Query evaluator over haz task DAGs.
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
//! Per-task evaluation of the relational filters of `QRY-004`.
//!
//! Each relational filter resolves a user expression to a *target
//! set* (every task whose project/task/tag attributes satisfy the
//! expression), then asks whether the candidate's hard-edge
//! relation to that target set is non-empty.
//!
//! Direct relations (`--child-of`, `--parent-of`) read the
//! candidate's direct hard-edge neighbours and intersect them with
//! the target set. Transitive relations (`--depends-on`,
//! `--ancestor-of`) BFS over hard edges; per `QRY-004` the result
//! excludes the target set itself ("minus the EXPR-matching tasks
//! themselves").
//!
//! Target sets are computed once per relational flag in
//! [`RelationalTargets::from_spec`] and shared across all
//! candidates; per-candidate work is then a set intersection or a
//! BFS.

use std::collections::BTreeSet;

use haz_dag::graph::TaskGraph;
use haz_dag::traversal::{
    direct_predecessors, direct_successors, transitive_predecessors, transitive_successors,
};
use haz_domain::task_id::TaskId;
use haz_domain::workspace::Workspace;
use haz_query_lang::expr::Expr;

use crate::engine::spec::QuerySpec;
use crate::expr::relational::RelationalAtom;

/// Target sets for every relational filter in a [`QuerySpec`].
///
/// A `None` field means the corresponding flag was not supplied;
/// `Some(set)` means the flag was supplied and the contained set
/// is its target set.
#[derive(Debug, Default, Clone)]
pub struct RelationalTargets {
    /// Target set of `--child-of`.
    pub child_of: Option<BTreeSet<TaskId>>,
    /// Target set of `--parent-of`.
    pub parent_of: Option<BTreeSet<TaskId>>,
    /// Target set of `--depends-on`.
    pub depends_on: Option<BTreeSet<TaskId>>,
    /// Target set of `--ancestor-of`.
    pub ancestor_of: Option<BTreeSet<TaskId>>,
}

impl RelationalTargets {
    /// Compute the target set of every relational filter present
    /// in `spec`. An absent filter yields a `None` field; the
    /// computation is therefore proportional to the number of
    /// supplied flags, never four full walks.
    #[must_use]
    pub fn from_spec(workspace: &Workspace, spec: &QuerySpec) -> Self {
        Self {
            child_of: spec
                .child_of
                .as_ref()
                .map(|expr| compute_target_set(workspace, expr)),
            parent_of: spec
                .parent_of
                .as_ref()
                .map(|expr| compute_target_set(workspace, expr)),
            depends_on: spec
                .depends_on
                .as_ref()
                .map(|expr| compute_target_set(workspace, expr)),
            ancestor_of: spec
                .ancestor_of
                .as_ref()
                .map(|expr| compute_target_set(workspace, expr)),
        }
    }
}

/// Compute the target set of a relational expression: every task
/// in the workspace whose `(project_name, task_name,
/// project_tags)` triple satisfies `expr`.
///
/// Returned as a `BTreeSet`, which iterates in canonical
/// `(ProjectName, TaskName)` order.
#[must_use]
pub fn compute_target_set(workspace: &Workspace, expr: &Expr<RelationalAtom>) -> BTreeSet<TaskId> {
    let mut target_set: BTreeSet<TaskId> = BTreeSet::new();
    for project in workspace.projects.values() {
        for task_name in project.tasks.keys() {
            let matches = expr.eval(|atom| atom.matches(&project.name, task_name, &project.tags));
            if matches {
                target_set.insert(TaskId {
                    project: project.name.clone(),
                    task: task_name.clone(),
                });
            }
        }
    }
    target_set
}

/// Whether `candidate` passes every relational filter in
/// `targets`. A `None` filter contributes no constraint; a
/// `Some(set)` filter requires the appropriate hard-edge relation
/// to that set to be non-empty.
#[must_use]
pub fn passes_relational(
    graph: &TaskGraph,
    candidate: &TaskId,
    targets: &RelationalTargets,
) -> bool {
    if let Some(set) = &targets.child_of
        && !passes_child_of(graph, candidate, set)
    {
        return false;
    }
    if let Some(set) = &targets.parent_of
        && !passes_parent_of(graph, candidate, set)
    {
        return false;
    }
    if let Some(set) = &targets.depends_on
        && !passes_depends_on(graph, candidate, set)
    {
        return false;
    }
    if let Some(set) = &targets.ancestor_of
        && !passes_ancestor_of(graph, candidate, set)
    {
        return false;
    }
    true
}

/// `--child-of EXPR`: at least one direct hard-edge predecessor of
/// `candidate` is in `targets` (the candidate's `deps:` names a
/// target).
#[must_use]
pub fn passes_child_of(graph: &TaskGraph, candidate: &TaskId, targets: &BTreeSet<TaskId>) -> bool {
    !direct_predecessors(graph, candidate).is_disjoint(targets)
}

/// `--parent-of EXPR`: at least one direct hard-edge successor of
/// `candidate` is in `targets` (some target's `deps:` names the
/// candidate).
#[must_use]
pub fn passes_parent_of(graph: &TaskGraph, candidate: &TaskId, targets: &BTreeSet<TaskId>) -> bool {
    !direct_successors(graph, candidate).is_disjoint(targets)
}

/// `--depends-on EXPR`: at least one transitive hard-edge
/// predecessor of `candidate` is in `targets` AND `candidate` is
/// not itself in `targets` (per the "minus the EXPR-matching
/// tasks themselves" clause of `QRY-004`).
#[must_use]
pub fn passes_depends_on(
    graph: &TaskGraph,
    candidate: &TaskId,
    targets: &BTreeSet<TaskId>,
) -> bool {
    if targets.contains(candidate) {
        return false;
    }
    !transitive_predecessors(graph, candidate).is_disjoint(targets)
}

/// `--ancestor-of EXPR`: at least one transitive hard-edge
/// successor of `candidate` is in `targets` AND `candidate` is
/// not itself in `targets` (per the "minus the EXPR-matching
/// tasks themselves" clause of `QRY-004`).
#[must_use]
pub fn passes_ancestor_of(
    graph: &TaskGraph,
    candidate: &TaskId,
    targets: &BTreeSet<TaskId>,
) -> bool {
    if targets.contains(candidate) {
        return false;
    }
    !transitive_successors(graph, candidate).is_disjoint(targets)
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, BTreeSet};
    use std::path::PathBuf;
    use std::str::FromStr;

    use haz_dag::edge::{Edge, EdgeKind};
    use haz_dag::graph::TaskGraph;
    use haz_domain::action::TaskAction;
    use haz_domain::env::EnvSettings;
    use haz_domain::name::{ProjectName, TagName, TaskName};
    use haz_domain::path::{CanonicalPath, HazPath, ProjectRoot, WorkspaceRootPath};
    use haz_domain::project::Project;
    use haz_domain::settings::WorkspaceSettings;
    use haz_domain::task::Task;
    use haz_domain::task_id::TaskId;
    use haz_domain::workspace::Workspace;
    use haz_query_lang::expr::Expr;
    use nonempty::NonEmpty;

    use super::*;

    fn argv(parts: &[&str]) -> NonEmpty<String> {
        NonEmpty::from_vec(parts.iter().map(|s| (*s).to_owned()).collect()).unwrap()
    }

    fn bare_task(name: &str) -> Task {
        Task {
            name: TaskName::from_str(name).unwrap(),
            action: TaskAction::Command(argv(&["true"])),
            inputs: vec![],
            outputs: vec![],
            deps: vec![],
            weak_deps: vec![],
            mutex: None,
            env: EnvSettings::default(),
        }
    }

    fn project(name: &str, root: &str, tags: &[&str], task_names: &[&str]) -> Project {
        let mut tasks = BTreeMap::new();
        for &task_name in task_names {
            tasks.insert(TaskName::from_str(task_name).unwrap(), bare_task(task_name));
        }
        Project {
            name: ProjectName::from_str(name).unwrap(),
            root: ProjectRoot::Nested(
                CanonicalPath::from_absolute(&HazPath::parse(root).unwrap()).unwrap(),
            ),
            tags: tags
                .iter()
                .map(|t| TagName::from_str(t).unwrap())
                .collect::<BTreeSet<_>>(),
            tasks,
        }
    }

    fn workspace(projects: Vec<Project>) -> Workspace {
        let mut map = BTreeMap::new();
        for p in projects {
            map.insert(p.name.clone(), p);
        }
        Workspace {
            root: WorkspaceRootPath::try_new(PathBuf::from("/abs/workspace")).unwrap(),
            projects: map,
            overlays: BTreeMap::new(),
            settings: WorkspaceSettings::default(),
        }
    }

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

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

    fn graph_with_hard_edges(nodes: &[TaskId], edges: &[(TaskId, TaskId)]) -> TaskGraph {
        TaskGraph {
            nodes: nodes.iter().cloned().collect(),
            edges: edges
                .iter()
                .map(|(from, to)| Edge {
                    from: from.clone(),
                    to: to.clone(),
                    kind: EdgeKind::Hard,
                })
                .collect(),
        }
    }

    fn relational_atom(text: &str) -> Expr<RelationalAtom> {
        use haz_query_lang::expr::RawAtom;
        use haz_query_lang::span::Span;

        use crate::expr::relational::parse_relational_atom;
        Expr::Atom(
            parse_relational_atom(RawAtom {
                text: text.to_owned(),
                span: Span { start: 0, end: 0 },
            })
            .unwrap(),
        )
    }

    // --- compute_target_set -------------------------------------

    #[test]
    fn target_set_for_name_atom_collects_matching_tasks_across_projects() {
        let ws = workspace(vec![
            project("lib", "/lib", &[], &["build", "test"]),
            project("web", "/web", &[], &["build", "bundle"]),
        ]);
        let expr = relational_atom("name:build");
        let target = compute_target_set(&ws, &expr);
        assert_eq!(target, ids(&[("lib", "build"), ("web", "build")]));
    }

    #[test]
    fn target_set_for_project_atom_collects_every_task_in_that_project() {
        let ws = workspace(vec![
            project("lib", "/lib", &[], &["build", "test"]),
            project("web", "/web", &[], &["bundle"]),
        ]);
        let expr = relational_atom("project:lib");
        let target = compute_target_set(&ws, &expr);
        assert_eq!(target, ids(&[("lib", "build"), ("lib", "test")]));
    }

    #[test]
    fn target_set_for_tag_atom_collects_tasks_under_tagged_projects() {
        let ws = workspace(vec![
            project("lib", "/lib", &["backend"], &["build"]),
            project("tools", "/tools", &["backend"], &["lint"]),
            project("web", "/web", &["frontend"], &["bundle"]),
        ]);
        let expr = relational_atom("tag:backend");
        let target = compute_target_set(&ws, &expr);
        assert_eq!(target, ids(&[("lib", "build"), ("tools", "lint")]));
    }

    #[test]
    fn target_set_under_boolean_composition_intersects() {
        let ws = workspace(vec![
            project("lib", "/lib", &["backend"], &["build", "test"]),
            project("web", "/web", &["frontend"], &["test"]),
        ]);
        // tag:backend & name:test  -> only lib:test
        let expr = Expr::And(
            Box::new(relational_atom("tag:backend")),
            Box::new(relational_atom("name:test")),
        );
        let target = compute_target_set(&ws, &expr);
        assert_eq!(target, ids(&[("lib", "test")]));
    }

    #[test]
    fn target_set_is_empty_when_no_task_matches() {
        let ws = workspace(vec![project("lib", "/lib", &[], &["build"])]);
        let expr = relational_atom("name:absent");
        let target = compute_target_set(&ws, &expr);
        assert!(target.is_empty());
    }

    // --- passes_child_of / passes_parent_of ---------------------

    #[test]
    fn child_of_passes_when_direct_predecessor_in_target_set() {
        // graph: a -> b
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with_hard_edges(&[a.clone(), b.clone()], &[(a.clone(), b.clone())]);
        let targets = ids(&[("p", "a")]);
        assert!(passes_child_of(&graph, &b, &targets));
        assert!(!passes_child_of(&graph, &a, &targets));
    }

    #[test]
    fn parent_of_passes_when_direct_successor_in_target_set() {
        // graph: a -> b
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with_hard_edges(&[a.clone(), b.clone()], &[(a.clone(), b.clone())]);
        let targets = ids(&[("p", "b")]);
        assert!(passes_parent_of(&graph, &a, &targets));
        assert!(!passes_parent_of(&graph, &b, &targets));
    }

    #[test]
    fn child_of_rejects_when_target_is_only_transitive_predecessor() {
        // graph: a -> b -> c, target = a
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with_hard_edges(
            &[a.clone(), b.clone(), c.clone()],
            &[(a.clone(), b.clone()), (b, c.clone())],
        );
        let targets = ids(&[("p", "a")]);
        // c's only direct predecessor is b, not a.
        assert!(!passes_child_of(&graph, &c, &targets));
    }

    // --- passes_depends_on --------------------------------------

    #[test]
    fn depends_on_passes_when_transitive_predecessor_in_target_set() {
        // graph: a -> b -> c, target = a
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with_hard_edges(
            &[a.clone(), b.clone(), c.clone()],
            &[(a.clone(), b.clone()), (b.clone(), c.clone())],
        );
        let targets = ids(&[("p", "a")]);
        assert!(passes_depends_on(&graph, &c, &targets));
        assert!(passes_depends_on(&graph, &b, &targets));
        // a is in target_set, so excluded by the QRY-004 clause.
        assert!(!passes_depends_on(&graph, &a, &targets));
    }

    #[test]
    fn depends_on_excludes_self_when_candidate_in_target_set() {
        // graph: a -> b -> c, target = {a, c} (both endpoints).
        // c is in targets, so c MUST be excluded from `depends-on
        // targets` even though c transitively depends on a.
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with_hard_edges(
            &[a.clone(), b.clone(), c.clone()],
            &[(a.clone(), b.clone()), (b.clone(), c.clone())],
        );
        let targets = ids(&[("p", "a"), ("p", "c")]);
        assert!(!passes_depends_on(&graph, &c, &targets));
        assert!(passes_depends_on(&graph, &b, &targets));
    }

    // --- passes_ancestor_of -------------------------------------

    #[test]
    fn ancestor_of_passes_when_transitive_successor_in_target_set() {
        // graph: a -> b -> c, target = c
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with_hard_edges(
            &[a.clone(), b.clone(), c.clone()],
            &[(a.clone(), b.clone()), (b.clone(), c.clone())],
        );
        let targets = ids(&[("p", "c")]);
        assert!(passes_ancestor_of(&graph, &a, &targets));
        assert!(passes_ancestor_of(&graph, &b, &targets));
        // c is in target_set, excluded.
        assert!(!passes_ancestor_of(&graph, &c, &targets));
    }

    #[test]
    fn ancestor_of_excludes_self_when_candidate_in_target_set() {
        let a = id("p", "a");
        let b = id("p", "b");
        let c = id("p", "c");
        let graph = graph_with_hard_edges(
            &[a.clone(), b.clone(), c.clone()],
            &[(a.clone(), b.clone()), (b.clone(), c.clone())],
        );
        let targets = ids(&[("p", "a"), ("p", "c")]);
        assert!(!passes_ancestor_of(&graph, &a, &targets));
        assert!(passes_ancestor_of(&graph, &b, &targets));
    }

    // --- empty target set ---------------------------------------

    #[test]
    fn every_relation_fails_when_target_set_is_empty() {
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with_hard_edges(&[a.clone(), b.clone()], &[(a.clone(), b.clone())]);
        let empty: BTreeSet<TaskId> = BTreeSet::new();
        assert!(!passes_child_of(&graph, &b, &empty));
        assert!(!passes_parent_of(&graph, &a, &empty));
        assert!(!passes_depends_on(&graph, &b, &empty));
        assert!(!passes_ancestor_of(&graph, &a, &empty));
    }

    // --- passes_relational composes the four arms ---------------

    #[test]
    fn passes_relational_returns_true_when_no_filter_set() {
        let a = id("p", "a");
        let graph = graph_with_hard_edges(std::slice::from_ref(&a), &[]);
        let targets = RelationalTargets::default();
        assert!(passes_relational(&graph, &a, &targets));
    }

    #[test]
    fn passes_relational_short_circuits_on_first_failing_filter() {
        // a -> b, candidate = b.
        // child_of = {a} (passes), parent_of = {a} (fails: a has
        // no successor relationship from b).
        let a = id("p", "a");
        let b = id("p", "b");
        let graph = graph_with_hard_edges(&[a.clone(), b.clone()], &[(a.clone(), b.clone())]);
        let targets = RelationalTargets {
            child_of: Some(ids(&[("p", "a")])),
            parent_of: Some(ids(&[("p", "a")])),
            ..RelationalTargets::default()
        };
        assert!(!passes_relational(&graph, &b, &targets));
    }
}