Skip to main content

artifactize_core/
query.rs

1//! Read-only state queries and result projections.
2
3mod summary;
4pub use summary::{
5    Kinds, RunOutput, Source, SourceKind, profile_name, request_output, request_summary, reused,
6    run_output, run_summary, source,
7};
8
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    path::Path,
12};
13
14use serde::Serialize;
15
16use crate::{
17    config::{Artifact, Eval, RepoConfig},
18    graph::Graph,
19    project::selection::Selection,
20    scope::Relation,
21};
22
23/// The format version of the printed graph: the shape of its Artifacts, evals, relations
24/// and components. It changes when a field is removed or changes meaning, so that scripts
25/// reading the output can refuse a shape they do not know.
26const GRAPH_FORMAT_VERSION: u32 = 3;
27
28#[derive(Debug, Serialize)]
29#[serde(rename_all = "camelCase")]
30pub struct GraphView<'a> {
31    pub version: u32,
32    #[serde(serialize_with = "crate::platform::path_serde::serialize")]
33    pub repo_path: &'a Path,
34    pub selection: &'a Selection,
35    pub artifacts: BTreeMap<&'a crate::config::ArtifactName, &'a Artifact>,
36    pub evals: Vec<&'a Eval>,
37    pub relations: Vec<GraphRelation<'a>>,
38    pub components: Vec<GraphComponent<'a>>,
39    /// The environment variables the project's profiles read, each with its value (`null`
40    /// while unset); a Run's saved graph records the branch every Agent eval ran with.
41    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
42    pub environment: BTreeMap<&'a str, Option<&'a str>>,
43}
44
45#[derive(Debug, Serialize)]
46pub struct GraphRelation<'a> {
47    #[serde(flatten)]
48    pub relation: &'a Relation,
49    pub cyclic: bool,
50}
51
52#[derive(Debug, Serialize)]
53pub struct GraphComponent<'a> {
54    pub id: crate::graph::ComponentId,
55    pub artifacts: Vec<&'a crate::config::ArtifactName>,
56    pub dependencies: Vec<crate::graph::ComponentId>,
57    pub gates: Vec<&'a crate::config::EvalId>,
58    pub cyclic: bool,
59}
60
61/// Full static definitions, restricted to the selected dependency closure.
62pub fn graph<'a>(
63    config: &'a RepoConfig,
64    selection: &'a Selection,
65) -> Result<GraphView<'a>, String> {
66    let graph = Graph::new(config).map_err(|error| error.to_string())?;
67    let selected = selection.resolve(config)?;
68    let required = graph
69        .dependency_closure(&selected.roots)
70        .map_err(|error| error.to_string())?;
71    Ok(scoped_graph(config, selection, &graph, required))
72}
73
74pub(crate) fn scoped_graph<'a>(
75    config: &'a RepoConfig,
76    selection: &'a Selection,
77    graph: &Graph<'a>,
78    required: impl IntoIterator<Item = &'a crate::config::ArtifactName>,
79) -> GraphView<'a> {
80    let artifacts: BTreeMap<_, _> = required
81        .into_iter()
82        .map(|id| (id, &config.artifacts[id]))
83        .collect();
84    let evals = config
85        .evals
86        .iter()
87        .filter(|eval| artifacts.contains_key(&eval.target))
88        .collect();
89    let relations: Vec<_> = config
90        .relations
91        .iter()
92        .filter(|relation| {
93            artifacts.contains_key(&relation.source) && artifacts.contains_key(&relation.target)
94        })
95        .map(|relation| GraphRelation {
96            relation,
97            cyclic: graph.artifacts()[relation.source.as_str()].component
98                == graph.artifacts()[relation.target.as_str()].component,
99        })
100        .collect();
101    let cyclic: BTreeSet<_> = relations
102        .iter()
103        .filter(|edge| edge.cyclic)
104        .map(|edge| graph.artifacts()[&edge.relation.source].component)
105        .collect();
106    let components = graph
107        .components()
108        .iter()
109        .enumerate()
110        .filter(|(_, component)| artifacts.contains_key(component.artifacts[0]))
111        .map(|(id, component)| GraphComponent {
112            id: crate::graph::ComponentId::from_position(id),
113            artifacts: component.artifacts.clone(),
114            dependencies: component.dependencies.clone(),
115            gates: component.gates.clone(),
116            cyclic: component.artifacts.len() > 1
117                || cyclic.contains(&crate::graph::ComponentId::from_position(id)),
118        })
119        .collect();
120    GraphView {
121        version: GRAPH_FORMAT_VERSION,
122        repo_path: &config.root,
123        selection,
124        artifacts,
125        evals,
126        relations,
127        components,
128        environment: config
129            .program
130            .iter()
131            .flat_map(|program| &program.environment)
132            .map(|(name, value)| (name.as_str(), value.as_deref()))
133            .collect(),
134    }
135}
136
137/// Conservative change impact: consumers of the selected roots, including cycle peers.
138/// This is structural reachability, not a prediction that every eval's reuse key changed.
139pub fn impact(config: &RepoConfig, selection: &Selection) -> Result<Selection, String> {
140    let resolved = selection.resolve(config)?;
141    let mut affected: std::collections::BTreeSet<_> = resolved.roots.into_iter().cloned().collect();
142    loop {
143        let consumers: Vec<_> = config
144            .relations
145            .iter()
146            .filter(|edge| affected.contains(&edge.source))
147            .map(|edge| edge.target.clone())
148            .collect();
149        let before = affected.len();
150        affected.extend(consumers);
151        if affected.len() == before {
152            break;
153        }
154    }
155    Ok(Selection::Artifacts {
156        artifact_ids: affected.into_iter().collect(),
157    })
158}