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.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    /// Returns the next revision: this one with `nodes` appended.
77    ///
78    /// Existing nodes stay exactly as they are, so their executions, results,
79    /// and pinned inputs remain valid under the new revision. Appended nodes
80    /// may depend on existing nodes, never the reverse.
81    ///
82    /// # Errors
83    /// Rejects an empty expansion, an exhausted revision counter, and any
84    /// expanded graph that fails [`Self::validate`], such as one reusing a
85    /// node or task identity.
86    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    /// Pins one declared input to a host-loaded, validated or accepted version.
103    ///
104    /// The result may come from this revision or an earlier one; hosts admit
105    /// an earlier one only when every later revision appended nodes. This
106    /// checks shape and consistency only. Hosts must load result state
107    /// from authoritative storage, validate all dependency gates atomically at
108    /// dispatch, and persist every resolved input with the execution admission.
109    ///
110    /// # Errors
111    /// Rejects invalid graphs, undeclared inputs, foreign or stale results,
112    /// schema/execution mismatches, and unsatisfied result gates.
113    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        // A result from an earlier revision stays bindable once later
129        // revisions only appended nodes; hosts check that lineage.
130        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    /// Looks up a node using the same scoped error for consumers and producers.
179    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    /// Validates fields owned by a single node without following edges.
187    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    /// Validates each gate and requires a matching gate for every result input.
227    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    /// Reports undeclared outputs consistently for both gates and bindings.
260    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    /// Checks validated dependency references with an iterative traversal,
272    /// preserving caller order and avoiding recursion for caller-supplied
273    /// depth.
274    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    /// Constructs a scoped uniqueness error without losing the conflicting ID.
297    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;