aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / orchestration / workflow.rs
| 1 | //! Dependency-aware task workflow (DAG) for multi-step agent work (issue #39). |
| 2 | //! |
| 3 | //! This layer sits above the single-run lifecycle in `orchestration::run` and |
| 4 | //! far above AIEN inference scheduling. It decides only WHEN a caller-supplied |
| 5 | //! task may start. It authorizes nothing, caches no decision, retries nothing |
| 6 | //! and never schedules inference: every real effect happens inside the task |
| 7 | //! body through the existing gated paths. State is in memory only and does not |
| 8 | //! survive a restart (see `docs/WORKFLOW-DAG.md`). |
| 9 | |
| 10 | use crate::events::{AegisEvent, EventBus, EventEnvelope}; |
| 11 | use crate::failure::{ |
| 12 | now_millis, payload_digest, redact_payload_echoes, truncate_bytes, CancelToken, |
| 13 | EffectCertainty, FailureClass, FailureRecord, ToolFault, MAX_CAUSE_MESSAGE_BYTES, |
| 14 | }; |
| 15 | use crate::sessions::id::{RunId, SessionId}; |
| 16 | use async_trait::async_trait; |
| 17 | use futures_util::future::BoxFuture; |
| 18 | use parking_lot::Mutex; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 21 | use std::fmt; |
| 22 | use std::sync::Arc; |
| 23 | use std::time::Duration; |
| 24 | use tokio::sync::Semaphore; |
| 25 | use tokio::task::JoinSet; |
| 26 | |
| 27 | /// Tool name stamped on failure records produced by the DAG itself. |
| 28 | pub const WORKFLOW_TOOL_NAME: &str = "workflow_task"; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 31 | #[serde(transparent)] |
| 32 | pub struct TaskId(String); |
| 33 | |
| 34 | impl TaskId { |
| 35 | pub fn new(id: impl Into<String>) -> Self { |
| 36 | Self(id.into()) |
| 37 | } |
| 38 | |
| 39 | pub fn as_str(&self) -> &str { |
| 40 | &self.0 |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | impl fmt::Display for TaskId { |
| 45 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 46 | f.write_str(&self.0) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl From<&str> for TaskId { |
| 51 | fn from(s: &str) -> Self { |
| 52 | Self::new(s) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// Build-time errors. A spec that builds is a valid DAG. |
| 57 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 58 | pub enum WorkflowError { |
| 59 | EmptyTaskId, |
| 60 | DuplicateTask(TaskId), |
| 61 | UnknownPredecessor { |
| 62 | task: TaskId, |
| 63 | predecessor: TaskId, |
| 64 | }, |
| 65 | DuplicateEdge { |
| 66 | task: TaskId, |
| 67 | predecessor: TaskId, |
| 68 | }, |
| 69 | SelfDependency(TaskId), |
| 70 | /// One cycle, listed in dependency order. |
| 71 | Cycle(Vec<TaskId>), |
| 72 | InvalidConfig(String), |
| 73 | } |
| 74 | |
| 75 | impl fmt::Display for WorkflowError { |
| 76 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 77 | match self { |
| 78 | Self::EmptyTaskId => write!(f, "task id must not be empty"), |
| 79 | Self::DuplicateTask(t) => write!(f, "duplicate task id: {t}"), |
| 80 | Self::UnknownPredecessor { task, predecessor } => { |
| 81 | write!(f, "task {task} depends on unknown task {predecessor}") |
| 82 | } |
| 83 | Self::DuplicateEdge { task, predecessor } => { |
| 84 | write!(f, "task {task} lists predecessor {predecessor} twice") |
| 85 | } |
| 86 | Self::SelfDependency(t) => write!(f, "task {t} depends on itself"), |
| 87 | Self::Cycle(c) => { |
| 88 | let names: Vec<&str> = c.iter().map(|t| t.as_str()).collect(); |
| 89 | write!(f, "dependency cycle: {}", names.join(" -> ")) |
| 90 | } |
| 91 | Self::InvalidConfig(m) => write!(f, "invalid workflow config: {m}"), |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl std::error::Error for WorkflowError {} |
| 97 | |
| 98 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 99 | #[serde(tag = "state", content = "detail", rename_all = "snake_case")] |
| 100 | pub enum TaskState { |
| 101 | Pending, |
| 102 | Ready, |
| 103 | Running, |
| 104 | WaitingForApproval, |
| 105 | Completed, |
| 106 | Failed(FailureRecord), |
| 107 | Cancelled, |
| 108 | Skipped { |
| 109 | prerequisite: TaskId, |
| 110 | }, |
| 111 | /// Started, then interrupted (timeout or cancel) while its effect |
| 112 | /// certainty was `Uncertain`: not known whether the effect happened. Not |
| 113 | /// terminal: it must be reconciled against the effect authority before |
| 114 | /// anything else happens, and its dependents stay Pending behind it |
| 115 | /// (issue #55). The record says why it was interrupted. |
| 116 | Uncertain(FailureRecord), |
| 117 | } |
| 118 | |
| 119 | impl TaskState { |
| 120 | /// Terminal means the task will never change state again. `Uncertain` is |
| 121 | /// not terminal: reconciliation decides its final state. |
| 122 | pub fn is_terminal(&self) -> bool { |
| 123 | matches!( |
| 124 | self, |
| 125 | Self::Completed | Self::Failed(_) | Self::Cancelled | Self::Skipped { .. } |
| 126 | ) |
| 127 | } |
| 128 | |
| 129 | /// Short stable name, used in events. |
| 130 | pub fn name(&self) -> &'static str { |
| 131 | match self { |
| 132 | Self::Pending => "pending", |
| 133 | Self::Ready => "ready", |
| 134 | Self::Running => "running", |
| 135 | Self::WaitingForApproval => "waiting_for_approval", |
| 136 | Self::Completed => "completed", |
| 137 | Self::Failed(_) => "failed", |
| 138 | Self::Cancelled => "cancelled", |
| 139 | Self::Skipped { .. } => "skipped", |
| 140 | Self::Uncertain(_) => "uncertain", |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// What a task body reports. Approval pending is not success. |
| 146 | #[derive(Debug, Clone)] |
| 147 | pub enum TaskOutcome { |
| 148 | Completed(serde_json::Value), |
| 149 | Failed(ToolFault), |
| 150 | ApprovalPending, |
| 151 | Cancelled, |
| 152 | } |
| 153 | |
| 154 | /// Handed to the task body when it starts. |
| 155 | #[derive(Clone)] |
| 156 | pub struct TaskContext { |
| 157 | pub task_id: TaskId, |
| 158 | pub run_id: RunId, |
| 159 | pub session_id: SessionId, |
| 160 | /// Fires when the workflow is cancelled or its total budget is spent. |
| 161 | pub cancel: CancelToken, |
| 162 | } |
| 163 | |
| 164 | /// Caller-supplied task body. It must route every real effect through the |
| 165 | /// existing gate path; the DAG never authorizes on its behalf. |
| 166 | #[async_trait] |
| 167 | pub trait TaskRunner: Send + Sync { |
| 168 | async fn run(&self, ctx: TaskContext) -> TaskOutcome; |
| 169 | |
| 170 | /// Certainty recorded when the DAG interrupts this task (timeout or |
| 171 | /// cancellation) before it reports. Default is the safe answer. |
| 172 | fn certainty_on_interrupt(&self) -> EffectCertainty { |
| 173 | EffectCertainty::Uncertain |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /// Wraps an async closure as a `TaskRunner`. |
| 178 | pub struct FnRunner<F> { |
| 179 | f: F, |
| 180 | interrupt: EffectCertainty, |
| 181 | } |
| 182 | |
| 183 | pub fn runner_fn<F>(f: F) -> Arc<dyn TaskRunner> |
| 184 | where |
| 185 | F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, |
| 186 | { |
| 187 | Arc::new(FnRunner { |
| 188 | f, |
| 189 | interrupt: EffectCertainty::Uncertain, |
| 190 | }) |
| 191 | } |
| 192 | |
| 193 | /// Like `runner_fn` with an explicit certainty for interruptions. |
| 194 | pub fn runner_fn_with_certainty<F>(f: F, interrupt: EffectCertainty) -> Arc<dyn TaskRunner> |
| 195 | where |
| 196 | F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, |
| 197 | { |
| 198 | Arc::new(FnRunner { f, interrupt }) |
| 199 | } |
| 200 | |
| 201 | #[async_trait] |
| 202 | impl<F> TaskRunner for FnRunner<F> |
| 203 | where |
| 204 | F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, |
| 205 | { |
| 206 | async fn run(&self, ctx: TaskContext) -> TaskOutcome { |
| 207 | (self.f)(ctx).await |
| 208 | } |
| 209 | |
| 210 | fn certainty_on_interrupt(&self) -> EffectCertainty { |
| 211 | self.interrupt |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | struct TaskNode { |
| 216 | id: TaskId, |
| 217 | deps: Vec<TaskId>, |
| 218 | runner: Arc<dyn TaskRunner>, |
| 219 | } |
| 220 | |
| 221 | /// A validated DAG. Insertion order is the deterministic tie break. |
| 222 | pub struct WorkflowSpec { |
| 223 | tasks: Vec<TaskNode>, |
| 224 | } |
| 225 | |
| 226 | impl WorkflowSpec { |
| 227 | pub fn builder() -> WorkflowBuilder { |
| 228 | WorkflowBuilder::default() |
| 229 | } |
| 230 | |
| 231 | pub fn task_ids(&self) -> Vec<TaskId> { |
| 232 | self.tasks.iter().map(|t| t.id.clone()).collect() |
| 233 | } |
| 234 | |
| 235 | /// The prerequisites of `id`, in the order they were listed. |
| 236 | pub fn dependencies(&self, id: &TaskId) -> Option<&[TaskId]> { |
| 237 | self.tasks |
| 238 | .iter() |
| 239 | .find(|t| &t.id == id) |
| 240 | .map(|t| t.deps.as_slice()) |
| 241 | } |
| 242 | |
| 243 | pub fn len(&self) -> usize { |
| 244 | self.tasks.len() |
| 245 | } |
| 246 | |
| 247 | pub fn is_empty(&self) -> bool { |
| 248 | self.tasks.is_empty() |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | #[derive(Default)] |
| 253 | pub struct WorkflowBuilder { |
| 254 | tasks: Vec<TaskNode>, |
| 255 | } |
| 256 | |
| 257 | impl WorkflowBuilder { |
| 258 | /// Predecessors may be added after their dependents (forward references |
| 259 | /// are allowed). `build` validates the whole graph: unknown predecessors, |
| 260 | /// duplicate edges and cycles are all rejected there. |
| 261 | pub fn add_task( |
| 262 | mut self, |
| 263 | id: impl Into<TaskId>, |
| 264 | deps: &[&str], |
| 265 | runner: Arc<dyn TaskRunner>, |
| 266 | ) -> Result<Self, WorkflowError> { |
| 267 | let id = id.into(); |
| 268 | if id.as_str().is_empty() { |
| 269 | return Err(WorkflowError::EmptyTaskId); |
| 270 | } |
| 271 | if self.tasks.iter().any(|t| t.id == id) { |
| 272 | return Err(WorkflowError::DuplicateTask(id)); |
| 273 | } |
| 274 | let mut seen: HashSet<&str> = HashSet::new(); |
| 275 | let mut deps_out = Vec::with_capacity(deps.len()); |
| 276 | for d in deps { |
| 277 | if *d == id.as_str() { |
| 278 | return Err(WorkflowError::SelfDependency(id)); |
| 279 | } |
| 280 | if !seen.insert(d) { |
| 281 | return Err(WorkflowError::DuplicateEdge { |
| 282 | task: id, |
| 283 | predecessor: TaskId::new(*d), |
| 284 | }); |
| 285 | } |
| 286 | deps_out.push(TaskId::new(*d)); |
| 287 | } |
| 288 | self.tasks.push(TaskNode { |
| 289 | id, |
| 290 | deps: deps_out, |
| 291 | runner, |
| 292 | }); |
| 293 | Ok(self) |
| 294 | } |
| 295 | |
| 296 | /// Validates predecessors and rejects cycles. Predecessors may be added |
| 297 | /// after their dependents, so this is where unknown ids and cycles surface. |
| 298 | pub fn build(self) -> Result<WorkflowSpec, WorkflowError> { |
| 299 | let index: HashMap<&TaskId, usize> = self |
| 300 | .tasks |
| 301 | .iter() |
| 302 | .enumerate() |
| 303 | .map(|(i, t)| (&t.id, i)) |
| 304 | .collect(); |
| 305 | for t in &self.tasks { |
| 306 | for d in &t.deps { |
| 307 | if !index.contains_key(d) { |
| 308 | return Err(WorkflowError::UnknownPredecessor { |
| 309 | task: t.id.clone(), |
| 310 | predecessor: d.clone(), |
| 311 | }); |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | // Kahn: whatever cannot be peeled off sits on or behind a cycle. |
| 316 | let mut indegree: Vec<usize> = self.tasks.iter().map(|t| t.deps.len()).collect(); |
| 317 | let mut queue: Vec<usize> = (0..self.tasks.len()) |
| 318 | .filter(|i| indegree[*i] == 0) |
| 319 | .collect(); |
| 320 | let mut peeled = 0; |
| 321 | while let Some(n) = queue.pop() { |
| 322 | peeled += 1; |
| 323 | for (i, t) in self.tasks.iter().enumerate() { |
| 324 | if t.deps.contains(&self.tasks[n].id) { |
| 325 | indegree[i] -= 1; |
| 326 | if indegree[i] == 0 { |
| 327 | queue.push(i); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | if peeled != self.tasks.len() { |
| 333 | return Err(WorkflowError::Cycle(find_cycle( |
| 334 | &self.tasks, |
| 335 | &index, |
| 336 | &indegree, |
| 337 | ))); |
| 338 | } |
| 339 | Ok(WorkflowSpec { tasks: self.tasks }) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | /// Walks predecessor links among the unpeeled nodes until one repeats. |
| 344 | fn find_cycle( |
| 345 | tasks: &[TaskNode], |
| 346 | index: &HashMap<&TaskId, usize>, |
| 347 | indegree: &[usize], |
| 348 | ) -> Vec<TaskId> { |
| 349 | let start = (0..tasks.len()).find(|i| indegree[*i] > 0).unwrap_or(0); |
| 350 | let mut path: Vec<usize> = vec![start]; |
| 351 | let mut cur = start; |
| 352 | loop { |
| 353 | let next = tasks[cur] |
| 354 | .deps |
| 355 | .iter() |
| 356 | .map(|d| index[d]) |
| 357 | .find(|i| indegree[*i] > 0) |
| 358 | .unwrap_or(start); |
| 359 | if let Some(pos) = path.iter().position(|p| *p == next) { |
| 360 | let mut cycle: Vec<TaskId> = path[pos..].iter().map(|i| tasks[*i].id.clone()).collect(); |
| 361 | cycle.reverse(); |
| 362 | return cycle; |
| 363 | } |
| 364 | path.push(next); |
| 365 | cur = next; |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | #[derive(Debug, Clone)] |
| 370 | pub struct WorkflowConfig { |
| 371 | pub run_id: RunId, |
| 372 | pub session_id: SessionId, |
| 373 | /// Upper bound on tasks running at once. Must be at least 1. |
| 374 | pub max_parallel: usize, |
| 375 | pub per_task_timeout: Option<Duration>, |
| 376 | /// Wall-clock cap for the whole workflow. When it elapses the workflow is |
| 377 | /// cancelled like an operator cancel and `budget_exhausted` is set. |
| 378 | pub total_budget: Option<Duration>, |
| 379 | } |
| 380 | |
| 381 | impl WorkflowConfig { |
| 382 | pub fn new(run_id: RunId, session_id: SessionId, max_parallel: usize) -> Self { |
| 383 | Self { |
| 384 | run_id, |
| 385 | session_id, |
| 386 | max_parallel, |
| 387 | per_task_timeout: None, |
| 388 | total_budget: None, |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | /// Digest of a completed task's result. The value itself is not kept here. |
| 394 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 395 | pub struct ResultHandle { |
| 396 | pub digest: String, |
| 397 | } |
| 398 | |
| 399 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 400 | #[serde(rename_all = "snake_case")] |
| 401 | pub enum WorkflowStatus { |
| 402 | /// Every task completed. |
| 403 | Completed, |
| 404 | /// Some task failed, was skipped or cancelled, and nothing waits on a human. |
| 405 | Failed, |
| 406 | /// Cancelled (operator or budget). |
| 407 | Cancelled, |
| 408 | /// At least one task waits for approval; the workflow is not finished. |
| 409 | WaitingForApproval, |
| 410 | } |
| 411 | |
| 412 | /// One transition, in workflow order. `seq` starts at 1. |
| 413 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 414 | pub struct WorkflowEvent { |
| 415 | pub seq: u64, |
| 416 | pub task_id: Option<TaskId>, |
| 417 | pub state: String, |
| 418 | } |
| 419 | |
| 420 | /// Serializable view of the in-memory workflow state. |
| 421 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 422 | pub struct WorkflowSnapshot { |
| 423 | pub run_id: String, |
| 424 | pub last_seq: u64, |
| 425 | pub states: BTreeMap<TaskId, TaskState>, |
| 426 | pub results: BTreeMap<TaskId, ResultHandle>, |
| 427 | } |
| 428 | |
| 429 | #[derive(Debug, Clone)] |
| 430 | pub struct WorkflowReport { |
| 431 | pub status: WorkflowStatus, |
| 432 | pub snapshot: WorkflowSnapshot, |
| 433 | /// Failure records for Failed, Skipped, Cancelled and Uncertain tasks. |
| 434 | pub failures: BTreeMap<TaskId, FailureRecord>, |
| 435 | /// Tasks left non-terminal (waiting for approval, uncertain, or blocked |
| 436 | /// behind either). |
| 437 | pub unfinished: Vec<TaskId>, |
| 438 | /// Pending tasks that wait, directly or through other pending tasks, on |
| 439 | /// an `Uncertain` task, mapped to one uncertain task they wait on. |
| 440 | /// They were neither run nor skipped. |
| 441 | pub blocked_behind_uncertain: BTreeMap<TaskId, TaskId>, |
| 442 | pub events: Vec<WorkflowEvent>, |
| 443 | pub peak_concurrency: usize, |
| 444 | pub budget_exhausted: bool, |
| 445 | } |
| 446 | |
| 447 | struct Ledger { |
| 448 | seq: u64, |
| 449 | states: BTreeMap<TaskId, TaskState>, |
| 450 | results: BTreeMap<TaskId, ResultHandle>, |
| 451 | failures: BTreeMap<TaskId, FailureRecord>, |
| 452 | events: Vec<WorkflowEvent>, |
| 453 | } |
| 454 | |
| 455 | /// The one place a state change is recorded. The sequence number is assigned |
| 456 | /// under the lock together with the state change, so replay order equals |
| 457 | /// transition order. |
| 458 | struct Recorder { |
| 459 | ledger: Mutex<Ledger>, |
| 460 | bus: Option<EventBus>, |
| 461 | run_id: RunId, |
| 462 | session_id: SessionId, |
| 463 | } |
| 464 | |
| 465 | impl Recorder { |
| 466 | fn transition(&self, id: &TaskId, state: TaskState, result: Option<ResultHandle>) -> u64 { |
| 467 | let mut l = self.ledger.lock(); |
| 468 | l.seq += 1; |
| 469 | let seq = l.seq; |
| 470 | let name = state.name(); |
| 471 | let event = self.event_for(seq, id, &state, result.as_ref()); |
| 472 | if let Some(r) = result { |
| 473 | l.results.insert(id.clone(), r); |
| 474 | } |
| 475 | l.states.insert(id.clone(), state); |
| 476 | l.events.push(WorkflowEvent { |
| 477 | seq, |
| 478 | task_id: Some(id.clone()), |
| 479 | state: name.to_string(), |
| 480 | }); |
| 481 | // Publish while holding the lock so bus order equals sequence order. |
| 482 | if let Some(event) = event { |
| 483 | self.publish(event, seq); |
| 484 | } |
| 485 | seq |
| 486 | } |
| 487 | |
| 488 | fn finish(&self, status: WorkflowStatus) { |
| 489 | let mut l = self.ledger.lock(); |
| 490 | l.seq += 1; |
| 491 | let seq = l.seq; |
| 492 | l.events.push(WorkflowEvent { |
| 493 | seq, |
| 494 | task_id: None, |
| 495 | state: "finished".to_string(), |
| 496 | }); |
| 497 | let event = AegisEvent::WorkflowFinished { |
| 498 | run_id: self.run_id.to_string(), |
| 499 | workflow_seq: seq, |
| 500 | status: format!("{status:?}").to_lowercase(), |
| 501 | }; |
| 502 | self.publish(event, seq); |
| 503 | } |
| 504 | |
| 505 | fn note_failure(&self, id: &TaskId, rec: FailureRecord) { |
| 506 | self.ledger.lock().failures.insert(id.clone(), rec); |
| 507 | } |
| 508 | |
| 509 | fn state_of(&self, id: &TaskId) -> TaskState { |
| 510 | self.ledger.lock().states[id].clone() |
| 511 | } |
| 512 | |
| 513 | fn next_failure_seq(&self) -> u64 { |
| 514 | // Failure records share the workflow sequence space; the number is |
| 515 | // only a stable order key, so the next transition's number is used. |
| 516 | self.ledger.lock().seq + 1 |
| 517 | } |
| 518 | |
| 519 | fn publish(&self, event: AegisEvent, seq: u64) { |
| 520 | if let Some(bus) = &self.bus { |
| 521 | let env = EventEnvelope::new( |
| 522 | event, |
| 523 | Some(self.session_id.to_string()), |
| 524 | Some(self.run_id.to_string()), |
| 525 | seq, |
| 526 | ); |
| 527 | // No subscriber is not an error for the workflow. |
| 528 | let _ = bus.publish(env); |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | fn event_for( |
| 533 | &self, |
| 534 | seq: u64, |
| 535 | id: &TaskId, |
| 536 | state: &TaskState, |
| 537 | result: Option<&ResultHandle>, |
| 538 | ) -> Option<AegisEvent> { |
| 539 | let run_id = self.run_id.to_string(); |
| 540 | let task_id = id.to_string(); |
| 541 | Some(match state { |
| 542 | // Pending is the initial state and is never recorded as a |
| 543 | // transition, and the event enum has no variant for it, so no |
| 544 | // bus event exists (the ledger entry is still written). |
| 545 | TaskState::Pending => return None, |
| 546 | TaskState::Ready => AegisEvent::WorkflowTaskReady { |
| 547 | run_id, |
| 548 | workflow_seq: seq, |
| 549 | task_id, |
| 550 | }, |
| 551 | TaskState::Running => AegisEvent::WorkflowTaskStarted { |
| 552 | run_id, |
| 553 | workflow_seq: seq, |
| 554 | task_id, |
| 555 | }, |
| 556 | TaskState::Completed => AegisEvent::WorkflowTaskCompleted { |
| 557 | run_id, |
| 558 | workflow_seq: seq, |
| 559 | task_id, |
| 560 | result_digest: result.map(|r| r.digest.clone()).unwrap_or_default(), |
| 561 | }, |
| 562 | TaskState::WaitingForApproval => AegisEvent::WorkflowTaskWaiting { |
| 563 | run_id, |
| 564 | workflow_seq: seq, |
| 565 | task_id, |
| 566 | }, |
| 567 | TaskState::Failed(rec) => AegisEvent::WorkflowTaskFailed { |
| 568 | run_id, |
| 569 | workflow_seq: seq, |
| 570 | task_id, |
| 571 | failure: rec.clone(), |
| 572 | }, |
| 573 | TaskState::Cancelled => AegisEvent::WorkflowTaskCancelled { |
| 574 | run_id, |
| 575 | workflow_seq: seq, |
| 576 | task_id, |
| 577 | }, |
| 578 | TaskState::Skipped { prerequisite } => AegisEvent::WorkflowTaskSkipped { |
| 579 | run_id, |
| 580 | workflow_seq: seq, |
| 581 | task_id, |
| 582 | prerequisite: prerequisite.to_string(), |
| 583 | }, |
| 584 | // No bus variant yet (issue #55 item 4). Publishing it as Failed |
| 585 | // or Cancelled would be false, so the bus stays silent; the |
| 586 | // ledger event "uncertain" is still written in sequence. |
| 587 | TaskState::Uncertain(_) => return None, |
| 588 | }) |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | enum Finish { |
| 593 | Outcome(TaskOutcome), |
| 594 | TimedOut, |
| 595 | Interrupted, |
| 596 | } |
| 597 | |
| 598 | pub struct WorkflowExecutor { |
| 599 | config: WorkflowConfig, |
| 600 | bus: Option<EventBus>, |
| 601 | cancel: CancelToken, |
| 602 | } |
| 603 | |
| 604 | impl WorkflowExecutor { |
| 605 | pub fn new(config: WorkflowConfig) -> Result<Self, WorkflowError> { |
| 606 | if config.max_parallel == 0 { |
| 607 | return Err(WorkflowError::InvalidConfig( |
| 608 | "max_parallel must be at least 1".into(), |
| 609 | )); |
| 610 | } |
| 611 | Ok(Self { |
| 612 | config, |
| 613 | bus: None, |
| 614 | cancel: CancelToken::new(), |
| 615 | }) |
| 616 | } |
| 617 | |
| 618 | pub fn with_event_bus(mut self, bus: EventBus) -> Self { |
| 619 | self.bus = Some(bus); |
| 620 | self |
| 621 | } |
| 622 | |
| 623 | pub fn with_cancel_token(mut self, cancel: CancelToken) -> Self { |
| 624 | self.cancel = cancel; |
| 625 | self |
| 626 | } |
| 627 | |
| 628 | fn failure( |
| 629 | &self, |
| 630 | rec: &Recorder, |
| 631 | id: &TaskId, |
| 632 | class: FailureClass, |
| 633 | certainty: EffectCertainty, |
| 634 | message: &str, |
| 635 | ) -> FailureRecord { |
| 636 | let now = now_millis(); |
| 637 | FailureRecord::new( |
| 638 | rec.next_failure_seq(), |
| 639 | self.config.run_id.to_string(), |
| 640 | 0, |
| 641 | id.to_string(), |
| 642 | None, |
| 643 | WORKFLOW_TOOL_NAME, |
| 644 | 1, |
| 645 | class, |
| 646 | certainty, |
| 647 | now, |
| 648 | now, |
| 649 | ) |
| 650 | .with_cause("workflow", &scrub_message(message), None) |
| 651 | } |
| 652 | |
| 653 | /// Runs the DAG to quiescence. Never blocks a worker thread: the |
| 654 | /// coordinator awaits, and task bodies run on spawned tasks. |
| 655 | pub async fn run(&self, spec: WorkflowSpec) -> WorkflowReport { |
| 656 | let ids = spec.task_ids(); |
| 657 | let rec = Recorder { |
| 658 | ledger: Mutex::new(Ledger { |
| 659 | seq: 0, |
| 660 | states: ids |
| 661 | .iter() |
| 662 | .map(|i| (i.clone(), TaskState::Pending)) |
| 663 | .collect(), |
| 664 | results: BTreeMap::new(), |
| 665 | failures: BTreeMap::new(), |
| 666 | events: Vec::new(), |
| 667 | }), |
| 668 | bus: self.bus.clone(), |
| 669 | run_id: self.config.run_id.clone(), |
| 670 | session_id: self.config.session_id.clone(), |
| 671 | }; |
| 672 | let nodes: HashMap<TaskId, &TaskNode> = |
| 673 | spec.tasks.iter().map(|t| (t.id.clone(), t)).collect(); |
| 674 | let permits = Arc::new(Semaphore::new(self.config.max_parallel)); |
| 675 | let mut running: JoinSet<(TaskId, Finish)> = JoinSet::new(); |
| 676 | let mut by_join_id: HashMap<tokio::task::Id, TaskId> = HashMap::new(); |
| 677 | let mut live = 0usize; |
| 678 | let mut peak = 0usize; |
| 679 | // The executor never triggers the caller's token. Budget expiry and |
| 680 | // observed caller cancels both trip this run-local token instead. |
| 681 | let run_cancel = CancelToken::new(); |
| 682 | let mut cancel_seen = false; |
| 683 | let mut budget_exhausted = false; |
| 684 | let deadline = self |
| 685 | .config |
| 686 | .total_budget |
| 687 | .map(|d| tokio::time::Instant::now() + d); |
| 688 | |
| 689 | 'outer: loop { |
| 690 | // Deadline first: no task may start once the budget is spent. |
| 691 | if !budget_exhausted && deadline.is_some_and(|d| tokio::time::Instant::now() >= d) { |
| 692 | budget_exhausted = true; |
| 693 | run_cancel.cancel(); |
| 694 | } |
| 695 | if self.cancel.is_cancelled() { |
| 696 | run_cancel.cancel(); |
| 697 | } |
| 698 | if !cancel_seen && run_cancel.is_cancelled() { |
| 699 | cancel_seen = true; |
| 700 | self.cancel_open(&rec, &ids, &nodes); |
| 701 | } |
| 702 | |
| 703 | if !cancel_seen { |
| 704 | self.propagate(&ids, &nodes, &rec); |
| 705 | // Start ready tasks in insertion order while permits last. |
| 706 | for id in &ids { |
| 707 | if rec.state_of(id) != TaskState::Ready { |
| 708 | continue; |
| 709 | } |
| 710 | // Re-check right before starting: cancel or an expired |
| 711 | // budget restarts the pass, which cancels what is left. |
| 712 | if self.cancel.is_cancelled() |
| 713 | || run_cancel.is_cancelled() |
| 714 | || deadline.is_some_and(|d| tokio::time::Instant::now() >= d) |
| 715 | { |
| 716 | continue 'outer; |
| 717 | } |
| 718 | let Ok(permit) = permits.clone().try_acquire_owned() else { |
| 719 | break; |
| 720 | }; |
| 721 | rec.transition(id, TaskState::Running, None); |
| 722 | live += 1; |
| 723 | peak = peak.max(self.config.max_parallel - permits.available_permits()); |
| 724 | let node = nodes[id]; |
| 725 | let runner = node.runner.clone(); |
| 726 | let ctx = TaskContext { |
| 727 | task_id: id.clone(), |
| 728 | run_id: self.config.run_id.clone(), |
| 729 | session_id: self.config.session_id.clone(), |
| 730 | cancel: run_cancel.clone(), |
| 731 | }; |
| 732 | let cancel = run_cancel.clone(); |
| 733 | let timeout = self.config.per_task_timeout; |
| 734 | let tid = id.clone(); |
| 735 | let handle = running.spawn(async move { |
| 736 | let _permit = permit; |
| 737 | let body = runner.run(ctx); |
| 738 | let finish = tokio::select! { |
| 739 | biased; |
| 740 | _ = cancel.cancelled() => Finish::Interrupted, |
| 741 | f = async { |
| 742 | match timeout { |
| 743 | Some(d) => match tokio::time::timeout(d, body).await { |
| 744 | Ok(o) => Finish::Outcome(o), |
| 745 | Err(_) => Finish::TimedOut, |
| 746 | }, |
| 747 | None => Finish::Outcome(body.await), |
| 748 | } |
| 749 | } => f, |
| 750 | }; |
| 751 | (tid, finish) |
| 752 | }); |
| 753 | by_join_id.insert(handle.id(), id.clone()); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | if live == 0 { |
| 758 | break; |
| 759 | } |
| 760 | |
| 761 | let joined = tokio::select! { |
| 762 | biased; |
| 763 | _ = self.cancel.cancelled(), if !cancel_seen => { |
| 764 | run_cancel.cancel(); |
| 765 | continue; |
| 766 | } |
| 767 | _ = async { |
| 768 | match deadline { |
| 769 | Some(d) => tokio::time::sleep_until(d).await, |
| 770 | None => std::future::pending().await, |
| 771 | } |
| 772 | }, if !budget_exhausted => { |
| 773 | budget_exhausted = true; |
| 774 | run_cancel.cancel(); |
| 775 | continue; |
| 776 | } |
| 777 | j = running.join_next_with_id() => j, |
| 778 | }; |
| 779 | let Some(joined) = joined else { break }; |
| 780 | live -= 1; |
| 781 | let (jid, result) = match joined { |
| 782 | Ok((jid, r)) => (jid, Ok(r)), |
| 783 | Err(e) => (e.id(), Err(e)), |
| 784 | }; |
| 785 | let tid = by_join_id.remove(&jid).expect("tracked join id"); |
| 786 | let runner = nodes[&tid].runner.clone(); |
| 787 | let interrupt = runner.certainty_on_interrupt(); |
| 788 | let finish = match result { |
| 789 | Ok((_, f)) => f, |
| 790 | Err(_) => { |
| 791 | // A panicking body: the effect may have happened. |
| 792 | let f = self.failure( |
| 793 | &rec, |
| 794 | &tid, |
| 795 | FailureClass::Failed, |
| 796 | EffectCertainty::Uncertain, |
| 797 | "task body panicked", |
| 798 | ); |
| 799 | rec.note_failure(&tid, f.clone()); |
| 800 | rec.transition(&tid, TaskState::Failed(f), None); |
| 801 | continue; |
| 802 | } |
| 803 | }; |
| 804 | self.settle(&rec, &tid, finish, interrupt); |
| 805 | } |
| 806 | |
| 807 | if cancel_seen { |
| 808 | // A task that reported ApprovalPending after the cancel was seen |
| 809 | // is settled here, so Cancelled never lists unfinished tasks. |
| 810 | self.cancel_open(&rec, &ids, &nodes); |
| 811 | } |
| 812 | let blocked = blocked_behind_uncertain(&rec, &ids, &nodes); |
| 813 | self.report(rec, ids, peak, budget_exhausted, cancel_seen, blocked) |
| 814 | } |
| 815 | |
| 816 | /// Moves every non-terminal, non-running task to Cancelled. A task |
| 817 | /// waiting for approval is cancelled too: nothing will ever resume it. |
| 818 | fn cancel_open(&self, rec: &Recorder, ids: &[TaskId], nodes: &HashMap<TaskId, &TaskNode>) { |
| 819 | for id in ids { |
| 820 | let (message, certainty) = match rec.state_of(id) { |
| 821 | TaskState::Pending | TaskState::Ready => { |
| 822 | ("workflow cancelled before start", EffectCertainty::NoEffect) |
| 823 | } |
| 824 | TaskState::WaitingForApproval => ( |
| 825 | "workflow cancelled while waiting for approval", |
| 826 | nodes[id].runner.certainty_on_interrupt(), |
| 827 | ), |
| 828 | _ => continue, |
| 829 | }; |
| 830 | let f = self.failure(rec, id, FailureClass::Cancelled, certainty, message); |
| 831 | rec.note_failure(id, f); |
| 832 | rec.transition(id, TaskState::Cancelled, None); |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | /// Unblocks dependents whose prerequisites all completed, and skips |
| 837 | /// dependents of any prerequisite that ended without success. A task that |
| 838 | /// waits for approval is not terminal, so its dependents stay Pending. |
| 839 | fn propagate(&self, ids: &[TaskId], nodes: &HashMap<TaskId, &TaskNode>, rec: &Recorder) { |
| 840 | loop { |
| 841 | let mut changed = false; |
| 842 | for id in ids { |
| 843 | if rec.state_of(id) != TaskState::Pending { |
| 844 | continue; |
| 845 | } |
| 846 | let deps = &nodes[id].deps; |
| 847 | let bad = deps.iter().find(|d| { |
| 848 | matches!( |
| 849 | rec.state_of(d), |
| 850 | TaskState::Failed(_) | TaskState::Cancelled | TaskState::Skipped { .. } |
| 851 | ) |
| 852 | }); |
| 853 | if let Some(bad) = bad { |
| 854 | let f = self.failure( |
| 855 | rec, |
| 856 | id, |
| 857 | FailureClass::Rejected, |
| 858 | EffectCertainty::NoEffect, |
| 859 | &format!("prerequisite failed: {bad}"), |
| 860 | ); |
| 861 | rec.note_failure(id, f); |
| 862 | rec.transition( |
| 863 | id, |
| 864 | TaskState::Skipped { |
| 865 | prerequisite: bad.clone(), |
| 866 | }, |
| 867 | None, |
| 868 | ); |
| 869 | changed = true; |
| 870 | } else if deps.iter().all(|d| rec.state_of(d) == TaskState::Completed) { |
| 871 | rec.transition(id, TaskState::Ready, None); |
| 872 | changed = true; |
| 873 | } |
| 874 | } |
| 875 | if !changed { |
| 876 | break; |
| 877 | } |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | fn settle(&self, rec: &Recorder, id: &TaskId, finish: Finish, interrupt: EffectCertainty) { |
| 882 | match finish { |
| 883 | Finish::Outcome(TaskOutcome::Completed(v)) => { |
| 884 | let handle = ResultHandle { |
| 885 | digest: payload_digest(&v), |
| 886 | }; |
| 887 | rec.transition(id, TaskState::Completed, Some(handle)); |
| 888 | } |
| 889 | Finish::Outcome(TaskOutcome::Failed(fault)) => { |
| 890 | let f = self.failure(rec, id, fault.class, fault.certainty, &fault.message); |
| 891 | rec.note_failure(id, f.clone()); |
| 892 | rec.transition(id, TaskState::Failed(f), None); |
| 893 | } |
| 894 | Finish::Outcome(TaskOutcome::ApprovalPending) => { |
| 895 | rec.transition(id, TaskState::WaitingForApproval, None); |
| 896 | } |
| 897 | Finish::Outcome(TaskOutcome::Cancelled) | Finish::Interrupted => { |
| 898 | let f = self.failure( |
| 899 | rec, |
| 900 | id, |
| 901 | FailureClass::Cancelled, |
| 902 | interrupt, |
| 903 | "task cancelled while running", |
| 904 | ); |
| 905 | rec.note_failure(id, f.clone()); |
| 906 | if interrupt == EffectCertainty::Uncertain { |
| 907 | rec.transition(id, TaskState::Uncertain(f), None); |
| 908 | } else { |
| 909 | rec.transition(id, TaskState::Cancelled, None); |
| 910 | } |
| 911 | } |
| 912 | Finish::TimedOut => { |
| 913 | let f = self.failure( |
| 914 | rec, |
| 915 | id, |
| 916 | FailureClass::Timeout, |
| 917 | interrupt, |
| 918 | "per-task timeout elapsed", |
| 919 | ); |
| 920 | rec.note_failure(id, f.clone()); |
| 921 | if interrupt == EffectCertainty::Uncertain { |
| 922 | rec.transition(id, TaskState::Uncertain(f), None); |
| 923 | } else { |
| 924 | rec.transition(id, TaskState::Failed(f), None); |
| 925 | } |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | fn report( |
| 931 | &self, |
| 932 | rec: Recorder, |
| 933 | ids: Vec<TaskId>, |
| 934 | peak: usize, |
| 935 | budget_exhausted: bool, |
| 936 | cancelled: bool, |
| 937 | blocked_behind_uncertain: BTreeMap<TaskId, TaskId>, |
| 938 | ) -> WorkflowReport { |
| 939 | let (unfinished, any_waiting, all_done) = { |
| 940 | let l = rec.ledger.lock(); |
| 941 | let unfinished: Vec<TaskId> = ids |
| 942 | .iter() |
| 943 | .filter(|i| !l.states[*i].is_terminal()) |
| 944 | .cloned() |
| 945 | .collect(); |
| 946 | let any_waiting = l |
| 947 | .states |
| 948 | .values() |
| 949 | .any(|s| matches!(s, TaskState::WaitingForApproval)); |
| 950 | let all_done = l.states.values().all(|s| matches!(s, TaskState::Completed)); |
| 951 | (unfinished, any_waiting, all_done) |
| 952 | }; |
| 953 | let status = if cancelled { |
| 954 | WorkflowStatus::Cancelled |
| 955 | } else if any_waiting { |
| 956 | WorkflowStatus::WaitingForApproval |
| 957 | } else if all_done { |
| 958 | WorkflowStatus::Completed |
| 959 | } else { |
| 960 | WorkflowStatus::Failed |
| 961 | }; |
| 962 | rec.finish(status); |
| 963 | let l = rec.ledger.lock(); |
| 964 | WorkflowReport { |
| 965 | status, |
| 966 | snapshot: WorkflowSnapshot { |
| 967 | run_id: self.config.run_id.to_string(), |
| 968 | last_seq: l.seq, |
| 969 | states: l.states.clone(), |
| 970 | results: l.results.clone(), |
| 971 | }, |
| 972 | failures: l.failures.clone(), |
| 973 | unfinished, |
| 974 | blocked_behind_uncertain, |
| 975 | events: l.events.clone(), |
| 976 | peak_concurrency: peak, |
| 977 | budget_exhausted, |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | /// Pending tasks that wait on an `Uncertain` task, directly or through other |
| 983 | /// pending tasks. Each maps to one uncertain task it waits on (several may |
| 984 | /// apply; the first one found is named). |
| 985 | fn blocked_behind_uncertain( |
| 986 | rec: &Recorder, |
| 987 | ids: &[TaskId], |
| 988 | nodes: &HashMap<TaskId, &TaskNode>, |
| 989 | ) -> BTreeMap<TaskId, TaskId> { |
| 990 | let mut blocked: BTreeMap<TaskId, TaskId> = BTreeMap::new(); |
| 991 | loop { |
| 992 | let mut changed = false; |
| 993 | for id in ids { |
| 994 | if blocked.contains_key(id) || rec.state_of(id) != TaskState::Pending { |
| 995 | continue; |
| 996 | } |
| 997 | let root = nodes[id].deps.iter().find_map(|d| match rec.state_of(d) { |
| 998 | TaskState::Uncertain(_) => Some(d.clone()), |
| 999 | _ => blocked.get(d).cloned(), |
| 1000 | }); |
| 1001 | if let Some(root) = root { |
| 1002 | blocked.insert(id.clone(), root); |
| 1003 | changed = true; |
| 1004 | } |
| 1005 | } |
| 1006 | if !changed { |
| 1007 | return blocked; |
| 1008 | } |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | /// Error text from runners and engines goes into Workflow events and reports, |
| 1013 | /// so it is cut to the cause limit before it is recorded. Runners that know |
| 1014 | /// their payload should also call `redact_payload_echoes` first (the agent |
| 1015 | /// adapter does). |
| 1016 | fn scrub_message(message: &str) -> String { |
| 1017 | truncate_bytes(message, MAX_CAUSE_MESSAGE_BYTES) |
| 1018 | } |
| 1019 | |
| 1020 | /// Maps a finished `AgentEngine::execute_task` result onto a task outcome. |
| 1021 | /// This is the whole adapter seam: the agent already gates every tool call, |
| 1022 | /// so the DAG adds no authority here. |
| 1023 | pub fn agent_outcome(result: &crate::agent::AgentExecutionResult) -> TaskOutcome { |
| 1024 | if let Some(fault) = crate::agent::terminal_tool_failure(&result.steps) { |
| 1025 | return if fault.class == FailureClass::ApprovalPending { |
| 1026 | TaskOutcome::ApprovalPending |
| 1027 | } else { |
| 1028 | TaskOutcome::Failed(fault) |
| 1029 | }; |
| 1030 | } |
| 1031 | if result.completed { |
| 1032 | TaskOutcome::Completed(serde_json::json!({ "final_response": result.final_response })) |
| 1033 | } else { |
| 1034 | // Ran out of turns: tools may have acted, so claim no certainty. |
| 1035 | TaskOutcome::Failed(ToolFault::new( |
| 1036 | FailureClass::Failed, |
| 1037 | EffectCertainty::Uncertain, |
| 1038 | "agent did not complete within its turn budget", |
| 1039 | )) |
| 1040 | } |
| 1041 | } |
| 1042 | |
| 1043 | /// Runs one `AgentEngine::execute_task` call as a workflow task. |
| 1044 | pub struct AgentTaskRunner { |
| 1045 | pub engine: Arc<crate::agent::AgentEngine>, |
| 1046 | pub goal: String, |
| 1047 | pub max_turns: usize, |
| 1048 | } |
| 1049 | |
| 1050 | #[async_trait] |
| 1051 | impl TaskRunner for AgentTaskRunner { |
| 1052 | async fn run(&self, _ctx: TaskContext) -> TaskOutcome { |
| 1053 | match self |
| 1054 | .engine |
| 1055 | .execute_task(&self.goal, None, self.max_turns) |
| 1056 | .await |
| 1057 | { |
| 1058 | Ok(r) => agent_outcome(&r), |
| 1059 | Err(e) => TaskOutcome::Failed(ToolFault::new( |
| 1060 | FailureClass::Failed, |
| 1061 | EffectCertainty::Uncertain, |
| 1062 | redact_payload_echoes(&e.to_string(), &serde_json::json!({ "goal": self.goal })), |
| 1063 | )), |
| 1064 | } |
| 1065 | } |
| 1066 | } |