From 0a956beec757c4b6e8e0c9b1bc511bf8ed455891 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 10 Oct 2026 11:04:02 -0500 Subject: [PATCH 1/5] feat(orchestration): dependency-aware task workflow DAG (#39) Typed TaskId, validated WorkflowSpec (cycles, unknown/duplicate edges), bounded-parallel executor, dependency failure propagation reusing #38 FailureRecord, deterministic workflow events. Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- src/events/event.rs | 46 ++ src/lib.rs | 4 + src/orchestration/mod.rs | 1 + src/orchestration/workflow.rs | 961 ++++++++++++++++++++++++++++++++++ 4 files changed, 1012 insertions(+) create mode 100644 src/orchestration/workflow.rs diff --git a/src/events/event.rs b/src/events/event.rs index 301ae2d..9862e74 100644 --- a/src/events/event.rs +++ b/src/events/event.rs @@ -36,6 +36,52 @@ pub enum AegisEvent { failure: crate::failure::FailureRecord, }, + /// Workflow (task DAG) transitions. `workflow_seq` is assigned under one + /// lock at transition time, so sorting by it replays the exact order. + WorkflowTaskReady { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskStarted { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskCompleted { + run_id: String, + workflow_seq: u64, + task_id: String, + result_digest: String, + }, + WorkflowTaskWaiting { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskFailed { + run_id: String, + workflow_seq: u64, + task_id: String, + failure: crate::failure::FailureRecord, + }, + WorkflowTaskCancelled { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskSkipped { + run_id: String, + workflow_seq: u64, + task_id: String, + prerequisite: String, + }, + WorkflowFinished { + run_id: String, + workflow_seq: u64, + status: String, + }, + AssistantDelta { text: String, }, diff --git a/src/lib.rs b/src/lib.rs index 3b723e2..fba5b92 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,10 @@ pub use inference::{ ProtocolInferenceBackend, ToolCallFunction, ToolCallItem, }; pub use mojo_bridge::MojoSimdBridge; +pub use orchestration::workflow::{ + TaskId, TaskOutcome, TaskRunner, TaskState, WorkflowConfig, WorkflowError, WorkflowExecutor, + WorkflowReport, WorkflowSpec, WorkflowStatus, +}; pub use orchestration::{Run, RunBudget, RunState, TerminationReason, Trigger}; pub use persistence::{ AsyncDatabase, CrumbRecord, Database, PersistenceError, SqliteActionStore, SqliteApprovalStore, diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs index 9979a63..47d90e2 100644 --- a/src/orchestration/mod.rs +++ b/src/orchestration/mod.rs @@ -2,6 +2,7 @@ pub mod budget; pub mod run; pub mod termination; pub mod trigger; +pub mod workflow; pub use budget::RunBudget; pub use run::{Run, RunState}; diff --git a/src/orchestration/workflow.rs b/src/orchestration/workflow.rs new file mode 100644 index 0000000..f57223b --- /dev/null +++ b/src/orchestration/workflow.rs @@ -0,0 +1,961 @@ +//! Dependency-aware task workflow (DAG) for multi-step agent work (issue #39). +//! +//! This layer sits above the single-run lifecycle in `orchestration::run` and +//! far above AIEN inference scheduling. It decides only WHEN a caller-supplied +//! task may start. It authorizes nothing, caches no decision, retries nothing +//! and never schedules inference: every real effect happens inside the task +//! body through the existing gated paths. State is in memory only and does not +//! survive a restart (see `docs/WORKFLOW-DAG.md`). + +use crate::events::{AegisEvent, EventBus, EventEnvelope}; +use crate::failure::{ + now_millis, payload_digest, CancelToken, EffectCertainty, FailureClass, FailureRecord, + ToolFault, +}; +use crate::sessions::id::{RunId, SessionId}; +use async_trait::async_trait; +use futures_util::future::BoxFuture; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Semaphore; +use tokio::task::JoinSet; + +/// Tool name stamped on failure records produced by the DAG itself. +pub const WORKFLOW_TOOL_NAME: &str = "workflow_task"; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct TaskId(String); + +impl TaskId { + pub fn new(id: impl Into) -> Self { + Self(id.into()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for TaskId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl From<&str> for TaskId { + fn from(s: &str) -> Self { + Self::new(s) + } +} + +/// Build-time errors. A spec that builds is a valid DAG. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WorkflowError { + EmptyTaskId, + DuplicateTask(TaskId), + UnknownPredecessor { + task: TaskId, + predecessor: TaskId, + }, + DuplicateEdge { + task: TaskId, + predecessor: TaskId, + }, + SelfDependency(TaskId), + /// One cycle, listed in dependency order. + Cycle(Vec), + InvalidConfig(String), +} + +impl fmt::Display for WorkflowError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyTaskId => write!(f, "task id must not be empty"), + Self::DuplicateTask(t) => write!(f, "duplicate task id: {t}"), + Self::UnknownPredecessor { task, predecessor } => { + write!(f, "task {task} depends on unknown task {predecessor}") + } + Self::DuplicateEdge { task, predecessor } => { + write!(f, "task {task} lists predecessor {predecessor} twice") + } + Self::SelfDependency(t) => write!(f, "task {t} depends on itself"), + Self::Cycle(c) => { + let names: Vec<&str> = c.iter().map(|t| t.as_str()).collect(); + write!(f, "dependency cycle: {}", names.join(" -> ")) + } + Self::InvalidConfig(m) => write!(f, "invalid workflow config: {m}"), + } + } +} + +impl std::error::Error for WorkflowError {} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", content = "detail", rename_all = "snake_case")] +pub enum TaskState { + Pending, + Ready, + Running, + WaitingForApproval, + Completed, + Failed(FailureRecord), + Cancelled, + Skipped { prerequisite: TaskId }, +} + +impl TaskState { + /// Terminal means the task will never change state again. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Completed | Self::Failed(_) | Self::Cancelled | Self::Skipped { .. } + ) + } + + /// Short stable name, used in events. + pub fn name(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Ready => "ready", + Self::Running => "running", + Self::WaitingForApproval => "waiting_for_approval", + Self::Completed => "completed", + Self::Failed(_) => "failed", + Self::Cancelled => "cancelled", + Self::Skipped { .. } => "skipped", + } + } +} + +/// What a task body reports. Approval pending is not success. +#[derive(Debug, Clone)] +pub enum TaskOutcome { + Completed(serde_json::Value), + Failed(ToolFault), + ApprovalPending, + Cancelled, +} + +/// Handed to the task body when it starts. +#[derive(Clone)] +pub struct TaskContext { + pub task_id: TaskId, + pub run_id: RunId, + pub session_id: SessionId, + /// Fires when the workflow is cancelled or its total budget is spent. + pub cancel: CancelToken, +} + +/// Caller-supplied task body. It must route every real effect through the +/// existing gate path; the DAG never authorizes on its behalf. +#[async_trait] +pub trait TaskRunner: Send + Sync { + async fn run(&self, ctx: TaskContext) -> TaskOutcome; + + /// Certainty recorded when the DAG interrupts this task (timeout or + /// cancellation) before it reports. Default is the safe answer. + fn certainty_on_interrupt(&self) -> EffectCertainty { + EffectCertainty::Uncertain + } +} + +/// Wraps an async closure as a `TaskRunner`. +pub struct FnRunner { + f: F, + interrupt: EffectCertainty, +} + +pub fn runner_fn(f: F) -> Arc +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + Arc::new(FnRunner { + f, + interrupt: EffectCertainty::Uncertain, + }) +} + +/// Like `runner_fn` with an explicit certainty for interruptions. +pub fn runner_fn_with_certainty(f: F, interrupt: EffectCertainty) -> Arc +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + Arc::new(FnRunner { f, interrupt }) +} + +#[async_trait] +impl TaskRunner for FnRunner +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + async fn run(&self, ctx: TaskContext) -> TaskOutcome { + (self.f)(ctx).await + } + + fn certainty_on_interrupt(&self) -> EffectCertainty { + self.interrupt + } +} + +struct TaskNode { + id: TaskId, + deps: Vec, + runner: Arc, +} + +/// A validated DAG. Insertion order is the deterministic tie break. +pub struct WorkflowSpec { + tasks: Vec, +} + +impl WorkflowSpec { + pub fn builder() -> WorkflowBuilder { + WorkflowBuilder::default() + } + + pub fn task_ids(&self) -> Vec { + self.tasks.iter().map(|t| t.id.clone()).collect() + } + + pub fn len(&self) -> usize { + self.tasks.len() + } + + pub fn is_empty(&self) -> bool { + self.tasks.is_empty() + } +} + +#[derive(Default)] +pub struct WorkflowBuilder { + tasks: Vec, +} + +impl WorkflowBuilder { + /// Predecessors must already be added, which also makes forward edges + /// (and so most cycles) impossible; `build` still checks the whole graph. + pub fn add_task( + mut self, + id: impl Into, + deps: &[&str], + runner: Arc, + ) -> Result { + let id = id.into(); + if id.as_str().is_empty() { + return Err(WorkflowError::EmptyTaskId); + } + if self.tasks.iter().any(|t| t.id == id) { + return Err(WorkflowError::DuplicateTask(id)); + } + let mut seen: HashSet<&str> = HashSet::new(); + let mut deps_out = Vec::with_capacity(deps.len()); + for d in deps { + if *d == id.as_str() { + return Err(WorkflowError::SelfDependency(id)); + } + if !seen.insert(d) { + return Err(WorkflowError::DuplicateEdge { + task: id, + predecessor: TaskId::new(*d), + }); + } + deps_out.push(TaskId::new(*d)); + } + self.tasks.push(TaskNode { + id, + deps: deps_out, + runner, + }); + Ok(self) + } + + /// Validates predecessors and rejects cycles. Predecessors may be added + /// after their dependents, so this is where unknown ids and cycles surface. + pub fn build(self) -> Result { + let index: HashMap<&TaskId, usize> = self + .tasks + .iter() + .enumerate() + .map(|(i, t)| (&t.id, i)) + .collect(); + for t in &self.tasks { + for d in &t.deps { + if !index.contains_key(d) { + return Err(WorkflowError::UnknownPredecessor { + task: t.id.clone(), + predecessor: d.clone(), + }); + } + } + } + // Kahn: whatever cannot be peeled off sits on or behind a cycle. + let mut indegree: Vec = self.tasks.iter().map(|t| t.deps.len()).collect(); + let mut queue: Vec = (0..self.tasks.len()) + .filter(|i| indegree[*i] == 0) + .collect(); + let mut peeled = 0; + while let Some(n) = queue.pop() { + peeled += 1; + for (i, t) in self.tasks.iter().enumerate() { + if t.deps.contains(&self.tasks[n].id) { + indegree[i] -= 1; + if indegree[i] == 0 { + queue.push(i); + } + } + } + } + if peeled != self.tasks.len() { + return Err(WorkflowError::Cycle(find_cycle( + &self.tasks, + &index, + &indegree, + ))); + } + Ok(WorkflowSpec { tasks: self.tasks }) + } +} + +/// Walks predecessor links among the unpeeled nodes until one repeats. +fn find_cycle( + tasks: &[TaskNode], + index: &HashMap<&TaskId, usize>, + indegree: &[usize], +) -> Vec { + let start = (0..tasks.len()).find(|i| indegree[*i] > 0).unwrap_or(0); + let mut path: Vec = vec![start]; + let mut cur = start; + loop { + let next = tasks[cur] + .deps + .iter() + .map(|d| index[d]) + .find(|i| indegree[*i] > 0) + .unwrap_or(start); + if let Some(pos) = path.iter().position(|p| *p == next) { + let mut cycle: Vec = path[pos..].iter().map(|i| tasks[*i].id.clone()).collect(); + cycle.reverse(); + return cycle; + } + path.push(next); + cur = next; + } +} + +#[derive(Debug, Clone)] +pub struct WorkflowConfig { + pub run_id: RunId, + pub session_id: SessionId, + /// Upper bound on tasks running at once. Must be at least 1. + pub max_parallel: usize, + pub per_task_timeout: Option, + /// Wall-clock cap for the whole workflow. When it elapses the workflow is + /// cancelled like an operator cancel and `budget_exhausted` is set. + pub total_budget: Option, +} + +impl WorkflowConfig { + pub fn new(run_id: RunId, session_id: SessionId, max_parallel: usize) -> Self { + Self { + run_id, + session_id, + max_parallel, + per_task_timeout: None, + total_budget: None, + } + } +} + +/// Digest of a completed task's result. The value itself is not kept here. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResultHandle { + pub digest: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkflowStatus { + /// Every task completed. + Completed, + /// Some task failed, was skipped or cancelled, and nothing waits on a human. + Failed, + /// Cancelled (operator or budget). + Cancelled, + /// At least one task waits for approval; the workflow is not finished. + WaitingForApproval, +} + +/// One transition, in workflow order. `seq` starts at 1. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkflowEvent { + pub seq: u64, + pub task_id: Option, + pub state: String, +} + +/// Serializable view of the in-memory workflow state. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkflowSnapshot { + pub run_id: String, + pub last_seq: u64, + pub states: BTreeMap, + pub results: BTreeMap, +} + +#[derive(Debug, Clone)] +pub struct WorkflowReport { + pub status: WorkflowStatus, + pub snapshot: WorkflowSnapshot, + /// Failure records for Failed, Skipped and Cancelled tasks. + pub failures: BTreeMap, + /// Tasks left non-terminal (waiting for approval, or blocked behind one). + pub unfinished: Vec, + pub events: Vec, + pub peak_concurrency: usize, + pub budget_exhausted: bool, +} + +struct Ledger { + seq: u64, + states: BTreeMap, + results: BTreeMap, + failures: BTreeMap, + events: Vec, +} + +/// The one place a state change is recorded. The sequence number is assigned +/// under the lock together with the state change, so replay order equals +/// transition order. +struct Recorder { + ledger: Mutex, + bus: Option, + run_id: RunId, + session_id: SessionId, +} + +impl Recorder { + fn transition(&self, id: &TaskId, state: TaskState, result: Option) -> u64 { + let mut l = self.ledger.lock(); + l.seq += 1; + let seq = l.seq; + let name = state.name(); + let event = self.event_for(seq, id, &state, result.as_ref()); + if let Some(r) = result { + l.results.insert(id.clone(), r); + } + l.states.insert(id.clone(), state); + l.events.push(WorkflowEvent { + seq, + task_id: Some(id.clone()), + state: name.to_string(), + }); + // Publish while holding the lock so bus order equals sequence order. + self.publish(event, seq); + seq + } + + fn finish(&self, status: WorkflowStatus) { + let mut l = self.ledger.lock(); + l.seq += 1; + let seq = l.seq; + l.events.push(WorkflowEvent { + seq, + task_id: None, + state: "finished".to_string(), + }); + let event = AegisEvent::WorkflowFinished { + run_id: self.run_id.to_string(), + workflow_seq: seq, + status: format!("{status:?}").to_lowercase(), + }; + self.publish(event, seq); + } + + fn note_failure(&self, id: &TaskId, rec: FailureRecord) { + self.ledger.lock().failures.insert(id.clone(), rec); + } + + fn state_of(&self, id: &TaskId) -> TaskState { + self.ledger.lock().states[id].clone() + } + + fn next_failure_seq(&self) -> u64 { + // Failure records share the workflow sequence space; the number is + // only a stable order key, so the next transition's number is used. + self.ledger.lock().seq + 1 + } + + fn publish(&self, event: AegisEvent, seq: u64) { + if let Some(bus) = &self.bus { + let env = EventEnvelope::new( + event, + Some(self.session_id.to_string()), + Some(self.run_id.to_string()), + seq, + ); + // No subscriber is not an error for the workflow. + let _ = bus.publish(env); + } + } + + fn event_for( + &self, + seq: u64, + id: &TaskId, + state: &TaskState, + result: Option<&ResultHandle>, + ) -> AegisEvent { + let run_id = self.run_id.to_string(); + let task_id = id.to_string(); + match state { + TaskState::Pending => AegisEvent::WorkflowTaskReady { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Ready => AegisEvent::WorkflowTaskReady { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Running => AegisEvent::WorkflowTaskStarted { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Completed => AegisEvent::WorkflowTaskCompleted { + run_id, + workflow_seq: seq, + task_id, + result_digest: result.map(|r| r.digest.clone()).unwrap_or_default(), + }, + TaskState::WaitingForApproval => AegisEvent::WorkflowTaskWaiting { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Failed(rec) => AegisEvent::WorkflowTaskFailed { + run_id, + workflow_seq: seq, + task_id, + failure: rec.clone(), + }, + TaskState::Cancelled => AegisEvent::WorkflowTaskCancelled { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Skipped { prerequisite } => AegisEvent::WorkflowTaskSkipped { + run_id, + workflow_seq: seq, + task_id, + prerequisite: prerequisite.to_string(), + }, + } + } +} + +enum Finish { + Outcome(TaskOutcome), + TimedOut, + Interrupted, +} + +pub struct WorkflowExecutor { + config: WorkflowConfig, + bus: Option, + cancel: CancelToken, +} + +impl WorkflowExecutor { + pub fn new(config: WorkflowConfig) -> Result { + if config.max_parallel == 0 { + return Err(WorkflowError::InvalidConfig( + "max_parallel must be at least 1".into(), + )); + } + Ok(Self { + config, + bus: None, + cancel: CancelToken::new(), + }) + } + + pub fn with_event_bus(mut self, bus: EventBus) -> Self { + self.bus = Some(bus); + self + } + + pub fn with_cancel_token(mut self, cancel: CancelToken) -> Self { + self.cancel = cancel; + self + } + + fn failure( + &self, + rec: &Recorder, + id: &TaskId, + class: FailureClass, + certainty: EffectCertainty, + message: &str, + ) -> FailureRecord { + let now = now_millis(); + FailureRecord::new( + rec.next_failure_seq(), + self.config.run_id.to_string(), + 0, + id.to_string(), + None, + WORKFLOW_TOOL_NAME, + 1, + class, + certainty, + now, + now, + ) + .with_cause("workflow", message, None) + } + + /// Runs the DAG to quiescence. Never blocks a worker thread: the + /// coordinator awaits, and task bodies run on spawned tasks. + pub async fn run(&self, spec: WorkflowSpec) -> WorkflowReport { + let ids = spec.task_ids(); + let rec = Recorder { + ledger: Mutex::new(Ledger { + seq: 0, + states: ids + .iter() + .map(|i| (i.clone(), TaskState::Pending)) + .collect(), + results: BTreeMap::new(), + failures: BTreeMap::new(), + events: Vec::new(), + }), + bus: self.bus.clone(), + run_id: self.config.run_id.clone(), + session_id: self.config.session_id.clone(), + }; + let nodes: HashMap = + spec.tasks.iter().map(|t| (t.id.clone(), t)).collect(); + let permits = Arc::new(Semaphore::new(self.config.max_parallel)); + let mut running: JoinSet<(TaskId, Finish)> = JoinSet::new(); + let mut by_join_id: HashMap = HashMap::new(); + let mut live = 0usize; + let mut peak = 0usize; + let mut cancel_seen = false; + let mut budget_exhausted = false; + let deadline = self + .config + .total_budget + .map(|d| tokio::time::Instant::now() + d); + + loop { + if !cancel_seen && self.cancel.is_cancelled() { + cancel_seen = true; + for id in &ids { + if matches!(rec.state_of(id), TaskState::Pending | TaskState::Ready) { + let f = self.failure( + &rec, + id, + FailureClass::Cancelled, + EffectCertainty::NoEffect, + "workflow cancelled before start", + ); + rec.note_failure(id, f); + rec.transition(id, TaskState::Cancelled, None); + } + } + } + + if !cancel_seen { + self.propagate(&ids, &nodes, &rec); + // Start ready tasks in insertion order while permits last. + for id in &ids { + if rec.state_of(id) != TaskState::Ready { + continue; + } + let Ok(permit) = permits.clone().try_acquire_owned() else { + break; + }; + rec.transition(id, TaskState::Running, None); + live += 1; + peak = peak.max(self.config.max_parallel - permits.available_permits()); + let node = nodes[id]; + let runner = node.runner.clone(); + let ctx = TaskContext { + task_id: id.clone(), + run_id: self.config.run_id.clone(), + session_id: self.config.session_id.clone(), + cancel: self.cancel.clone(), + }; + let cancel = self.cancel.clone(); + let timeout = self.config.per_task_timeout; + let tid = id.clone(); + let handle = running.spawn(async move { + let _permit = permit; + let body = runner.run(ctx); + let finish = tokio::select! { + biased; + _ = cancel.cancelled() => Finish::Interrupted, + f = async { + match timeout { + Some(d) => match tokio::time::timeout(d, body).await { + Ok(o) => Finish::Outcome(o), + Err(_) => Finish::TimedOut, + }, + None => Finish::Outcome(body.await), + } + } => f, + }; + (tid, finish) + }); + by_join_id.insert(handle.id(), id.clone()); + } + } + + if live == 0 { + break; + } + + let joined = tokio::select! { + j = running.join_next_with_id() => j, + _ = async { + match deadline { + Some(d) => tokio::time::sleep_until(d).await, + None => std::future::pending().await, + } + }, if !budget_exhausted => { + budget_exhausted = true; + self.cancel.cancel(); + continue; + } + }; + let Some(joined) = joined else { break }; + live -= 1; + let (jid, result) = match joined { + Ok((jid, r)) => (jid, Ok(r)), + Err(e) => (e.id(), Err(e)), + }; + let tid = by_join_id.remove(&jid).expect("tracked join id"); + let runner = nodes[&tid].runner.clone(); + let interrupt = runner.certainty_on_interrupt(); + let finish = match result { + Ok((_, f)) => f, + Err(_) => { + // A panicking body: the effect may have happened. + let f = self.failure( + &rec, + &tid, + FailureClass::Failed, + EffectCertainty::Uncertain, + "task body panicked", + ); + rec.note_failure(&tid, f.clone()); + rec.transition(&tid, TaskState::Failed(f), None); + continue; + } + }; + self.settle(&rec, &tid, finish, interrupt); + } + + self.report(rec, ids, peak, budget_exhausted, cancel_seen) + } + + /// Unblocks dependents whose prerequisites all completed, and skips + /// dependents of any prerequisite that ended without success. A task that + /// waits for approval is not terminal, so its dependents stay Pending. + fn propagate(&self, ids: &[TaskId], nodes: &HashMap, rec: &Recorder) { + loop { + let mut changed = false; + for id in ids { + if rec.state_of(id) != TaskState::Pending { + continue; + } + let deps = &nodes[id].deps; + let bad = deps.iter().find(|d| { + matches!( + rec.state_of(d), + TaskState::Failed(_) | TaskState::Cancelled | TaskState::Skipped { .. } + ) + }); + if let Some(bad) = bad { + let f = self.failure( + rec, + id, + FailureClass::Rejected, + EffectCertainty::NoEffect, + &format!("prerequisite failed: {bad}"), + ); + rec.note_failure(id, f); + rec.transition( + id, + TaskState::Skipped { + prerequisite: bad.clone(), + }, + None, + ); + changed = true; + } else if deps.iter().all(|d| rec.state_of(d) == TaskState::Completed) { + rec.transition(id, TaskState::Ready, None); + changed = true; + } + } + if !changed { + break; + } + } + } + + fn settle(&self, rec: &Recorder, id: &TaskId, finish: Finish, interrupt: EffectCertainty) { + match finish { + Finish::Outcome(TaskOutcome::Completed(v)) => { + let handle = ResultHandle { + digest: payload_digest(&v), + }; + rec.transition(id, TaskState::Completed, Some(handle)); + } + Finish::Outcome(TaskOutcome::Failed(fault)) => { + let f = self.failure(rec, id, fault.class, fault.certainty, &fault.message); + rec.note_failure(id, f.clone()); + rec.transition(id, TaskState::Failed(f), None); + } + Finish::Outcome(TaskOutcome::ApprovalPending) => { + rec.transition(id, TaskState::WaitingForApproval, None); + } + Finish::Outcome(TaskOutcome::Cancelled) | Finish::Interrupted => { + let f = self.failure( + rec, + id, + FailureClass::Cancelled, + interrupt, + "task cancelled while running", + ); + rec.note_failure(id, f); + rec.transition(id, TaskState::Cancelled, None); + } + Finish::TimedOut => { + let f = self.failure( + rec, + id, + FailureClass::Timeout, + interrupt, + "per-task timeout elapsed", + ); + rec.note_failure(id, f.clone()); + rec.transition(id, TaskState::Failed(f), None); + } + } + } + + fn report( + &self, + rec: Recorder, + ids: Vec, + peak: usize, + budget_exhausted: bool, + cancelled: bool, + ) -> WorkflowReport { + let (unfinished, any_waiting, all_done) = { + let l = rec.ledger.lock(); + let unfinished: Vec = ids + .iter() + .filter(|i| !l.states[*i].is_terminal()) + .cloned() + .collect(); + let any_waiting = l + .states + .values() + .any(|s| matches!(s, TaskState::WaitingForApproval)); + let all_done = l.states.values().all(|s| matches!(s, TaskState::Completed)); + (unfinished, any_waiting, all_done) + }; + let status = if cancelled { + WorkflowStatus::Cancelled + } else if any_waiting { + WorkflowStatus::WaitingForApproval + } else if all_done { + WorkflowStatus::Completed + } else { + WorkflowStatus::Failed + }; + rec.finish(status); + let l = rec.ledger.lock(); + WorkflowReport { + status, + snapshot: WorkflowSnapshot { + run_id: self.config.run_id.to_string(), + last_seq: l.seq, + states: l.states.clone(), + results: l.results.clone(), + }, + failures: l.failures.clone(), + unfinished, + events: l.events.clone(), + peak_concurrency: peak, + budget_exhausted, + } + } +} + +/// Maps a finished `AgentEngine::execute_task` result onto a task outcome. +/// This is the whole adapter seam: the agent already gates every tool call, +/// so the DAG adds no authority here. +pub fn agent_outcome(result: &crate::agent::AgentExecutionResult) -> TaskOutcome { + let last_failure = result + .steps + .iter() + .flat_map(|s| s.tool_calls.iter()) + .filter_map(|c| c.failure.as_ref()) + .next_back(); + if let Some(f) = last_failure { + if f.class == FailureClass::ApprovalPending { + return TaskOutcome::ApprovalPending; + } + let msg = f + .cause + .first() + .map(|c| c.message.clone()) + .unwrap_or_else(|| "agent tool call failed".into()); + return TaskOutcome::Failed(ToolFault::new(f.class, f.effect_certainty, msg)); + } + if result.completed { + TaskOutcome::Completed(serde_json::json!({ "final_response": result.final_response })) + } else { + // Ran out of turns: tools may have acted, so claim no certainty. + TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + "agent did not complete within its turn budget", + )) + } +} + +/// Runs one `AgentEngine::execute_task` call as a workflow task. +pub struct AgentTaskRunner { + pub engine: Arc, + pub goal: String, + pub max_turns: usize, +} + +#[async_trait] +impl TaskRunner for AgentTaskRunner { + async fn run(&self, _ctx: TaskContext) -> TaskOutcome { + match self + .engine + .execute_task(&self.goal, None, self.max_turns) + .await + { + Ok(r) => agent_outcome(&r), + Err(e) => TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + e.to_string(), + )), + } + } +} From 5e2f1e009b519da2b73ad447be148143122b790c Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 10 Oct 2026 11:04:02 -0500 Subject: [PATCH 2/5] test+docs: workflow DAG tests, demo and overlap note (#39) Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- docs/WORKFLOW-DAG.md | 58 ++++ tests/workflow_dag_tests.rs | 596 ++++++++++++++++++++++++++++++++++++ 2 files changed, 654 insertions(+) create mode 100644 docs/WORKFLOW-DAG.md create mode 100644 tests/workflow_dag_tests.rs diff --git a/docs/WORKFLOW-DAG.md b/docs/WORKFLOW-DAG.md new file mode 100644 index 0000000..023cb82 --- /dev/null +++ b/docs/WORKFLOW-DAG.md @@ -0,0 +1,58 @@ +# Workflow DAG (issue #39) + +A small dependency-aware task layer for multi-step agent work. It decides +when a caller-supplied task may start. Nothing else. + +## Existing machinery + +Inspected before writing any code. + +| Area | What exists | +|---|---| +| `src/orchestration/run.rs` | One `Run` with `RunState {Running, WaitingForApproval, WaitingForTool, Completed, Failed, Cancelled}`, step and action counters, a `Trigger`. A run is a single linear lifecycle. | +| `src/orchestration/budget.rs` | `RunBudget` counters (steps, inference calls, actions, wall seconds) for one run. | +| `src/orchestration/termination.rs`, `trigger.rs` | Why a run ended; what started it. | +| `src/agent.rs` | `AgentEngine::execute_task`: a sequential model/tool loop. Since #38 it classifies tool failures (`FailureRecord`), retries only idempotent no-effect cases, and stops on `ApprovalPending`. | +| `src/failure.rs` (#38) | `FailureClass`, `EffectCertainty`, `FailureRecord`, `CancelToken`. Reused here. | +| `src/events/{event,envelope,bus}.rs` | `AegisEvent`, `EventEnvelope` (has a `sequence` field), broadcast `EventBus`. | +| `src/execution/{broker,action,receipt}.rs` | `ExecutionAuthority` and action receipts: the only authority for effects. | +| `src/sessions`, `tests/aegis_tests.rs` | Ids (`RunId`, `SessionId`), stores, and the integration test conventions (tokio tests, scripted fakes). | + +Already present: the single-run lifecycle, approval-gate states, a per-run budget, cancellation tokens, failure vocabulary, events. + +Absent before this change: prerequisite edges between tasks, readiness tracking, bounded concurrent execution of independent tasks, propagation of a prerequisite's failure to dependents, a workflow-level event order. No equivalent DAG exists, so `src/orchestration/workflow.rs` is new. It is not an inference scheduler: AIEN's `aien-scheduler` and the swarm manager are untouched and never called. + +## Model + +- `TaskId` newtype. `WorkflowSpec::builder().add_task(id, &[deps], runner)...build()` rejects empty ids, duplicate tasks, duplicate edges, self dependency, unknown predecessors and cycles with typed `WorkflowError`. +- `TaskState {Pending, Ready, Running, WaitingForApproval, Completed, Failed(FailureRecord), Cancelled, Skipped{prerequisite}}`. +- `TaskRunner` is the task body and returns `TaskOutcome {Completed(value), Failed(ToolFault), ApprovalPending, Cancelled}`. `certainty_on_interrupt()` says what is known about effects if the DAG interrupts the body (timeout, cancel); the default is `Uncertain`. +- `WorkflowConfig {run_id, session_id, max_parallel, per_task_timeout, total_budget}`. + +## Rules the executor enforces + +- A dependent becomes Ready only when every prerequisite is `Completed`. +- A prerequisite that is `Failed`, `Cancelled` or `Skipped` makes the dependent `Skipped` with a `FailureRecord` of class `Rejected`, certainty `NoEffect`, cause `prerequisite failed: `. This is transitive. +- `WaitingForApproval` is not success and not terminal. Dependents stay `Pending`; the report lists them in `unfinished` and the status is `WaitingForApproval`. +- The DAG never retries or reschedules anything. An `Uncertain` outcome runs once and is final. +- Timeout gives `Failed` with class `Timeout` and the runner's certainty. Cancellation (token or total budget) cancels running tasks and every Pending/Ready task and starts nothing new. +- Parallelism is bounded by a `tokio::sync::Semaphore`. The coordinator only awaits; task bodies run on spawned tasks. No `block_on`. +- The DAG authorizes nothing and caches no decision. Real effects go through the agent/skill gate path or `ExecutionAuthority` inside the task body. + +## Events and replay + +Every transition takes a workflow sequence number under one lock, together with the state change, and is published in that same critical section. New `AegisEvent` variants: `WorkflowTaskReady/Started/Completed/Waiting/Failed/Cancelled/Skipped`, `WorkflowFinished`. They carry `workflow_seq` and go out with `EventEnvelope.sequence` set to it, so sorting by sequence replays the exact order. With `max_parallel = 1` the whole order is fixed for a given spec; with more parallelism the order of simultaneous completions follows real completion order, but the sequence is still gapless and dependency-consistent. Existing variants are unchanged; the canonical mapping returns `None` for the new ones. + +Results: `WorkflowSnapshot.results` maps task id to a sha256 digest of the result value. Failure records for Failed, Skipped and Cancelled tasks are in `WorkflowReport.failures`. + +## Agent adapter + +`AgentTaskRunner` runs one `AgentEngine::execute_task` as a task; `agent_outcome` maps its result (failure class and certainty from the last tool failure, `ApprovalPending` stays pending, an incomplete run is `Failed/Uncertain`). It is a thin seam and is not exercised against a live model in tests. + +## Restart boundary + +Workflow state is in memory only. After a process restart nothing is recovered and no task is resumed or re-run. `WorkflowSnapshot` is serializable (tested) so a later change can persist it, but no schema, table or recovery path exists. A resumed workflow must not re-run a task whose effect is `Uncertain`; that recovery policy is not designed here. + +## Not claimed + +AEGIS is outside release v1; nothing here is wired into a release path or the frozen E2E contract. Timings printed by the demo test compare `max_parallel = 1` against 2 with sleep-based fake tasks on CPU. They are informational, and no GPU or throughput claim is made. diff --git a/tests/workflow_dag_tests.rs b/tests/workflow_dag_tests.rs new file mode 100644 index 0000000..6f23f69 --- /dev/null +++ b/tests/workflow_dag_tests.rs @@ -0,0 +1,596 @@ +//! Task DAG tests (issue #39). CPU only, deterministic ordering assertions, +//! sleep-based fake tasks. Timings are printed for information, never asserted. + +use aegis::orchestration::workflow::{ + runner_fn, runner_fn_with_certainty, TaskContext, TaskOutcome, WorkflowBuilder, +}; +use aegis::{ + AegisEvent, CancelToken, EffectCertainty, EventBus, FailureClass, RunId, SessionId, TaskId, + TaskRunner, TaskState, ToolFault, WorkflowConfig, WorkflowError, WorkflowExecutor, + WorkflowSpec, WorkflowStatus, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +fn cfg(max_parallel: usize) -> WorkflowConfig { + WorkflowConfig::new( + RunId::from_string("run_test"), + SessionId::from_string("sess_test"), + max_parallel, + ) +} + +fn ok(ms: u64) -> Arc { + runner_fn(move |_c: TaskContext| { + Box::pin(async move { + tokio::time::sleep(Duration::from_millis(ms)).await; + TaskOutcome::Completed(serde_json::json!({ "ms": ms })) + }) + }) +} + +fn failing(class: FailureClass, cert: EffectCertainty) -> Arc { + runner_fn(move |_c: TaskContext| { + Box::pin(async move { TaskOutcome::Failed(ToolFault::new(class, cert, "boom")) }) + }) +} + +fn tid(s: &str) -> TaskId { + TaskId::new(s) +} + +fn b() -> WorkflowBuilder { + WorkflowSpec::builder() +} + +/// Records start/finish order and a counter of runs per task. +struct Probe { + log: Mutex>, + runs: Mutex>, + live: AtomicUsize, + peak: AtomicUsize, +} + +impl Probe { + fn new() -> Arc { + Arc::new(Self { + log: Mutex::new(vec![]), + runs: Mutex::new(Default::default()), + live: AtomicUsize::new(0), + peak: AtomicUsize::new(0), + }) + } + + fn task(self: &Arc, name: &'static str, ms: u64) -> Arc { + let p = self.clone(); + runner_fn(move |_c| { + let p = p.clone(); + Box::pin(async move { + let now = p.live.fetch_add(1, Ordering::SeqCst) + 1; + p.peak.fetch_max(now, Ordering::SeqCst); + p.log.lock().unwrap().push(format!("start:{name}")); + *p.runs.lock().unwrap().entry(name.into()).or_default() += 1; + tokio::time::sleep(Duration::from_millis(ms)).await; + p.log.lock().unwrap().push(format!("end:{name}")); + p.live.fetch_sub(1, Ordering::SeqCst); + TaskOutcome::Completed(serde_json::json!(name)) + }) + }) + } + + fn runs(&self, name: &str) -> usize { + self.runs.lock().unwrap().get(name).copied().unwrap_or(0) + } + + fn pos(&self, entry: &str) -> usize { + self.log + .lock() + .unwrap() + .iter() + .position(|e| e == entry) + .unwrap_or_else(|| panic!("missing {entry}")) + } +} + +#[tokio::test] +async fn fixture_a_b_independent_c_waits_d_blocked_on_failure() { + let p = Probe::new(); + let spec = b() + .add_task("A", &[], p.task("A", 30)) + .unwrap() + .add_task("B", &[], p.task("B", 30)) + .unwrap() + .add_task("C", &["A", "B"], p.task("C", 5)) + .unwrap() + .add_task( + "F", + &[], + failing(FailureClass::Failed, EffectCertainty::EffectOccurred), + ) + .unwrap() + .add_task("D", &["F"], p.task("D", 5)) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(4)).unwrap().run(spec).await; + + assert_eq!(p.runs("C"), 1, "C runs exactly once"); + assert!(p.pos("end:A") < p.pos("start:C")); + assert!(p.pos("end:B") < p.pos("start:C")); + assert!(p.pos("start:B") < p.pos("end:A"), "A and B overlapped"); + assert_eq!(p.runs("D"), 0, "D never starts"); + assert_eq!(r.snapshot.states[&tid("C")], TaskState::Completed); + assert!(matches!(r.snapshot.states[&tid("F")], TaskState::Failed(_))); + assert_eq!( + r.snapshot.states[&tid("D")], + TaskState::Skipped { + prerequisite: tid("F") + } + ); + let rec = &r.failures[&tid("D")]; + assert_eq!(rec.class, FailureClass::Rejected); + assert_eq!(rec.effect_certainty, EffectCertainty::NoEffect); + assert_eq!(rec.cause[0].message, "prerequisite failed: F"); + assert_eq!(r.status, WorkflowStatus::Failed); + assert!(r.snapshot.results.contains_key(&tid("C"))); + assert!(!r.snapshot.results.contains_key(&tid("D"))); +} + +#[tokio::test] +async fn skip_propagates_transitively() { + let spec = b() + .add_task( + "F", + &[], + failing(FailureClass::Rejected, EffectCertainty::NoEffect), + ) + .unwrap() + .add_task("X", &["F"], ok(1)) + .unwrap() + .add_task("Y", &["X"], ok(1)) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await; + assert_eq!( + r.snapshot.states[&tid("X")], + TaskState::Skipped { + prerequisite: tid("F") + } + ); + assert_eq!( + r.snapshot.states[&tid("Y")], + TaskState::Skipped { + prerequisite: tid("X") + } + ); +} + +#[test] +fn rejects_cycle() { + let spec = b() + .add_task("A", &["C"], ok(1)) + .unwrap() + .add_task("B", &["A"], ok(1)) + .unwrap() + .add_task("C", &["B"], ok(1)) + .unwrap() + .add_task("Z", &[], ok(1)) + .unwrap() + .build(); + match spec { + Err(WorkflowError::Cycle(c)) => { + assert_eq!(c.len(), 3); + assert!(!c.contains(&tid("Z"))); + } + _ => panic!("expected cycle"), + } +} + +#[test] +fn rejects_self_dependency() { + let e = b().add_task("A", &["A"], ok(1)).err().unwrap(); + assert_eq!(e, WorkflowError::SelfDependency(tid("A"))); +} + +#[test] +fn rejects_unknown_predecessor() { + let e = b() + .add_task("A", &["ghost"], ok(1)) + .unwrap() + .build() + .err() + .unwrap(); + assert_eq!( + e, + WorkflowError::UnknownPredecessor { + task: tid("A"), + predecessor: tid("ghost") + } + ); +} + +#[test] +fn rejects_duplicate_task_and_duplicate_edge() { + let e = b() + .add_task("A", &[], ok(1)) + .unwrap() + .add_task("A", &[], ok(1)) + .err() + .unwrap(); + assert_eq!(e, WorkflowError::DuplicateTask(tid("A"))); + let e = b() + .add_task("A", &[], ok(1)) + .unwrap() + .add_task("B", &["A", "A"], ok(1)) + .err() + .unwrap(); + assert_eq!( + e, + WorkflowError::DuplicateEdge { + task: tid("B"), + predecessor: tid("A") + } + ); +} + +#[test] +fn rejects_zero_parallelism() { + assert!(matches!( + WorkflowExecutor::new(cfg(0)), + Err(WorkflowError::InvalidConfig(_)) + )); +} + +#[tokio::test] +async fn timeout_is_failed_timeout_with_runner_certainty() { + let slow = |c: EffectCertainty| { + runner_fn_with_certainty( + |_c| { + Box::pin(async { + tokio::time::sleep(Duration::from_secs(30)).await; + TaskOutcome::Completed(serde_json::json!(null)) + }) + }, + c, + ) + }; + let spec = b() + .add_task("read_only", &[], slow(EffectCertainty::NoEffect)) + .unwrap() + .add_task("writer", &[], slow(EffectCertainty::Uncertain)) + .unwrap() + .add_task("after", &["writer"], ok(1)) + .unwrap() + .build() + .unwrap(); + let mut c = cfg(2); + c.per_task_timeout = Some(Duration::from_millis(40)); + let r = WorkflowExecutor::new(c).unwrap().run(spec).await; + for (id, cert) in [ + ("read_only", EffectCertainty::NoEffect), + ("writer", EffectCertainty::Uncertain), + ] { + match &r.snapshot.states[&tid(id)] { + TaskState::Failed(f) => { + assert_eq!(f.class, FailureClass::Timeout); + assert_eq!(f.effect_certainty, cert); + } + other => panic!("{id}: {other:?}"), + } + } + assert!(matches!( + r.snapshot.states[&tid("after")], + TaskState::Skipped { .. } + )); +} + +#[tokio::test] +async fn cancellation_cancels_running_and_pending_and_starts_nothing_new() { + let p = Probe::new(); + let spec = b() + .add_task( + "long", + &[], + runner_fn(|c: TaskContext| { + Box::pin(async move { + c.cancel.cancelled().await; + TaskOutcome::Cancelled + }) + }), + ) + .unwrap() + .add_task("next", &["long"], p.task("next", 1)) + .unwrap() + .add_task("other", &[], p.task("other", 1)) + .unwrap() + .build() + .unwrap(); + let cancel = CancelToken::new(); + let c2 = cancel.clone(); + let exec = WorkflowExecutor::new(cfg(1)) + .unwrap() + .with_cancel_token(cancel); + let h = tokio::spawn(async move { exec.run(spec).await }); + tokio::time::sleep(Duration::from_millis(30)).await; + c2.cancel(); + let r = h.await.unwrap(); + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert_eq!(r.snapshot.states[&tid("long")], TaskState::Cancelled); + assert_eq!(r.snapshot.states[&tid("next")], TaskState::Cancelled); + assert_eq!(r.snapshot.states[&tid("other")], TaskState::Cancelled); + assert_eq!(p.runs("next") + p.runs("other"), 0); +} + +#[tokio::test] +async fn total_budget_cancels_the_workflow() { + let spec = b() + .add_task("slow", &[], ok(10_000)) + .unwrap() + .add_task("n", &["slow"], ok(1)) + .unwrap() + .build() + .unwrap(); + let mut c = cfg(2); + c.total_budget = Some(Duration::from_millis(40)); + let r = WorkflowExecutor::new(c).unwrap().run(spec).await; + assert!(r.budget_exhausted); + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert_eq!(r.snapshot.states[&tid("slow")], TaskState::Cancelled); + assert_eq!(r.snapshot.states[&tid("n")], TaskState::Cancelled); +} + +#[tokio::test] +async fn max_parallel_is_honoured() { + for limit in [1usize, 2, 3] { + let p = Probe::new(); + let mut bld = b(); + for n in ["t1", "t2", "t3", "t4", "t5", "t6"] { + bld = bld.add_task(n, &[], p.task(n, 15)).unwrap(); + } + let r = WorkflowExecutor::new(cfg(limit)) + .unwrap() + .run(bld.build().unwrap()) + .await; + assert_eq!(r.status, WorkflowStatus::Completed); + assert!(p.peak.load(Ordering::SeqCst) <= limit, "limit {limit}"); + assert_eq!( + p.peak.load(Ordering::SeqCst), + limit, + "limit {limit} is reached" + ); + assert!(r.peak_concurrency <= limit); + } +} + +#[tokio::test] +async fn approval_pending_blocks_dependents_and_is_not_success() { + let p = Probe::new(); + let spec = b() + .add_task( + "gate", + &[], + runner_fn(|_c| Box::pin(async { TaskOutcome::ApprovalPending })), + ) + .unwrap() + .add_task("after", &["gate"], p.task("after", 1)) + .unwrap() + .add_task("later", &["after"], p.task("later", 1)) + .unwrap() + .add_task("free", &[], p.task("free", 1)) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await; + assert_eq!(r.status, WorkflowStatus::WaitingForApproval); + assert_eq!( + r.snapshot.states[&tid("gate")], + TaskState::WaitingForApproval + ); + assert_eq!(r.snapshot.states[&tid("after")], TaskState::Pending); + assert_eq!(r.snapshot.states[&tid("free")], TaskState::Completed); + assert_eq!(p.runs("after") + p.runs("later"), 0); + assert_eq!(r.unfinished, vec![tid("gate"), tid("after"), tid("later")]); +} + +#[tokio::test] +async fn uncertain_outcome_is_never_rescheduled() { + let n = Arc::new(AtomicUsize::new(0)); + let n2 = n.clone(); + let spec = b() + .add_task( + "write", + &[], + runner_fn(move |_c| { + let n = n2.clone(); + Box::pin(async move { + n.fetch_add(1, Ordering::SeqCst); + TaskOutcome::Failed(ToolFault::new( + FailureClass::Uncertain, + EffectCertainty::Uncertain, + "lost response", + )) + }) + }), + ) + .unwrap() + .add_task("dep", &["write"], ok(1)) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await; + assert_eq!(n.load(Ordering::SeqCst), 1); + match &r.snapshot.states[&tid("write")] { + TaskState::Failed(f) => { + assert_eq!(f.class, FailureClass::Uncertain); + assert_eq!(f.effect_certainty, EffectCertainty::Uncertain); + } + o => panic!("{o:?}"), + } + assert!(matches!( + r.snapshot.states[&tid("dep")], + TaskState::Skipped { .. } + )); +} + +fn diamond(p: &Arc) -> WorkflowSpec { + b().add_task("A", &[], p.task("A", 5)) + .unwrap() + .add_task("B", &["A"], p.task("B", 5)) + .unwrap() + .add_task("C", &["A"], p.task("C", 5)) + .unwrap() + .add_task("D", &["B", "C"], p.task("D", 5)) + .unwrap() + .build() + .unwrap() +} + +#[tokio::test] +async fn event_sequence_is_deterministic_and_matches_the_bus() { + let mut runs = vec![]; + for _ in 0..2 { + let bus = EventBus::default(); + let mut rx = bus.subscribe(); + let p = Probe::new(); + // max_parallel 1 removes completion races, so the whole order is fixed. + let r = WorkflowExecutor::new(cfg(1)) + .unwrap() + .with_event_bus(bus) + .run(diamond(&p)) + .await; + let mut bus_seq = vec![]; + while let Ok(env) = rx.try_recv() { + let name = match env.event { + AegisEvent::WorkflowTaskReady { task_id, .. } => format!("ready:{task_id}"), + AegisEvent::WorkflowTaskStarted { task_id, .. } => format!("started:{task_id}"), + AegisEvent::WorkflowTaskCompleted { + task_id, + result_digest, + .. + } => { + assert!(result_digest.starts_with("sha256:")); + format!("completed:{task_id}") + } + AegisEvent::WorkflowFinished { .. } => "finished".into(), + other => panic!("unexpected {other:?}"), + }; + bus_seq.push((env.sequence, name)); + } + let from_report: Vec<(u64, String)> = r + .events + .iter() + .map(|e| { + let n = match &e.task_id { + Some(t) => format!("{}:{t}", e.state), + None => e.state.clone(), + }; + (e.seq, n.replace("running", "started")) + }) + .collect(); + assert_eq!(bus_seq, from_report, "bus order equals recorded order"); + let seqs: Vec = bus_seq.iter().map(|e| e.0).collect(); + assert_eq!(seqs, (1..=seqs.len() as u64).collect::>()); + runs.push(bus_seq); + } + assert_eq!(runs[0], runs[1]); +} + +#[tokio::test] +async fn parallel_run_sequence_is_gapless_and_orders_dependencies() { + let p = Probe::new(); + let r = WorkflowExecutor::new(cfg(4)) + .unwrap() + .run(diamond(&p)) + .await; + let seqs: Vec = r.events.iter().map(|e| e.seq).collect(); + assert_eq!(seqs, (1..=seqs.len() as u64).collect::>()); + let at = |t: &str, s: &str| { + r.events + .iter() + .find(|e| e.task_id.as_ref().map(|x| x.as_str()) == Some(t) && e.state == s) + .unwrap() + .seq + }; + assert!(at("A", "completed") < at("B", "ready")); + assert!(at("B", "completed") < at("D", "ready")); + assert!(at("C", "completed") < at("D", "ready")); +} + +#[tokio::test] +async fn snapshot_is_serializable_and_deterministic() { + let p = Probe::new(); + let r = WorkflowExecutor::new(cfg(1)) + .unwrap() + .run(diamond(&p)) + .await; + let j1 = serde_json::to_string(&r.snapshot).unwrap(); + let j2 = serde_json::to_string(&r.snapshot.clone()).unwrap(); + assert_eq!(j1, j2); + let back: aegis::orchestration::workflow::WorkflowSnapshot = serde_json::from_str(&j1).unwrap(); + assert_eq!(back, r.snapshot); + // A failed task also round trips (it carries a FailureRecord). + let spec = b() + .add_task( + "F", + &[], + failing(FailureClass::Failed, EffectCertainty::EffectOccurred), + ) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(1)).unwrap().run(spec).await; + let j = serde_json::to_string(&r.snapshot).unwrap(); + let back: aegis::orchestration::workflow::WorkflowSnapshot = serde_json::from_str(&j).unwrap(); + assert_eq!(back, r.snapshot); +} + +/// Demo: edit and lint are independent, test needs both, a build task fails +/// and its dependent report is skipped. Same four-plus tasks run with +/// max_parallel 1 (sequential) and 2. Only ordering and the bound are asserted. +#[tokio::test] +async fn demo_code_test_eval_dag_sequential_vs_parallel() { + async fn run( + limit: usize, + p: &Arc, + ) -> (Duration, aegis::orchestration::workflow::WorkflowReport) { + let spec = b() + .add_task("edit", &[], p.task("edit", 40)) + .unwrap() + .add_task("lint", &[], p.task("lint", 40)) + .unwrap() + .add_task("test", &["edit", "lint"], p.task("test", 20)) + .unwrap() + .add_task( + "build_docs", + &[], + failing(FailureClass::Failed, EffectCertainty::EffectOccurred), + ) + .unwrap() + .add_task("report", &["build_docs"], p.task("report", 20)) + .unwrap() + .build() + .unwrap(); + let t = Instant::now(); + let r = WorkflowExecutor::new(cfg(limit)).unwrap().run(spec).await; + (t.elapsed(), r) + } + let p1 = Probe::new(); + let (seq_t, r1) = run(1, &p1).await; + let p2 = Probe::new(); + let (par_t, r2) = run(2, &p2).await; + println!("INFO sequential(max_parallel=1) {seq_t:?} dag(max_parallel=2) {par_t:?}"); + assert!(p1.peak.load(Ordering::SeqCst) <= 1); + assert!(p2.peak.load(Ordering::SeqCst) <= 2); + assert!(p2.pos("end:edit") < p2.pos("start:test")); + assert!(p2.pos("end:lint") < p2.pos("start:test")); + assert_eq!(p2.runs("report"), 0); + for r in [&r1, &r2] { + assert_eq!(r.snapshot.states[&tid("test")], TaskState::Completed); + assert!(matches!( + r.snapshot.states[&tid("report")], + TaskState::Skipped { .. } + )); + } +} From f80c04c3c709a823db4ad911d3b1401fcecf82b0 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 10 Oct 2026 11:05:06 -0500 Subject: [PATCH 3/5] crumb compile Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 24 ++++++++++++------------ docs/.crumb | 10 +++++----- src/.crumb | 20 ++++++++++---------- src/events/.crumb | 8 ++++---- src/orchestration/.crumb | 10 +++++----- tests/.crumb | 10 +++++----- 6 files changed, 41 insertions(+), 41 deletions(-) diff --git a/.crumb b/.crumb index ef3f41c..78881c4 100644 --- a/.crumb +++ b/.crumb @@ -25,8 +25,8 @@ "generated": { "children": [ { - "digest": "8c6acdc9a526bbdc77b97c7f57fbfc452f30e37ae586baeb3f1bca94ef638b41", - "last_commit": "59106f2", + "digest": "0e67f750d69e5210c482d53230ffe07209af58a7d6176eb6a936759c0504d4c6", + "last_commit": "e21dab3", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -43,27 +43,27 @@ "purpose": "Directory scripts. Purpose not yet described by a human." }, { - "digest": "9b9d657c8664a989a95b74e0e0be8b4c6224939dd63bb58735a7269a43a0df9d", - "last_commit": "59106f2", + "digest": "abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", + "last_commit": "8cba4a8", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "553b7ce7b77250717e875a812846042ff7b9dba674f0d17213a550feee3065bf", - "last_commit": "59106f2", + "digest": "df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", + "last_commit": "e21dab3", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." } ], - "children_root": "sha256:d8ec53ddc9c061bc6dfad5e949fc039883591c9187142fbe6dfc1ac7da9c7b43", - "compiled_at": "2026-10-10T16:04:06Z", + "children_root": "sha256:40c5a9c14dc005adbcf61c63a2217d0da1e551b9fe6368b2103b490c3226935e", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:38f7c78c5829dc07d3238f0d0b8e126e8f3467cde530781f7d70155f8d58cb0c", + "digest": "sha256:a3483fe46887a8829bc847c0b1f129fb54e9ea2fe3ca2cb0e73001b8a6115ae0", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 80, - "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", - "source_tree": "sha256:55741903b205bfafd8ff9d3c3f666f6beb0e7a2feca91ab25e8175ad211548ae" + "files": 83, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:79fe2cae789343782218006056cd3f7f27d80620de55a9c2107e3de7a744f76a" }, "owner_lane": "", "seed": { diff --git a/docs/.crumb b/docs/.crumb index eb6ecc1..e30bbbd 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-10T16:04:06Z", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:8c6acdc9a526bbdc77b97c7f57fbfc452f30e37ae586baeb3f1bca94ef638b41", + "digest": "sha256:0e67f750d69e5210c482d53230ffe07209af58a7d6176eb6a936759c0504d4c6", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 2, - "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", - "source_tree": "sha256:e7c8114eed38411665a78d8bc2d26ca79f00e6c8eb1e8120655ef1e39f5e45dc" + "files": 3, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:6a89e2f26e44220fe9335f8be611fac690c78f656d1f6bd0b88359f98a91ed85" }, "owner_lane": "", "seed": { diff --git a/src/.crumb b/src/.crumb index 5441a10..00a4ebe 100644 --- a/src/.crumb +++ b/src/.crumb @@ -39,8 +39,8 @@ "purpose": "Directory src/defense. Purpose not yet described by a human." }, { - "digest": "512fab250fa949734a143c79571f82ac993c503fcd2ac71f699cf34415582481", - "last_commit": "d98ba21", + "digest": "14dd72b905c79d44b86b01f4ab43763cf21520fd4e38f077b682e35268010d17", + "last_commit": "8cba4a8", "name": "events", "purpose": "Directory src/events. Purpose not yet described by a human." }, @@ -51,8 +51,8 @@ "purpose": "Directory src/execution. Purpose not yet described by a human." }, { - "digest": "0c08369b428afac636246de8b36637a58106c235df8524f3f01be1195cc70dbe", - "last_commit": "1b0c299", + "digest": "2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", + "last_commit": "8cba4a8", "name": "orchestration", "purpose": "Directory src/orchestration. Purpose not yet described by a human." }, @@ -69,15 +69,15 @@ "purpose": "Directory src/sessions. Purpose not yet described by a human." } ], - "children_root": "sha256:eafd79d762cf1c61e44c50176c2dfe4636950452ab07f0e54908276de92a5aa2", - "compiled_at": "2026-10-10T16:04:06Z", + "children_root": "sha256:a59ed6eb87f1c402e863353ec922d5962090251ec943c0389b96c1ffa11a5a8e", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:9b9d657c8664a989a95b74e0e0be8b4c6224939dd63bb58735a7269a43a0df9d", + "digest": "sha256:abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 48, - "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", - "source_tree": "sha256:ba81f730236b2440dd667c9d0ae62df98dac3a39df29fe9ca5a21db97d327e95" + "files": 49, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:cbff5b20541baaf2bbd1db819692230be1d361a6ff77a3c4610847c5a62a47d2" }, "owner_lane": "", "seed": { diff --git a/src/events/.crumb b/src/events/.crumb index 5cd819e..231ad39 100644 --- a/src/events/.crumb +++ b/src/events/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-10T15:56:06Z", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:512fab250fa949734a143c79571f82ac993c503fcd2ac71f699cf34415582481", + "digest": "sha256:14dd72b905c79d44b86b01f4ab43763cf21520fd4e38f077b682e35268010d17", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 5, - "generated_at_commit": "b805c8890675e0e9ddc3eec065ad09061a58dc3a", - "source_tree": "sha256:5e6da4bc45d00e5c2d1a061ee8d50e563fda9056deb87772438b90888a0cff7b" + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:559178d9f324b485ea60b2c5633cae9bcaa92b50f320b9ec3b7a6130230abef2" }, "owner_lane": "", "seed": { diff --git a/src/orchestration/.crumb b/src/orchestration/.crumb index fe21733..89d9399 100644 --- a/src/orchestration/.crumb +++ b/src/orchestration/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T18:13:51Z", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:0c08369b428afac636246de8b36637a58106c235df8524f3f01be1195cc70dbe", + "digest": "sha256:2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 5, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:b0e17001d12b6199a624eca29181527851108d5157f2460ea610a4e4074a0f10" + "files": 6, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:a348ca8c11e634e65edf319e0d659df6d1fa70fd32a1ace49ff38e167dab98a3" }, "owner_lane": "", "seed": { diff --git a/tests/.crumb b/tests/.crumb index b828c75..dd48b57 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:2f0b999b8999ad3095c8081fb342d506f27f7b07b31452b67140d330ccf4dc76", - "compiled_at": "2026-10-10T16:04:06Z", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:553b7ce7b77250717e875a812846042ff7b9dba674f0d17213a550feee3065bf", + "digest": "sha256:df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 10, - "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", - "source_tree": "sha256:5c2fdd65496a766d892518fb6ae28568d7e5a62345e63fa907b6892efaefedf7" + "files": 11, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:5da247af43d882b241d26788cf1e16fe963f108ba4c49efd8d7fec82220cf485" }, "owner_lane": "", "seed": { From 7be8b4b8c9c0aa061d85694997d5c5063fadd264 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 10 Oct 2026 11:23:18 -0500 Subject: [PATCH 4/5] workflow: address review minors (fail-closed agent outcome, cancel waiting tasks, budget token, redaction, tests) Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- src/orchestration/workflow.rs | 129 ++++++++++++----- tests/workflow_dag_tests.rs | 264 ++++++++++++++++++++++++++++++++++ 2 files changed, 359 insertions(+), 34 deletions(-) diff --git a/src/orchestration/workflow.rs b/src/orchestration/workflow.rs index f57223b..e9e6eae 100644 --- a/src/orchestration/workflow.rs +++ b/src/orchestration/workflow.rs @@ -9,8 +9,8 @@ use crate::events::{AegisEvent, EventBus, EventEnvelope}; use crate::failure::{ - now_millis, payload_digest, CancelToken, EffectCertainty, FailureClass, FailureRecord, - ToolFault, + now_millis, payload_digest, redact_payload_echoes, truncate_bytes, CancelToken, + EffectCertainty, FailureClass, FailureRecord, ToolFault, MAX_CAUSE_MESSAGE_BYTES, }; use crate::sessions::id::{RunId, SessionId}; use async_trait::async_trait; @@ -237,8 +237,9 @@ pub struct WorkflowBuilder { } impl WorkflowBuilder { - /// Predecessors must already be added, which also makes forward edges - /// (and so most cycles) impossible; `build` still checks the whole graph. + /// Predecessors may be added after their dependents (forward references + /// are allowed). `build` validates the whole graph: unknown predecessors, + /// duplicate edges and cycles are all rejected there. pub fn add_task( mut self, id: impl Into, @@ -455,7 +456,9 @@ impl Recorder { state: name.to_string(), }); // Publish while holding the lock so bus order equals sequence order. - self.publish(event, seq); + if let Some(event) = event { + self.publish(event, seq); + } seq } @@ -509,15 +512,14 @@ impl Recorder { id: &TaskId, state: &TaskState, result: Option<&ResultHandle>, - ) -> AegisEvent { + ) -> Option { let run_id = self.run_id.to_string(); let task_id = id.to_string(); - match state { - TaskState::Pending => AegisEvent::WorkflowTaskReady { - run_id, - workflow_seq: seq, - task_id, - }, + Some(match state { + // Pending is the initial state and is never recorded as a + // transition, and the event enum has no variant for it, so no + // bus event exists (the ledger entry is still written). + TaskState::Pending => return None, TaskState::Ready => AegisEvent::WorkflowTaskReady { run_id, workflow_seq: seq, @@ -556,7 +558,7 @@ impl Recorder { task_id, prerequisite: prerequisite.to_string(), }, - } + }) } } @@ -618,7 +620,7 @@ impl WorkflowExecutor { now, now, ) - .with_cause("workflow", message, None) + .with_cause("workflow", &scrub_message(message), None) } /// Runs the DAG to quiescence. Never blocks a worker thread: the @@ -647,6 +649,9 @@ impl WorkflowExecutor { let mut by_join_id: HashMap = HashMap::new(); let mut live = 0usize; let mut peak = 0usize; + // The executor never triggers the caller's token. Budget expiry and + // observed caller cancels both trip this run-local token instead. + let run_cancel = CancelToken::new(); let mut cancel_seen = false; let mut budget_exhausted = false; let deadline = self @@ -654,22 +659,18 @@ impl WorkflowExecutor { .total_budget .map(|d| tokio::time::Instant::now() + d); - loop { - if !cancel_seen && self.cancel.is_cancelled() { + 'outer: loop { + // Deadline first: no task may start once the budget is spent. + if !budget_exhausted && deadline.is_some_and(|d| tokio::time::Instant::now() >= d) { + budget_exhausted = true; + run_cancel.cancel(); + } + if self.cancel.is_cancelled() { + run_cancel.cancel(); + } + if !cancel_seen && run_cancel.is_cancelled() { cancel_seen = true; - for id in &ids { - if matches!(rec.state_of(id), TaskState::Pending | TaskState::Ready) { - let f = self.failure( - &rec, - id, - FailureClass::Cancelled, - EffectCertainty::NoEffect, - "workflow cancelled before start", - ); - rec.note_failure(id, f); - rec.transition(id, TaskState::Cancelled, None); - } - } + self.cancel_open(&rec, &ids, &nodes); } if !cancel_seen { @@ -679,6 +680,14 @@ impl WorkflowExecutor { if rec.state_of(id) != TaskState::Ready { continue; } + // Re-check right before starting: cancel or an expired + // budget restarts the pass, which cancels what is left. + if self.cancel.is_cancelled() + || run_cancel.is_cancelled() + || deadline.is_some_and(|d| tokio::time::Instant::now() >= d) + { + continue 'outer; + } let Ok(permit) = permits.clone().try_acquire_owned() else { break; }; @@ -691,9 +700,9 @@ impl WorkflowExecutor { task_id: id.clone(), run_id: self.config.run_id.clone(), session_id: self.config.session_id.clone(), - cancel: self.cancel.clone(), + cancel: run_cancel.clone(), }; - let cancel = self.cancel.clone(); + let cancel = run_cancel.clone(); let timeout = self.config.per_task_timeout; let tid = id.clone(); let handle = running.spawn(async move { @@ -723,7 +732,11 @@ impl WorkflowExecutor { } let joined = tokio::select! { - j = running.join_next_with_id() => j, + biased; + _ = self.cancel.cancelled(), if !cancel_seen => { + run_cancel.cancel(); + continue; + } _ = async { match deadline { Some(d) => tokio::time::sleep_until(d).await, @@ -731,9 +744,10 @@ impl WorkflowExecutor { } }, if !budget_exhausted => { budget_exhausted = true; - self.cancel.cancel(); + run_cancel.cancel(); continue; } + j = running.join_next_with_id() => j, }; let Some(joined) = joined else { break }; live -= 1; @@ -763,9 +777,34 @@ impl WorkflowExecutor { self.settle(&rec, &tid, finish, interrupt); } + if cancel_seen { + // A task that reported ApprovalPending after the cancel was seen + // is settled here, so Cancelled never lists unfinished tasks. + self.cancel_open(&rec, &ids, &nodes); + } self.report(rec, ids, peak, budget_exhausted, cancel_seen) } + /// Moves every non-terminal, non-running task to Cancelled. A task + /// waiting for approval is cancelled too: nothing will ever resume it. + fn cancel_open(&self, rec: &Recorder, ids: &[TaskId], nodes: &HashMap) { + for id in ids { + let (message, certainty) = match rec.state_of(id) { + TaskState::Pending | TaskState::Ready => { + ("workflow cancelled before start", EffectCertainty::NoEffect) + } + TaskState::WaitingForApproval => ( + "workflow cancelled while waiting for approval", + nodes[id].runner.certainty_on_interrupt(), + ), + _ => continue, + }; + let f = self.failure(rec, id, FailureClass::Cancelled, certainty, message); + rec.note_failure(id, f); + rec.transition(id, TaskState::Cancelled, None); + } + } + /// Unblocks dependents whose prerequisites all completed, and skips /// dependents of any prerequisite that ended without success. A task that /// waits for approval is not terminal, so its dependents stay Pending. @@ -902,6 +941,14 @@ impl WorkflowExecutor { } } +/// Error text from runners and engines goes into Workflow events and reports, +/// so it is cut to the cause limit before it is recorded. Runners that know +/// their payload should also call `redact_payload_echoes` first (the agent +/// adapter does). +fn scrub_message(message: &str) -> String { + truncate_bytes(message, MAX_CAUSE_MESSAGE_BYTES) +} + /// Maps a finished `AgentEngine::execute_task` result onto a task outcome. /// This is the whole adapter seam: the agent already gates every tool call, /// so the DAG adds no authority here. @@ -923,6 +970,20 @@ pub fn agent_outcome(result: &crate::agent::AgentExecutionResult) -> TaskOutcome .unwrap_or_else(|| "agent tool call failed".into()); return TaskOutcome::Failed(ToolFault::new(f.class, f.effect_certainty, msg)); } + // Deny by default: a failed call with no provenance record (older + // records) is still a failure, and its effect is unknown. + let unrecorded_failure = result + .steps + .iter() + .flat_map(|s| s.tool_calls.iter()) + .any(|c| !c.success); + if unrecorded_failure { + return TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + "agent tool call failed without a failure record", + )); + } if result.completed { TaskOutcome::Completed(serde_json::json!({ "final_response": result.final_response })) } else { @@ -954,7 +1015,7 @@ impl TaskRunner for AgentTaskRunner { Err(e) => TaskOutcome::Failed(ToolFault::new( FailureClass::Failed, EffectCertainty::Uncertain, - e.to_string(), + redact_payload_echoes(&e.to_string(), &serde_json::json!({ "goal": self.goal })), )), } } diff --git a/tests/workflow_dag_tests.rs b/tests/workflow_dag_tests.rs index 6f23f69..04505a2 100644 --- a/tests/workflow_dag_tests.rs +++ b/tests/workflow_dag_tests.rs @@ -594,3 +594,267 @@ async fn demo_code_test_eval_dag_sequential_vs_parallel() { )); } } + +fn gapless(r: &aegis::WorkflowReport) { + let seqs: Vec = r.events.iter().map(|e| e.seq).collect(); + assert_eq!(seqs, (1..=seqs.len() as u64).collect::>()); + assert_eq!(r.snapshot.last_seq, seqs.len() as u64); +} + +fn agent_result( + calls: Vec, + completed: bool, +) -> aegis::AgentExecutionResult { + aegis::AgentExecutionResult { + final_response: "done".into(), + steps: vec![aegis::AgentStep { + step_index: 0, + thought: None, + tool_calls: calls, + }], + turns_taken: 1, + duration_ms: 0, + completed, + } +} + +fn call(success: bool) -> aegis::ToolExecutionRecord { + aegis::ToolExecutionRecord { + call_id: "c1".into(), + tool_name: "t".into(), + arguments: serde_json::json!({}), + output: String::new(), + success, + failure: None, + retry_failures: vec![], + } +} + +#[test] +fn agent_outcome_unrecorded_failure_is_failed_and_uncertain() { + use aegis::orchestration::workflow::agent_outcome; + // success=false with no failure record must never read as success. + match agent_outcome(&agent_result(vec![call(false)], true)) { + TaskOutcome::Failed(f) => { + assert_eq!(f.class, FailureClass::Failed); + assert_eq!(f.certainty, EffectCertainty::Uncertain); + } + other => panic!("expected Failed, got {other:?}"), + } + // Control: a clean completed run is still success. + assert!(matches!( + agent_outcome(&agent_result(vec![call(true)], true)), + TaskOutcome::Completed(_) + )); + // Incomplete run stays Failed/Uncertain. + assert!(matches!( + agent_outcome(&agent_result(vec![call(true)], false)), + TaskOutcome::Failed(_) + )); +} + +#[tokio::test] +async fn cancel_while_waiting_for_approval_leaves_nothing_unfinished() { + let p = Probe::new(); + let spec = b() + .add_task( + "gate", + &[], + runner_fn(|_c| Box::pin(async { TaskOutcome::ApprovalPending })), + ) + .unwrap() + .add_task("after", &["gate"], p.task("after", 1)) + .unwrap() + .add_task( + "long", + &[], + runner_fn(|c: TaskContext| { + Box::pin(async move { + c.cancel.cancelled().await; + TaskOutcome::Cancelled + }) + }), + ) + .unwrap() + .build() + .unwrap(); + let cancel = CancelToken::new(); + let c2 = cancel.clone(); + let exec = WorkflowExecutor::new(cfg(2)) + .unwrap() + .with_cancel_token(cancel); + let h = tokio::spawn(async move { exec.run(spec).await }); + tokio::time::sleep(Duration::from_millis(30)).await; + c2.cancel(); + let r = h.await.unwrap(); + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert_eq!(r.snapshot.states[&tid("gate")], TaskState::Cancelled); + assert_eq!(r.snapshot.states[&tid("after")], TaskState::Cancelled); + assert_eq!(r.snapshot.states[&tid("long")], TaskState::Cancelled); + assert!(r.unfinished.is_empty(), "unfinished: {:?}", r.unfinished); + assert_eq!(p.runs("after"), 0); + gapless(&r); +} + +#[tokio::test] +async fn budget_exhaustion_does_not_cancel_the_callers_token() { + let spec = b() + .add_task("slow", &[], ok(10_000)) + .unwrap() + .build() + .unwrap(); + let caller = CancelToken::new(); + let mut c = cfg(1); + c.total_budget = Some(Duration::from_millis(40)); + let r = WorkflowExecutor::new(c) + .unwrap() + .with_cancel_token(caller.clone()) + .run(spec) + .await; + assert!(r.budget_exhausted); + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert!(!caller.is_cancelled(), "executor must only read the token"); +} + +#[tokio::test] +async fn caller_cancel_still_stops_the_workflow_through_the_run_token() { + let spec = b() + .add_task("slow", &[], ok(10_000)) + .unwrap() + .build() + .unwrap(); + let caller = CancelToken::new(); + caller.cancel(); + let r = WorkflowExecutor::new(cfg(1)) + .unwrap() + .with_cancel_token(caller) + .run(spec) + .await; + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert_eq!(r.snapshot.states[&tid("slow")], TaskState::Cancelled); +} + +#[tokio::test] +async fn no_task_starts_once_the_budget_is_exhausted() { + let p = Probe::new(); + let spec = b() + .add_task("a", &[], p.task("a", 1)) + .unwrap() + .add_task("b", &["a"], p.task("b", 1)) + .unwrap() + .build() + .unwrap(); + let mut c = cfg(2); + c.total_budget = Some(Duration::ZERO); + let r = WorkflowExecutor::new(c).unwrap().run(spec).await; + assert!(r.budget_exhausted); + assert_eq!(r.status, WorkflowStatus::Cancelled); + assert_eq!(p.runs("a") + p.runs("b"), 0, "nothing may start"); + assert!(r.unfinished.is_empty()); + gapless(&r); +} + +#[tokio::test] +async fn dependents_do_not_start_when_the_budget_expires_as_a_task_finishes() { + let p = Probe::new(); + // "first" outlives the 30 ms budget, so its dependent must never start + // even though "first" itself completes normally. + let spec = b() + .add_task( + "first", + &[], + runner_fn(|_c| { + Box::pin(async { + // Blocks the thread past the deadline, then returns + // without yielding to the timer. + std::thread::sleep(Duration::from_millis(80)); + TaskOutcome::Completed(serde_json::json!(1)) + }) + }), + ) + .unwrap() + .add_task("second", &["first"], p.task("second", 1)) + .unwrap() + .build() + .unwrap(); + let mut c = cfg(1); + c.total_budget = Some(Duration::from_millis(30)); + let r = WorkflowExecutor::new(c).unwrap().run(spec).await; + assert_eq!(p.runs("second"), 0, "no task starts after the budget"); + assert!(r.budget_exhausted); + assert!(r.unfinished.is_empty()); + gapless(&r); +} + +#[tokio::test] +async fn panicking_task_is_failed_uncertain_and_releases_its_permit() { + let p = Probe::new(); + let spec = b() + .add_task( + "boom", + &[], + runner_fn(|_c| { + Box::pin(async { + if true { + panic!("task body panic (expected in this test)"); + } + TaskOutcome::Cancelled + }) + }), + ) + .unwrap() + .add_task("dep", &["boom"], p.task("dep", 1)) + .unwrap() + .add_task("free", &[], p.task("free", 1)) + .unwrap() + .build() + .unwrap(); + // One permit: "free" can only run if the panicking task released it. + let r = WorkflowExecutor::new(cfg(1)).unwrap().run(spec).await; + assert!(matches!( + r.snapshot.states[&tid("boom")], + TaskState::Failed(_) + )); + let rec = &r.failures[&tid("boom")]; + assert_eq!(rec.class, FailureClass::Failed); + assert_eq!(rec.effect_certainty, EffectCertainty::Uncertain); + assert_eq!( + r.snapshot.states[&tid("dep")], + TaskState::Skipped { + prerequisite: tid("boom") + } + ); + assert_eq!(p.runs("dep"), 0); + assert_eq!(p.runs("free"), 1, "permit was released"); + assert_eq!(r.snapshot.states[&tid("free")], TaskState::Completed); + assert_eq!(r.status, WorkflowStatus::Failed); + assert!(r.unfinished.is_empty()); + assert_eq!(r.events.last().unwrap().state, "finished"); + gapless(&r); +} + +#[tokio::test] +async fn runner_error_text_is_truncated_before_it_is_recorded() { + let long = "x".repeat(5000); + let spec = b() + .add_task( + "noisy", + &[], + runner_fn(move |_c| { + let long = long.clone(); + Box::pin(async move { + TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + long, + )) + }) + }), + ) + .unwrap() + .build() + .unwrap(); + let r = WorkflowExecutor::new(cfg(1)).unwrap().run(spec).await; + let msg = &r.failures[&tid("noisy")].cause[0].message; + assert!(msg.len() <= aegis::failure::MAX_CAUSE_MESSAGE_BYTES); +} From 5507924c850c2221bca8049c6a4022d7d33b9867 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 10 Oct 2026 11:23:21 -0500 Subject: [PATCH 5/5] crumb compile Co-authored-by: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 20 ++++++++++---------- src/.crumb | 16 ++++++++-------- src/orchestration/.crumb | 8 ++++---- tests/.crumb | 8 ++++---- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/.crumb b/.crumb index 78881c4..1f45a06 100644 --- a/.crumb +++ b/.crumb @@ -26,7 +26,7 @@ "children": [ { "digest": "0e67f750d69e5210c482d53230ffe07209af58a7d6176eb6a936759c0504d4c6", - "last_commit": "e21dab3", + "last_commit": "5e2f1e0", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -43,27 +43,27 @@ "purpose": "Directory scripts. Purpose not yet described by a human." }, { - "digest": "abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", - "last_commit": "8cba4a8", + "digest": "3ba2f83f6464f4b188455f5f3fdfb5da1e845e36f314b7534423c5845467965a", + "last_commit": "7be8b4b", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", - "last_commit": "e21dab3", + "digest": "fd142eed5f6851fd3e67d7c91052c66f86a2b712c46c17d5a4b37675e0401f4d", + "last_commit": "7be8b4b", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." } ], - "children_root": "sha256:40c5a9c14dc005adbcf61c63a2217d0da1e551b9fe6368b2103b490c3226935e", - "compiled_at": "2026-10-10T16:05:01Z", + "children_root": "sha256:e362015ce6e6150f5df5a3973c8ebe529983bbaef591b0881d55529f22823885", + "compiled_at": "2026-10-10T16:23:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:a3483fe46887a8829bc847c0b1f129fb54e9ea2fe3ca2cb0e73001b8a6115ae0", + "digest": "sha256:7919ea5acabff482f35a4ca27daa8d0694c88060afa1913777991c8b8e645e4a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 83, - "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", - "source_tree": "sha256:79fe2cae789343782218006056cd3f7f27d80620de55a9c2107e3de7a744f76a" + "generated_at_commit": "7be8b4b8c9c0aa061d85694997d5c5063fadd264", + "source_tree": "sha256:b658631617c7c95f058bfab65a5000808c178f095aa9051fd4082b89801ff296" }, "owner_lane": "", "seed": { diff --git a/src/.crumb b/src/.crumb index 00a4ebe..b018664 100644 --- a/src/.crumb +++ b/src/.crumb @@ -40,7 +40,7 @@ }, { "digest": "14dd72b905c79d44b86b01f4ab43763cf21520fd4e38f077b682e35268010d17", - "last_commit": "8cba4a8", + "last_commit": "0a956be", "name": "events", "purpose": "Directory src/events. Purpose not yet described by a human." }, @@ -51,8 +51,8 @@ "purpose": "Directory src/execution. Purpose not yet described by a human." }, { - "digest": "2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", - "last_commit": "8cba4a8", + "digest": "c994eac17bd5e8da3a1f9e91ee112dd353fafc7756c9706cef7eb1954f5f2d1d", + "last_commit": "7be8b4b", "name": "orchestration", "purpose": "Directory src/orchestration. Purpose not yet described by a human." }, @@ -69,15 +69,15 @@ "purpose": "Directory src/sessions. Purpose not yet described by a human." } ], - "children_root": "sha256:a59ed6eb87f1c402e863353ec922d5962090251ec943c0389b96c1ffa11a5a8e", - "compiled_at": "2026-10-10T16:05:01Z", + "children_root": "sha256:af95fafcd57d595dacdc278a75abcc274f666cc995a97fa23b7b03ba2626d9c8", + "compiled_at": "2026-10-10T16:23:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", + "digest": "sha256:3ba2f83f6464f4b188455f5f3fdfb5da1e845e36f314b7534423c5845467965a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 49, - "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", - "source_tree": "sha256:cbff5b20541baaf2bbd1db819692230be1d361a6ff77a3c4610847c5a62a47d2" + "generated_at_commit": "7be8b4b8c9c0aa061d85694997d5c5063fadd264", + "source_tree": "sha256:a23d0652ba2519f30a2779a97f29d863c1a9d280e364d067d35a32909c617d59" }, "owner_lane": "", "seed": { diff --git a/src/orchestration/.crumb b/src/orchestration/.crumb index 89d9399..0e0780e 100644 --- a/src/orchestration/.crumb +++ b/src/orchestration/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-10T16:05:01Z", + "compiled_at": "2026-10-10T16:23:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", + "digest": "sha256:c994eac17bd5e8da3a1f9e91ee112dd353fafc7756c9706cef7eb1954f5f2d1d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 6, - "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", - "source_tree": "sha256:a348ca8c11e634e65edf319e0d659df6d1fa70fd32a1ace49ff38e167dab98a3" + "generated_at_commit": "7be8b4b8c9c0aa061d85694997d5c5063fadd264", + "source_tree": "sha256:2c167bb99e33cc151dddede0363ab7b0f654918c12b44cdc96d6a39598ba3fad" }, "owner_lane": "", "seed": { diff --git a/tests/.crumb b/tests/.crumb index dd48b57..1a90c55 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:2f0b999b8999ad3095c8081fb342d506f27f7b07b31452b67140d330ccf4dc76", - "compiled_at": "2026-10-10T16:05:01Z", + "compiled_at": "2026-10-10T16:23:18Z", "compiler": "crumb-compile/1", - "digest": "sha256:df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", + "digest": "sha256:fd142eed5f6851fd3e67d7c91052c66f86a2b712c46c17d5a4b37675e0401f4d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 11, - "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", - "source_tree": "sha256:5da247af43d882b241d26788cf1e16fe963f108ba4c49efd8d7fec82220cf485" + "generated_at_commit": "7be8b4b8c9c0aa061d85694997d5c5063fadd264", + "source_tree": "sha256:d5d07c84588d423524e37f67723ce057e56f83fd4133f70dbbd3b42ccb4f94ec" }, "owner_lane": "", "seed": {