Skip to main content

ag_session/execution_graph/
graph.rs

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