Skip to main content

ag_session/execution_graph/
graph.rs

1//! Static execution graph revisions, their structural validation, and exact
2//! input binding.
3
4use std::collections::{HashMap, HashSet};
5use std::num::NonZeroU64;
6
7use petgraph::algo;
8use petgraph::graph::DiGraph;
9use serde::{Deserialize, Serialize};
10
11use super::{
12    GraphCompletionGate, GraphContext, GraphContractError, GraphExecutionRef, GraphNode,
13    GraphPostProcessing, GraphResolvedInput, GraphResult, GraphResultState,
14};
15use crate::{EnvId, SessionId};
16
17/// A revision of an arbitrary static execution graph owned by one session.
18///
19/// These contracts do not persist, schedule, or execute nodes. Hosts validate
20/// before admission and enforce budgets, record ownership, permissions, Env
21/// conflicts, and existing worker capacity. A revision is a stale-action fence,
22/// not authorization to mutate started work or automatically replay after
23/// restart.
24#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
25pub struct ExecutionGraph {
26    /// Stable graph-instance identity, separate from command delivery identity.
27    pub id: String,
28    /// Nodes in caller order; validation never reorders or dispatches them.
29    pub nodes: Vec<GraphNode>,
30    /// Nonzero immutable revision captured by every admitted execution/result.
31    pub revision: NonZeroU64,
32    /// Session owning this graph and its currently supported shared local Env.
33    pub session_id: SessionId,
34}
35
36impl ExecutionGraph {
37    /// Checks identities, execution profiles, local references, and acyclicity.
38    ///
39    /// # Errors
40    /// Rejects empty graphs, blank or duplicate identities, foreign Envs,
41    /// incompatible schemas/profiles, missing nodes/outputs, ungated inputs,
42    /// duplicate edges, and cycles. No storage or runtime is consulted.
43    pub fn validate(&self) -> Result<(), GraphContractError> {
44        GraphContractError::require(&self.id, "graph_id")?;
45        GraphContractError::require(self.session_id.as_str(), "session_id")?;
46        if self.nodes.is_empty() {
47            return Err(GraphContractError::EmptyGraph);
48        }
49
50        let mut nodes = HashMap::new();
51        let mut tasks = HashSet::new();
52        for node in &self.nodes {
53            Self::validate_node(node)?;
54            if nodes.insert(node.id.as_str(), node).is_some() {
55                return Err(Self::duplicate("node", &node.id));
56            }
57            if node.env_id != EnvId::SessionWorktree(self.session_id.clone()) {
58                return Err(GraphContractError::ForeignEnv);
59            }
60            if let GraphContext::TaskConversation { task_id } = &node.execution.context
61                && !tasks.insert(task_id)
62            {
63                return Err(Self::duplicate("task", task_id));
64            }
65        }
66        for node in &self.nodes {
67            Self::validate_dependencies(node, &nodes)?;
68        }
69
70        self.validate_acyclic()
71    }
72
73    /// Pins one declared input to a host-loaded, validated or accepted version.
74    ///
75    /// This checks shape and consistency only. Hosts must load result state
76    /// from authoritative storage, validate all dependency gates atomically at
77    /// dispatch, and persist every resolved input with the execution admission.
78    ///
79    /// # Errors
80    /// Rejects invalid graphs, undeclared inputs, foreign or stale results,
81    /// schema/execution mismatches, and unsatisfied result gates.
82    pub fn bind_input(
83        &self,
84        node_id: &str,
85        input_name: &str,
86        result: &GraphResult,
87    ) -> Result<GraphResolvedInput, GraphContractError> {
88        self.validate()?;
89        result.reference.validate()?;
90        let consumer = self.node(node_id)?;
91        let binding = consumer
92            .inputs
93            .iter()
94            .find(|input| input.name == input_name)
95            .ok_or(GraphContractError::ResultMismatch("declared input"))?;
96        let reference = &result.reference;
97        if reference.graph_id != self.id || reference.graph_revision != self.revision {
98            return Err(GraphContractError::ResultMismatch(
99                "graph identity or revision",
100            ));
101        }
102        if reference.node_id != binding.producer_node_id
103            || reference.output_name != binding.output_name
104        {
105            return Err(GraphContractError::ResultMismatch("producer or output"));
106        }
107        let producer = self.node(&reference.node_id)?;
108        if reference.schema != producer.execution.response_profile {
109            return Err(GraphContractError::ResultMismatch("output schema"));
110        }
111        match (&producer.execution.context, &reference.execution) {
112            (GraphContext::Fresh, GraphExecutionRef::UtilityRun { .. }) => {}
113            (
114                GraphContext::TaskConversation { task_id },
115                GraphExecutionRef::TaskAttempt {
116                    task_id: producing_task,
117                    ..
118                },
119            ) if task_id == producing_task => {}
120            _ => return Err(GraphContractError::ResultMismatch("execution authority")),
121        }
122
123        for dependency in &consumer.dependencies {
124            if dependency.node_id == reference.node_id
125                && dependency.gate.output_name() == Some(reference.output_name.as_str())
126            {
127                let satisfied = match dependency.gate {
128                    GraphCompletionGate::ResultAccepted { .. } => {
129                        result.state == GraphResultState::Accepted
130                    }
131                    _ => result.state != GraphResultState::Produced,
132                };
133                if !satisfied {
134                    return Err(GraphContractError::UnsatisfiedGate);
135                }
136            }
137        }
138
139        Ok(GraphResolvedInput {
140            name: input_name.to_string(),
141            result: reference.clone(),
142        })
143    }
144
145    /// Looks up a node using the same scoped error for consumers and producers.
146    fn node(&self, id: &str) -> Result<&GraphNode, GraphContractError> {
147        self.nodes
148            .iter()
149            .find(|node| node.id == id)
150            .ok_or_else(|| GraphContractError::UnknownNode(id.to_string()))
151    }
152
153    /// Validates fields owned by a single node without following edges.
154    fn validate_node(node: &GraphNode) -> Result<(), GraphContractError> {
155        GraphContractError::require(&node.id, "node_id")?;
156        GraphContractError::require(&node.definition.id, "definition.id")?;
157        GraphContractError::require(&node.definition.prompt, "definition.prompt")?;
158        GraphContractError::require(&node.objective, "objective")?;
159        GraphContractError::require(&node.request.text, "request")?;
160        node.execution.validate()?;
161        if node.definition.read_only
162            && node.execution.post_processing == GraphPostProcessing::SessionWorkflow
163        {
164            return Err(GraphContractError::InvalidProfile(
165                "read-only definitions cannot perform host mutation effects",
166            ));
167        }
168        let mut outputs = HashSet::new();
169        for output in &node.outputs {
170            GraphContractError::require(&output.name, "output_name")?;
171            if !outputs.insert(&output.name) {
172                return Err(Self::duplicate("output", &output.name));
173            }
174            if output.schema != node.execution.response_profile {
175                return Err(GraphContractError::InvalidProfile(
176                    "output schema must match the producing response profile",
177                ));
178            }
179        }
180        let mut inputs = HashSet::new();
181        for input in &node.inputs {
182            GraphContractError::require(&input.name, "input_name")?;
183            GraphContractError::require(&input.producer_node_id, "producer_node_id")?;
184            GraphContractError::require(&input.output_name, "output_name")?;
185            if !inputs.insert(&input.name) {
186                return Err(Self::duplicate("input", &input.name));
187            }
188        }
189
190        Ok(())
191    }
192
193    /// Validates each gate and requires a matching gate for every result input.
194    fn validate_dependencies(
195        node: &GraphNode,
196        nodes: &HashMap<&str, &GraphNode>,
197    ) -> Result<(), GraphContractError> {
198        let mut dependencies = HashSet::new();
199        for dependency in &node.dependencies {
200            let producer = nodes
201                .get(dependency.node_id.as_str())
202                .ok_or_else(|| GraphContractError::UnknownNode(dependency.node_id.clone()))?;
203            if !dependencies.insert(dependency) {
204                return Err(Self::duplicate("dependency", &dependency.node_id));
205            }
206            if let Some(output_name) = dependency.gate.output_name() {
207                Self::require_output(producer, output_name)?;
208            }
209        }
210        for input in &node.inputs {
211            let producer = nodes
212                .get(input.producer_node_id.as_str())
213                .ok_or_else(|| GraphContractError::UnknownNode(input.producer_node_id.clone()))?;
214            Self::require_output(producer, &input.output_name)?;
215            if !node.dependencies.iter().any(|dependency| {
216                dependency.node_id == input.producer_node_id
217                    && dependency.gate.output_name() == Some(input.output_name.as_str())
218            }) {
219                return Err(GraphContractError::UngatedInput(input.name.clone()));
220            }
221        }
222
223        Ok(())
224    }
225
226    /// Reports undeclared outputs consistently for both gates and bindings.
227    fn require_output(node: &GraphNode, name: &str) -> Result<(), GraphContractError> {
228        if !node.outputs.iter().any(|output| output.name == name) {
229            return Err(GraphContractError::UnknownOutput {
230                node: node.id.clone(),
231                output: name.to_string(),
232            });
233        }
234
235        Ok(())
236    }
237
238    /// Checks validated dependency references with an iterative traversal,
239    /// preserving caller order and avoiding recursion for caller-supplied
240    /// depth.
241    fn validate_acyclic(&self) -> Result<(), GraphContractError> {
242        let mut topology = DiGraph::<(), ()>::new();
243        let indices: HashMap<_, _> = self
244            .nodes
245            .iter()
246            .map(|node| (node.id.as_str(), topology.add_node(())))
247            .collect();
248        for node in &self.nodes {
249            for dependency in &node.dependencies {
250                topology.add_edge(
251                    indices[dependency.node_id.as_str()],
252                    indices[node.id.as_str()],
253                    (),
254                );
255            }
256        }
257
258        algo::toposort(&topology, None)
259            .map(|_| ())
260            .map_err(|_| GraphContractError::Cycle)
261    }
262
263    /// Constructs a scoped uniqueness error without losing the conflicting ID.
264    fn duplicate(kind: &'static str, id: &str) -> GraphContractError {
265        GraphContractError::Duplicate {
266            kind,
267            id: id.to_string(),
268        }
269    }
270}
271
272#[cfg(test)]
273#[path = "graph_test.rs"]
274mod tests;