Fully Automated - 100% Backpressure - Pipeline runner ๐Ÿƒ for AI workflows. ๐Ÿš€

Commit ccc7e6a1

ccc7e6a1e69fMerged

Scott Nixon <[email protected]> ยท 9 months ago ยท 1 file ยท ~1 modified

Description

fix: Set default pipeline budget to $200 instead of unlimited

Without --max-budget-usd flag, budget defaulted to f64::MAX making budget_remaining meaningless in logs and providing no spending guardrail.

Details

Commit
ccc7e6a1e69f
Parent
8981d12d6227

crates/attractor-pipeline/src/engine.rsmodifiedView file

@@ -1,0 +1,768 @@
1+//! Pipeline execution engine โ€” the core traversal loop.
2+//!
3+//! Implements the 5-phase lifecycle: parse, validate, initialize, execute, finalize.
4+
5+use std::collections::HashMap;
6+use std::path::PathBuf;
7+
8+use attractor_types::{AttractorError, Context, Outcome, Result, StageStatus};
9+
10+use crate::edge_selection::select_edge;
11+use crate::goal_gate::enforce_goal_gates;
12+use crate::graph::PipelineGraph;
13+use crate::handler::{default_registry, HandlerRegistry};
14+use crate::validation::validate_or_raise;
15+
16+// ---------------------------------------------------------------------------
17+// Public types
18+// ---------------------------------------------------------------------------
19+
20+/// The core pipeline executor. Owns a handler registry and drives graph traversal.
21+pub struct PipelineExecutor {
22+ registry: HandlerRegistry,
23+}
24+
25+/// Configuration for a pipeline run.
26+pub struct PipelineConfig {
27+ pub logs_root: PathBuf,
28+}
29+
30+/// The result of a completed pipeline execution.
31+#[derive(Debug)]
32+pub struct PipelineResult {
33+ pub completed_nodes: Vec<String>,
34+ pub node_outcomes: HashMap<String, Outcome>,
35+ pub final_context: HashMap<String, serde_json::Value>,
36+}
37+
38+// ---------------------------------------------------------------------------
39+// Helpers
40+// ---------------------------------------------------------------------------
41+
42+/// Convert an `attractor_dot::AttributeValue` to a `serde_json::Value`.
43+fn attr_to_json(val: &attractor_dot::AttributeValue) -> serde_json::Value {
44+ match val {
45+ attractor_dot::AttributeValue::String(s) => serde_json::Value::String(s.clone()),
46+ attractor_dot::AttributeValue::Integer(i) => serde_json::json!(*i),
47+ attractor_dot::AttributeValue::Float(f) => serde_json::json!(*f),
48+ attractor_dot::AttributeValue::Boolean(b) => serde_json::Value::Bool(*b),
49+ attractor_dot::AttributeValue::Duration(d) => serde_json::json!(d.as_millis() as u64),
50+ }
51+}
52+
53+/// Map a `StageStatus` to the lowercase string used in edge conditions.
54+fn status_to_string(status: StageStatus) -> String {
55+ match status {
56+ StageStatus::Success => "success".to_string(),
57+ StageStatus::PartialSuccess => "partial_success".to_string(),
58+ StageStatus::Retry => "retry".to_string(),
59+ StageStatus::Fail => "fail".to_string(),
60+ StageStatus::Skipped => "skipped".to_string(),
61+ }
62+}
63+
64+// ---------------------------------------------------------------------------
65+// PipelineExecutor
66+// ---------------------------------------------------------------------------
67+
68+impl PipelineExecutor {
69+ /// Create an executor with the given handler registry.
70+ pub fn new(registry: HandlerRegistry) -> Self {
71+ Self { registry }
72+ }
73+
74+ /// Create an executor pre-loaded with the default built-in handlers.
75+ pub fn with_default_registry() -> Self {
76+ Self {
77+ registry: default_registry(),
78+ }
79+ }
80+
81+ /// Run the full 5-phase pipeline lifecycle on the given graph.
82+ pub async fn run(&self, graph: &PipelineGraph) -> Result<PipelineResult> {
83+ self.run_with_context(graph, Context::new()).await
84+ }
85+
86+ /// Run the pipeline with a pre-seeded context (e.g. workdir, dry_run).
87+ pub async fn run_with_context(
88+ &self,
89+ graph: &PipelineGraph,
90+ context: Context,
91+ ) -> Result<PipelineResult> {
92+ // Phase 2: Validate
93+ validate_or_raise(graph)?;
94+
95+ // Phase 3: Initialize (merge graph attrs into existing context)
96+ for (key, val) in &graph.attrs {
97+ context.set(key, attr_to_json(val)).await;
98+ }
99+ let mut completed_nodes: Vec<String> = Vec::new();
100+ let mut node_outcomes: HashMap<String, Outcome> = HashMap::new();
101+
102+ // Phase 4: Execute
103+ let start = graph.start_node().ok_or_else(|| {
104+ AttractorError::ValidationError("No start node found".into())
105+ })?;
106+ let mut current_node = start;
107+
108+ // Safety limits from context (set by CLI flags)
109+ let max_budget: f64 = context
110+ .get("max_budget_usd")
111+ .await
112+ .and_then(|v| v.as_f64())
113+ .unwrap_or(200.0);
114+ let max_steps: u64 = context
115+ .get("max_steps")
116+ .await
117+ .and_then(|v| v.as_u64())
118+ .unwrap_or(200);
119+ let mut total_cost: f64 = 0.0;
120+ let mut step_count: u64 = 0;
121+
122+ loop {
123+ // Check safety limits
124+ step_count += 1;
125+ if step_count > max_steps {
126+ tracing::error!(steps = step_count, max = max_steps, "Step limit exceeded");
127+ return Err(AttractorError::Other(format!(
128+ "Pipeline exceeded maximum step count ({max_steps}). Use --max-steps to increase."
129+ )));
130+ }
131+ if total_cost > max_budget {
132+ tracing::error!(cost = total_cost, max = max_budget, "Budget exceeded");
133+ return Err(AttractorError::Other(format!(
134+ "Pipeline exceeded budget (${:.2} > ${:.2}). Use --max-budget-usd to increase.",
135+ total_cost, max_budget
136+ )));
137+ }
138+
139+ // Terminal check (exit node)
140+ if current_node.shape == "Msquare" {
141+ // Check goal gates
142+ let gate_result = enforce_goal_gates(graph, &node_outcomes)?;
143+ if !gate_result.all_satisfied {
144+ if let Some(ref target) = gate_result.retry_target {
145+ current_node = graph.node(target).ok_or_else(|| {
146+ AttractorError::Other(format!(
147+ "Retry target '{}' not found",
148+ target
149+ ))
150+ })?;
151+ continue;
152+ }
153+ }
154+
155+ // Execute the exit handler
156+ let handler_type = self.registry.resolve_type(current_node);
157+ let handler = self.registry.get(&handler_type).ok_or_else(|| {
158+ AttractorError::HandlerError {
159+ handler: handler_type.clone(),
160+ node: current_node.id.clone(),
161+ message: format!("No handler registered for type '{}'", handler_type),
162+ }
163+ })?;
164+ let outcome = handler.execute(current_node, &context, graph).await?;
165+ completed_nodes.push(current_node.id.clone());
166+ node_outcomes.insert(current_node.id.clone(), outcome);
167+ break;
168+ }
169+
170+ // Execute handler
171+ let handler_type = self.registry.resolve_type(current_node);
172+ let handler = self.registry.get(&handler_type).ok_or_else(|| {
173+ AttractorError::HandlerError {
174+ handler: handler_type.clone(),
175+ node: current_node.id.clone(),
176+ message: format!("No handler registered for type '{}'", handler_type),
177+ }
178+ })?;
179+ let outcome = handler.execute(current_node, &context, graph).await?;
180+
181+ // Record
182+ completed_nodes.push(current_node.id.clone());
183+ node_outcomes.insert(current_node.id.clone(), outcome.clone());
184+
185+ // Track cost from this node
186+ if let Some(cost) = outcome.context_updates.get(&format!("{}.cost_usd", current_node.id)) {
187+ if let Some(c) = cost.as_f64() {
188+ total_cost += c;
189+ tracing::info!(
190+ node = %current_node.id,
191+ node_cost = c,
192+ total_cost = total_cost,
193+ budget_remaining = max_budget - total_cost,
194+ "Cost update"
195+ );
196+ }
197+ }
198+
199+ // Apply context updates
200+ context.apply_updates(outcome.context_updates.clone()).await;
201+ context
202+ .set(
203+ "outcome",
204+ serde_json::Value::String(status_to_string(outcome.status)),
205+ )
206+ .await;
207+ if let Some(ref label) = outcome.preferred_label {
208+ context
209+ .set(
210+ "preferred_label",
211+ serde_json::Value::String(label.clone()),
212+ )
213+ .await;
214+ }
215+
216+ // Select next edge โ€” resolve condition keys from outcome and context
217+ let ctx_snapshot = context.snapshot().await;
218+ let resolve = |key: &str| -> String {
219+ match key {
220+ "outcome" => status_to_string(outcome.status),
221+ "preferred_label" => outcome.preferred_label.clone().unwrap_or_default(),
222+ _ => ctx_snapshot
223+ .get(key)
224+ .and_then(|v| match v {
225+ serde_json::Value::String(s) => Some(s.clone()),
226+ serde_json::Value::Bool(b) => Some(b.to_string()),
227+ serde_json::Value::Number(n) => Some(n.to_string()),
228+ _ => Some(v.to_string()),
229+ })
230+ .unwrap_or_default(),
231+ }
232+ };
233+ let next_edge = select_edge(&current_node.id, &outcome, &resolve, graph);
234+
235+ match next_edge {
236+ Some(edge) => {
237+ // Handle loop_restart
238+ if edge.loop_restart {
239+ completed_nodes.clear();
240+ node_outcomes.clear();
241+ }
242+ let next_id = edge.to.clone();
243+ current_node = graph.node(&next_id).ok_or_else(|| {
244+ AttractorError::Other(format!("Edge target '{}' not found", next_id))
245+ })?;
246+ }
247+ None => {
248+ // No outgoing edge and not an exit node
249+ if outcome.status == StageStatus::Fail {
250+ return Err(AttractorError::HandlerError {
251+ handler: handler_type,
252+ node: current_node.id.clone(),
253+ message: "Handler failed with no outgoing edge".into(),
254+ });
255+ }
256+ break;
257+ }
258+ }
259+ }
260+
261+ // Phase 5: Finalize
262+ let final_context = context.snapshot().await;
263+ Ok(PipelineResult {
264+ completed_nodes,
265+ node_outcomes,
266+ final_context,
267+ })
268+ }
269+}
270+
271+// ---------------------------------------------------------------------------
272+// Tests
273+// ---------------------------------------------------------------------------
274+
275+#[cfg(test)]
276+mod tests {
277+ use super::*;
278+ use crate::graph::PipelineGraph;
279+ use crate::handler::{HandlerRegistry, NodeHandler, StartHandler, ExitHandler, ConditionalHandler};
280+ use async_trait::async_trait;
281+
282+ fn parse_graph(dot: &str) -> PipelineGraph {
283+ let parsed = attractor_dot::parse(dot).unwrap();
284+ PipelineGraph::from_dot(parsed).unwrap()
285+ }
286+
287+ /// A mock codergen handler that returns Success without shelling out to Claude CLI.
288+ struct MockCodergenHandler;
289+
290+ #[async_trait]
291+ impl NodeHandler for MockCodergenHandler {
292+ fn handler_type(&self) -> &str {
293+ "codergen"
294+ }
295+ async fn execute(
296+ &self,
297+ node: &crate::graph::PipelineNode,
298+ _ctx: &Context,
299+ _graph: &PipelineGraph,
300+ ) -> Result<Outcome> {
301+ let mut updates = HashMap::new();
302+ updates.insert(
303+ format!("{}.completed", node.id),
304+ serde_json::Value::Bool(true),
305+ );
306+ updates.insert(
307+ format!("{}.result", node.id),
308+ serde_json::Value::String("mock result".into()),
309+ );
310+ Ok(Outcome {
311+ status: StageStatus::Success,
312+ preferred_label: None,
313+ suggested_next_ids: vec![],
314+ context_updates: updates,
315+ notes: "mock codergen".into(),
316+ failure_reason: None,
317+ })
318+ }
319+ }
320+
321+ /// Build a test registry with mock codergen handler (no real CLI calls).
322+ fn test_registry() -> HandlerRegistry {
323+ let mut reg = HandlerRegistry::new();
324+ reg.register(StartHandler);
325+ reg.register(ExitHandler);
326+ reg.register(ConditionalHandler);
327+ reg.register(MockCodergenHandler);
328+ reg
329+ }
330+
331+ fn test_executor() -> PipelineExecutor {
332+ PipelineExecutor::new(test_registry())
333+ }
334+
335+ // Test 1: Linear pipeline (start -> A -> exit) completes successfully
336+ #[tokio::test]
337+ async fn linear_pipeline_completes() {
338+ let graph = parse_graph(
339+ r#"digraph G {
340+ start [shape="Mdiamond"]
341+ process [shape="box", label="Process", prompt="Do work"]
342+ done [shape="Msquare"]
343+ start -> process -> done
344+ }"#,
345+ );
346+ let executor = test_executor();
347+ let result = executor.run(&graph).await.unwrap();
348+
349+ assert_eq!(result.completed_nodes, vec!["start", "process", "done"]);
350+ assert!(result.node_outcomes.contains_key("start"));
351+ assert!(result.node_outcomes.contains_key("process"));
352+ assert!(result.node_outcomes.contains_key("done"));
353+ assert_eq!(
354+ result.node_outcomes["start"].status,
355+ StageStatus::Success
356+ );
357+ assert_eq!(
358+ result.node_outcomes["process"].status,
359+ StageStatus::Success
360+ );
361+ assert_eq!(
362+ result.node_outcomes["done"].status,
363+ StageStatus::Success
364+ );
365+ }
366+
367+ // Test 2: Branching pipeline routes based on conditions
368+ #[tokio::test]
369+ async fn branching_pipeline_routes_on_condition() {
370+ // The mock codergen handler returns Success, so outcome=success.
371+ // Edge to "yes_path" has condition="outcome=success", so it should be taken.
372+ let graph = parse_graph(
373+ r#"digraph G {
374+ start [shape="Mdiamond"]
375+ check [shape="box", label="Check", prompt="Check something"]
376+ yes_path [shape="box", label="Yes Path", prompt="Yes"]
377+ no_path [shape="box", label="No Path", prompt="No"]
378+ done [shape="Msquare"]
379+ start -> check
380+ check -> yes_path [condition="outcome=success"]
381+ check -> no_path [condition="outcome=fail"]
382+ yes_path -> done
383+ no_path -> done
384+ }"#,
385+ );
386+ let executor = test_executor();
387+ let result = executor.run(&graph).await.unwrap();
388+
389+ assert!(result.completed_nodes.contains(&"yes_path".to_string()));
390+ assert!(!result.completed_nodes.contains(&"no_path".to_string()));
391+ }
392+
393+ // Test 3: Pipeline with no start node returns error
394+ #[tokio::test]
395+ async fn no_start_node_returns_error() {
396+ let graph = parse_graph(
397+ r#"digraph G {
398+ process [shape="box", label="Do work"]
399+ done [shape="Msquare"]
400+ process -> done
401+ }"#,
402+ );
403+ let executor = test_executor();
404+ let result = executor.run(&graph).await;
405+
406+ assert!(result.is_err());
407+ let err = result.unwrap_err();
408+ match err {
409+ AttractorError::ValidationError(msg) => {
410+ assert!(
411+ msg.contains("start node"),
412+ "Expected error about start node, got: {msg}"
413+ );
414+ }
415+ other => panic!("Expected ValidationError, got: {other:?}"),
416+ }
417+ }
418+
419+ // Test 4: Context updates from one node visible to next (verify via final_context)
420+ #[tokio::test]
421+ async fn context_updates_propagate() {
422+ // The mock codergen handler sets context_updates with
423+ // "<node_id>.completed", "<node_id>.result", etc.
424+ let graph = parse_graph(
425+ r#"digraph G {
426+ start [shape="Mdiamond"]
427+ step [shape="box", label="Step", prompt="Generate code"]
428+ done [shape="Msquare"]
429+ start -> step -> done
430+ }"#,
431+ );
432+ let executor = test_executor();
433+ let result = executor.run(&graph).await.unwrap();
434+
435+ // The mock handler marks the node as completed
436+ assert_eq!(
437+ result.final_context.get("step.completed"),
438+ Some(&serde_json::Value::Bool(true)),
439+ );
440+ // The mock handler stores a result in "<node_id>.result"
441+ assert!(
442+ result.final_context.contains_key("step.result"),
443+ "Expected step.result in final context, keys: {:?}",
444+ result.final_context.keys().collect::<Vec<_>>()
445+ );
446+ // The engine also sets "outcome" in context
447+ assert_eq!(
448+ result.final_context.get("outcome"),
449+ Some(&serde_json::Value::String("success".into())),
450+ );
451+ }
452+
453+ // Test 5: Goal gate failure with retry target loops back
454+ #[tokio::test]
455+ async fn goal_gate_failure_with_retry_loops_back() {
456+ // The mock handler returns success, so goal gate is satisfied and no loop occurs.
457+ // Here we verify the goal gate path doesn't error when gates are satisfied.
458+ let graph = parse_graph(
459+ r#"digraph G {
460+ start [shape="Mdiamond"]
461+ review [shape="box", goal_gate=true, retry_target="start", label="Review", prompt="Review code"]
462+ done [shape="Msquare"]
463+ start -> review -> done
464+ }"#,
465+ );
466+ let executor = test_executor();
467+ let result = executor.run(&graph).await.unwrap();
468+
469+ // Goal gate is satisfied (mock returns success), so pipeline completes
470+ assert!(result.completed_nodes.contains(&"done".to_string()));
471+ }
472+
473+ // Test 6: Goal gate failure without retry target returns error
474+ #[tokio::test]
475+ async fn goal_gate_failure_without_retry_returns_error() {
476+ // To test this, we need a custom handler that returns Fail for the goal gate node.
477+ use async_trait::async_trait;
478+ use crate::handler::NodeHandler;
479+ use crate::graph::PipelineNode;
480+
481+ struct FailHandler;
482+
483+ #[async_trait]
484+ impl NodeHandler for FailHandler {
485+ fn handler_type(&self) -> &str {
486+ "codergen"
487+ }
488+ async fn execute(
489+ &self,
490+ _node: &PipelineNode,
491+ _ctx: &Context,
492+ _graph: &PipelineGraph,
493+ ) -> Result<Outcome> {
494+ Ok(Outcome::fail("intentional failure"))
495+ }
496+ }
497+
498+ let graph = parse_graph(
499+ r#"digraph G {
500+ start [shape="Mdiamond"]
501+ review [shape="box", goal_gate=true, label="Review", prompt="Review"]
502+ done [shape="Msquare"]
503+ start -> review -> done
504+ }"#,
505+ );
506+
507+ let mut registry = HandlerRegistry::new();
508+ registry.register(crate::handler::StartHandler);
509+ registry.register(crate::handler::ExitHandler);
510+ registry.register(crate::handler::ConditionalHandler);
511+ registry.register(FailHandler);
512+
513+ let executor = PipelineExecutor::new(registry);
514+ let result = executor.run(&graph).await;
515+
516+ assert!(result.is_err());
517+ let err = result.unwrap_err();
518+ match err {
519+ AttractorError::GoalGateUnsatisfied { node } => {
520+ assert_eq!(node, "review");
521+ }
522+ other => panic!("Expected GoalGateUnsatisfied, got: {other:?}"),
523+ }
524+ }
525+
526+ // Test 7: Goal gate failure with retry target retries correctly
527+ #[tokio::test]
528+ async fn goal_gate_failure_with_retry_target_retries() {
529+ use async_trait::async_trait;
530+ use crate::handler::NodeHandler;
531+ use crate::graph::PipelineNode;
532+ use std::sync::atomic::{AtomicUsize, Ordering};
533+ use std::sync::Arc;
534+
535+ // Handler that fails on first call, succeeds on subsequent calls
536+ struct RetryableHandler {
537+ call_count: Arc<AtomicUsize>,
538+ }
539+
540+ #[async_trait]
541+ impl NodeHandler for RetryableHandler {
542+ fn handler_type(&self) -> &str {
543+ "codergen"
544+ }
545+ async fn execute(
546+ &self,
547+ _node: &PipelineNode,
548+ _ctx: &Context,
549+ _graph: &PipelineGraph,
550+ ) -> Result<Outcome> {
551+ let count = self.call_count.fetch_add(1, Ordering::SeqCst);
552+ if count == 0 {
553+ Ok(Outcome::fail("first attempt fails"))
554+ } else {
555+ Ok(Outcome::success("retry succeeded"))
556+ }
557+ }
558+ }
559+
560+ let graph = parse_graph(
561+ r#"digraph G {
562+ start [shape="Mdiamond"]
563+ review [shape="box", goal_gate=true, retry_target="start", label="Review", prompt="Review"]
564+ done [shape="Msquare"]
565+ start -> review -> done
566+ }"#,
567+ );
568+
569+ let call_count = Arc::new(AtomicUsize::new(0));
570+ let mut registry = HandlerRegistry::new();
571+ registry.register(crate::handler::StartHandler);
572+ registry.register(crate::handler::ExitHandler);
573+ registry.register(crate::handler::ConditionalHandler);
574+ registry.register(RetryableHandler {
575+ call_count: call_count.clone(),
576+ });
577+
578+ let executor = PipelineExecutor::new(registry);
579+ let result = executor.run(&graph).await.unwrap();
580+
581+ // Should have retried: start -> review(fail) -> exit(goal gate fails, retry to start)
582+ // -> start -> review(success) -> exit(done)
583+ assert!(result.completed_nodes.contains(&"done".to_string()));
584+ // The handler was called twice (once fail, once success)
585+ assert_eq!(call_count.load(Ordering::SeqCst), 2);
586+ }
587+
588+ // Test 8a: Context-based edge conditions are resolved from pipeline context
589+ #[tokio::test]
590+ async fn context_based_conditions_resolve_from_context() {
591+ // A handler that sets a context key and succeeds
592+ struct ContextSettingHandler;
593+
594+ #[async_trait]
595+ impl NodeHandler for ContextSettingHandler {
596+ fn handler_type(&self) -> &str {
597+ "codergen"
598+ }
599+ async fn execute(
600+ &self,
601+ node: &crate::graph::PipelineNode,
602+ _ctx: &Context,
603+ _graph: &PipelineGraph,
604+ ) -> Result<Outcome> {
605+ let mut updates = HashMap::new();
606+ updates.insert(
607+ format!("{}.completed", node.id),
608+ serde_json::Value::Bool(true),
609+ );
610+ updates.insert(
611+ "deploy_env".to_string(),
612+ serde_json::Value::String("prod".to_string()),
613+ );
614+ Ok(Outcome {
615+ status: StageStatus::Success,
616+ preferred_label: None,
617+ suggested_next_ids: vec![],
618+ context_updates: updates,
619+ notes: "set context".into(),
620+ failure_reason: None,
621+ })
622+ }
623+ }
624+
625+ let graph = parse_graph(
626+ r#"digraph G {
627+ start [shape="Mdiamond"]
628+ setup [shape="box", label="Setup", prompt="setup"]
629+ prod_path [shape="box", label="Prod", prompt="prod"]
630+ dev_path [shape="box", label="Dev", prompt="dev"]
631+ done [shape="Msquare"]
632+ start -> setup
633+ setup -> prod_path [condition="deploy_env=prod"]
634+ setup -> dev_path [condition="deploy_env=dev"]
635+ prod_path -> done
636+ dev_path -> done
637+ }"#,
638+ );
639+
640+ let mut registry = HandlerRegistry::new();
641+ registry.register(StartHandler);
642+ registry.register(ExitHandler);
643+ registry.register(ConditionalHandler);
644+ registry.register(ContextSettingHandler);
645+
646+ let executor = PipelineExecutor::new(registry);
647+ let result = executor.run(&graph).await.unwrap();
648+
649+ // The condition "deploy_env=prod" should route to prod_path
650+ assert!(
651+ result.completed_nodes.contains(&"prod_path".to_string()),
652+ "Expected prod_path in completed nodes, got: {:?}",
653+ result.completed_nodes
654+ );
655+ assert!(
656+ !result.completed_nodes.contains(&"dev_path".to_string()),
657+ "dev_path should not be in completed nodes"
658+ );
659+ }
660+
661+ // Test 8: PipelineExecutor::new and with_default_registry
662+ #[test]
663+ fn executor_constructors() {
664+ let executor = PipelineExecutor::with_default_registry();
665+ assert!(executor.registry.has("start"));
666+ assert!(executor.registry.has("exit"));
667+ assert!(executor.registry.has("codergen"));
668+
669+ let custom = PipelineExecutor::new(HandlerRegistry::new());
670+ assert!(!custom.registry.has("start"));
671+ }
672+
673+ // Test 9: Step limit aborts runaway pipelines
674+ #[tokio::test]
675+ async fn step_limit_aborts_pipeline() {
676+ // A pipeline with a loop that never exits will hit the step limit.
677+ let graph = parse_graph(
678+ r#"digraph G {
679+ start [shape="Mdiamond"]
680+ loop_node [shape="box", label="Loop", prompt="loop"]
681+ done [shape="Msquare"]
682+ start -> loop_node
683+ loop_node -> loop_node [condition="outcome=success"]
684+ loop_node -> done [condition="outcome=fail"]
685+ }"#,
686+ );
687+ let executor = test_executor();
688+ let context = Context::new();
689+ context.set("max_steps", serde_json::json!(5)).await;
690+
691+ let result = executor.run_with_context(&graph, context).await;
692+ assert!(result.is_err());
693+ let err = result.unwrap_err().to_string();
694+ assert!(
695+ err.contains("maximum step count"),
696+ "Expected step limit error, got: {err}"
697+ );
698+ }
699+
700+ // Test 10: Budget limit aborts pipeline when cost exceeds cap
701+ #[tokio::test]
702+ async fn budget_limit_aborts_pipeline() {
703+ use crate::graph::PipelineNode;
704+
705+ /// Handler that reports a cost in its context_updates.
706+ struct CostlyHandler;
707+
708+ #[async_trait::async_trait]
709+ impl NodeHandler for CostlyHandler {
710+ fn handler_type(&self) -> &str {
711+ "codergen"
712+ }
713+ async fn execute(
714+ &self,
715+ node: &PipelineNode,
716+ _ctx: &Context,
717+ _graph: &PipelineGraph,
718+ ) -> Result<Outcome> {
719+ let mut updates = HashMap::new();
720+ updates.insert(
721+ format!("{}.completed", node.id),
722+ serde_json::Value::Bool(true),
723+ );
724+ updates.insert(
725+ format!("{}.cost_usd", node.id),
726+ serde_json::json!(1.50),
727+ );
728+ Ok(Outcome {
729+ status: StageStatus::Success,
730+ preferred_label: None,
731+ suggested_next_ids: vec![],
732+ context_updates: updates,
733+ notes: "costly operation".into(),
734+ failure_reason: None,
735+ })
736+ }
737+ }
738+
739+ let graph = parse_graph(
740+ r#"digraph G {
741+ start [shape="Mdiamond"]
742+ step1 [shape="box", label="Step1", prompt="work"]
743+ step2 [shape="box", label="Step2", prompt="work"]
744+ done [shape="Msquare"]
745+ start -> step1 -> step2 -> done
746+ }"#,
747+ );
748+
749+ let mut registry = HandlerRegistry::new();
750+ registry.register(StartHandler);
751+ registry.register(ExitHandler);
752+ registry.register(ConditionalHandler);
753+ registry.register(CostlyHandler);
754+
755+ let executor = PipelineExecutor::new(registry);
756+ let context = Context::new();
757+ // Budget of $2.00, but two nodes cost $1.50 each = $3.00 total
758+ context.set("max_budget_usd", serde_json::json!(2.0)).await;
759+
760+ let result = executor.run_with_context(&graph, context).await;
761+ assert!(result.is_err());
762+ let err = result.unwrap_err().to_string();
763+ assert!(
764+ err.contains("exceeded budget"),
765+ "Expected budget error, got: {err}"
766+ );
767+ }
768+}