ag_session/execution_graph/
graph.rs1use 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
25pub struct ExecutionGraph {
26 pub id: String,
28 pub nodes: Vec<GraphNode>,
30 pub revision: NonZeroU64,
32 pub session_id: SessionId,
34}
35
36impl ExecutionGraph {
37 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.session_id() != &self.session_id {
58 return Err(GraphContractError::ForeignEnv);
59 }
60 if matches!(node.env_id, EnvId::TaskWorktree(_)) {
61 return Err(GraphContractError::UnsupportedEnv);
62 }
63 if let GraphContext::TaskConversation { task_id } = &node.execution.context
64 && !tasks.insert(task_id)
65 {
66 return Err(Self::duplicate("task", task_id));
67 }
68 }
69 for node in &self.nodes {
70 Self::validate_dependencies(node, &nodes)?;
71 }
72
73 self.validate_acyclic()
74 }
75
76 pub fn expand(&self, nodes: Vec<GraphNode>) -> Result<Self, GraphContractError> {
87 if nodes.is_empty() {
88 return Err(GraphContractError::EmptyExpansion);
89 }
90 let revision = self
91 .revision
92 .checked_add(1)
93 .ok_or(GraphContractError::RevisionExhausted)?;
94 let mut graph = self.clone();
95 graph.nodes.extend(nodes);
96 graph.revision = revision;
97 graph.validate()?;
98
99 Ok(graph)
100 }
101
102 pub fn bind_input(
114 &self,
115 node_id: &str,
116 input_name: &str,
117 result: &GraphResult,
118 ) -> Result<GraphResolvedInput, GraphContractError> {
119 self.validate()?;
120 result.reference.validate()?;
121 let consumer = self.node(node_id)?;
122 let binding = consumer
123 .inputs
124 .iter()
125 .find(|input| input.name == input_name)
126 .ok_or(GraphContractError::ResultMismatch("declared input"))?;
127 let reference = &result.reference;
128 if reference.graph_id != self.id || reference.graph_revision > self.revision {
131 return Err(GraphContractError::ResultMismatch(
132 "graph identity or revision",
133 ));
134 }
135 if reference.node_id != binding.producer_node_id
136 || reference.output_name != binding.output_name
137 {
138 return Err(GraphContractError::ResultMismatch("producer or output"));
139 }
140 let producer = self.node(&reference.node_id)?;
141 if reference.schema != producer.execution.response_profile {
142 return Err(GraphContractError::ResultMismatch("output schema"));
143 }
144 match (&producer.execution.context, &reference.execution) {
145 (GraphContext::Fresh, GraphExecutionRef::UtilityRun { .. }) => {}
146 (
147 GraphContext::TaskConversation { task_id },
148 GraphExecutionRef::TaskAttempt {
149 task_id: producing_task,
150 ..
151 },
152 ) if task_id == producing_task => {}
153 _ => return Err(GraphContractError::ResultMismatch("execution authority")),
154 }
155
156 for dependency in &consumer.dependencies {
157 if dependency.node_id == reference.node_id
158 && dependency.gate.output_name() == Some(reference.output_name.as_str())
159 {
160 let satisfied = match dependency.gate {
161 GraphCompletionGate::ResultAccepted { .. } => {
162 result.state == GraphResultState::Accepted
163 }
164 _ => result.state != GraphResultState::Produced,
165 };
166 if !satisfied {
167 return Err(GraphContractError::UnsatisfiedGate);
168 }
169 }
170 }
171
172 Ok(GraphResolvedInput {
173 name: input_name.to_string(),
174 result: reference.clone(),
175 })
176 }
177
178 fn node(&self, id: &str) -> Result<&GraphNode, GraphContractError> {
180 self.nodes
181 .iter()
182 .find(|node| node.id == id)
183 .ok_or_else(|| GraphContractError::UnknownNode(id.to_string()))
184 }
185
186 fn validate_node(node: &GraphNode) -> Result<(), GraphContractError> {
188 GraphContractError::require(&node.id, "node_id")?;
189 GraphContractError::require(&node.definition.id, "definition.id")?;
190 GraphContractError::require(&node.definition.prompt, "definition.prompt")?;
191 GraphContractError::require(&node.objective, "objective")?;
192 GraphContractError::require(&node.request.text, "request")?;
193 node.execution.validate()?;
194 if node.definition.read_only
195 && node.execution.post_processing == GraphPostProcessing::SessionWorkflow
196 {
197 return Err(GraphContractError::InvalidProfile(
198 "read-only definitions cannot perform host mutation effects",
199 ));
200 }
201 let mut outputs = HashSet::new();
202 for output in &node.outputs {
203 GraphContractError::require(&output.name, "output_name")?;
204 if !outputs.insert(&output.name) {
205 return Err(Self::duplicate("output", &output.name));
206 }
207 if output.schema != node.execution.response_profile {
208 return Err(GraphContractError::InvalidProfile(
209 "output schema must match the producing response profile",
210 ));
211 }
212 }
213 let mut inputs = HashSet::new();
214 for input in &node.inputs {
215 GraphContractError::require(&input.name, "input_name")?;
216 GraphContractError::require(&input.producer_node_id, "producer_node_id")?;
217 GraphContractError::require(&input.output_name, "output_name")?;
218 if !inputs.insert(&input.name) {
219 return Err(Self::duplicate("input", &input.name));
220 }
221 }
222
223 Ok(())
224 }
225
226 fn validate_dependencies(
228 node: &GraphNode,
229 nodes: &HashMap<&str, &GraphNode>,
230 ) -> Result<(), GraphContractError> {
231 let mut dependencies = HashSet::new();
232 for dependency in &node.dependencies {
233 let producer = nodes
234 .get(dependency.node_id.as_str())
235 .ok_or_else(|| GraphContractError::UnknownNode(dependency.node_id.clone()))?;
236 if !dependencies.insert(dependency) {
237 return Err(Self::duplicate("dependency", &dependency.node_id));
238 }
239 if let Some(output_name) = dependency.gate.output_name() {
240 Self::require_output(producer, output_name)?;
241 }
242 }
243 for input in &node.inputs {
244 let producer = nodes
245 .get(input.producer_node_id.as_str())
246 .ok_or_else(|| GraphContractError::UnknownNode(input.producer_node_id.clone()))?;
247 Self::require_output(producer, &input.output_name)?;
248 if !node.dependencies.iter().any(|dependency| {
249 dependency.node_id == input.producer_node_id
250 && dependency.gate.output_name() == Some(input.output_name.as_str())
251 }) {
252 return Err(GraphContractError::UngatedInput(input.name.clone()));
253 }
254 }
255
256 Ok(())
257 }
258
259 fn require_output(node: &GraphNode, name: &str) -> Result<(), GraphContractError> {
261 if !node.outputs.iter().any(|output| output.name == name) {
262 return Err(GraphContractError::UnknownOutput {
263 node: node.id.clone(),
264 output: name.to_string(),
265 });
266 }
267
268 Ok(())
269 }
270
271 fn validate_acyclic(&self) -> Result<(), GraphContractError> {
275 let mut topology = DiGraph::<(), ()>::new();
276 let indices: HashMap<_, _> = self
277 .nodes
278 .iter()
279 .map(|node| (node.id.as_str(), topology.add_node(())))
280 .collect();
281 for node in &self.nodes {
282 for dependency in &node.dependencies {
283 topology.add_edge(
284 indices[dependency.node_id.as_str()],
285 indices[node.id.as_str()],
286 (),
287 );
288 }
289 }
290
291 algo::toposort(&topology, None)
292 .map(|_| ())
293 .map_err(|_| GraphContractError::Cycle)
294 }
295
296 fn duplicate(kind: &'static str, id: &str) -> GraphContractError {
298 GraphContractError::Duplicate {
299 kind,
300 id: id.to_string(),
301 }
302 }
303}
304
305#[cfg(test)]
306#[path = "graph_test.rs"]
307mod tests;