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 / recovery.rs
| 1 | //! Rebuild a workflow's state after a restart by asking the authoritative |
| 2 | //! records (G3, issue #56; authorities named in `docs/DELEGATED-DAG.md`). |
| 3 | //! |
| 4 | //! AEGIS keeps only pointers: per task, the effect intent id, the grant id, |
| 5 | //! the receipt digest and, for a no-effect task, its result digest. The |
| 6 | //! state of each task is derived from what the authorities say now, never |
| 7 | //! from a saved copy. Anything not known stays `Uncertain` and is never run |
| 8 | //! again; a missing pointer or an unreachable authority is a named refusal, |
| 9 | //! never a silent fresh start. |
| 10 | //! |
| 11 | //! First cut: the lookup is a trait with in-memory fakes in tests. There is |
| 12 | //! no storage, no sovereign-core client and no network here. The real |
| 13 | //! adapter reads the sovereign-core effect ledger |
| 14 | //! (`crates/aien-runtime/src/effects.rs`) and needs |
| 15 | //! aien-dev/aien-sovereign-core-mv#379; this module does not reimplement it. |
| 16 | |
| 17 | use crate::failure::{EffectCertainty, FailureClass, FailureRecord}; |
| 18 | use crate::orchestration::workflow::{ |
| 19 | ResultHandle, TaskId, TaskState, WorkflowSnapshot, WorkflowSpec, |
| 20 | }; |
| 21 | use async_trait::async_trait; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use sha2::{Digest, Sha256}; |
| 24 | use std::collections::BTreeMap; |
| 25 | use std::fmt; |
| 26 | |
| 27 | /// Tool name stamped on failure records produced by a rebuild. |
| 28 | pub const RECOVERY_TOOL_NAME: &str = "workflow_recovery"; |
| 29 | |
| 30 | macro_rules! opaque_id { |
| 31 | ($(#[$m:meta])* $name:ident) => { |
| 32 | $(#[$m])* |
| 33 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 34 | #[serde(transparent)] |
| 35 | pub struct $name(String); |
| 36 | |
| 37 | impl $name { |
| 38 | pub fn new(id: impl Into<String>) -> Self { |
| 39 | Self(id.into()) |
| 40 | } |
| 41 | |
| 42 | pub fn as_str(&self) -> &str { |
| 43 | &self.0 |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | impl fmt::Display for $name { |
| 48 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 49 | f.write_str(&self.0) |
| 50 | } |
| 51 | } |
| 52 | }; |
| 53 | } |
| 54 | |
| 55 | opaque_id!( |
| 56 | /// Names one effect intent record in the sovereign-core effect ledger. |
| 57 | EffectIntentId |
| 58 | ); |
| 59 | opaque_id!( |
| 60 | /// Names one grant at the Spark approval desk. Carries no authority. |
| 61 | GrantId |
| 62 | ); |
| 63 | opaque_id!( |
| 64 | /// Digest of a receipt held by the authority. |
| 65 | ReceiptDigest |
| 66 | ); |
| 67 | |
| 68 | /// Effect state as the sovereign-core effect ledger names it. |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 70 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] |
| 71 | pub enum EffectState { |
| 72 | Open, |
| 73 | Done, |
| 74 | NotDone, |
| 75 | Unresolved, |
| 76 | } |
| 77 | |
| 78 | impl EffectState { |
| 79 | pub fn name(self) -> &'static str { |
| 80 | match self { |
| 81 | Self::Open => "OPEN", |
| 82 | Self::Done => "DONE", |
| 83 | Self::NotDone => "NOT_DONE", |
| 84 | Self::Unresolved => "UNRESOLVED", |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | /// What the desk says about a grant now. |
| 90 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 91 | #[serde(rename_all = "snake_case")] |
| 92 | pub enum GrantStatus { |
| 93 | /// Unspent and still valid. |
| 94 | Available, |
| 95 | /// Spent on an effect intent. |
| 96 | Spent, |
| 97 | Expired, |
| 98 | Revoked, |
| 99 | } |
| 100 | |
| 101 | /// One grant as the desk reports it. |
| 102 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 103 | pub struct GrantRecord { |
| 104 | pub status: GrantStatus, |
| 105 | /// The effect intent this grant opened, when the desk can name it. |
| 106 | pub intent: Option<EffectIntentId>, |
| 107 | } |
| 108 | |
| 109 | /// The work class of a task, as PST1 `effect_class` names it. |
| 110 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 111 | #[serde(rename_all = "snake_case")] |
| 112 | pub enum EffectClass { |
| 113 | /// Touches nothing outside; safe to run again. |
| 114 | None, |
| 115 | /// Computes only; safe to run again. |
| 116 | Compute, |
| 117 | /// Changes something in the world; needs a grant. |
| 118 | Effect, |
| 119 | } |
| 120 | |
| 121 | /// The pointers AEGIS keeps for one task (DELEGATED-DAG.md section 2). |
| 122 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 123 | pub struct TaskPointers { |
| 124 | pub effect_class: EffectClass, |
| 125 | pub effect_intent: Option<EffectIntentId>, |
| 126 | pub grant: Option<GrantId>, |
| 127 | pub receipt: Option<ReceiptDigest>, |
| 128 | /// Digest of a no-effect task's result, once it finished. |
| 129 | pub result_digest: Option<String>, |
| 130 | } |
| 131 | |
| 132 | impl TaskPointers { |
| 133 | /// A no-effect task that has not finished. |
| 134 | pub fn no_effect() -> Self { |
| 135 | Self { |
| 136 | effect_class: EffectClass::None, |
| 137 | effect_intent: None, |
| 138 | grant: None, |
| 139 | receipt: None, |
| 140 | result_digest: None, |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// Every pointer AEGIS keeps for one workflow. |
| 146 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 147 | pub struct StoredPointers { |
| 148 | pub run_id: String, |
| 149 | /// Copied from the Pi; never minted here. |
| 150 | pub cause_id: String, |
| 151 | pub objective_id: String, |
| 152 | /// `spec_digest` of the spec this workflow was started with. |
| 153 | pub spec_digest: String, |
| 154 | pub tasks: BTreeMap<TaskId, TaskPointers>, |
| 155 | } |
| 156 | |
| 157 | /// The lookup could not reach its authority. |
| 158 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 159 | pub struct LookupError { |
| 160 | pub detail: String, |
| 161 | } |
| 162 | |
| 163 | impl LookupError { |
| 164 | pub fn new(detail: impl Into<String>) -> Self { |
| 165 | Self { |
| 166 | detail: detail.into(), |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Read-only questions to the authorities. Implementations must not |
| 172 | /// change anything they read. |
| 173 | #[async_trait] |
| 174 | pub trait AuthorityLookup: Send + Sync { |
| 175 | /// `Ok(None)`: the ledger holds no such intent. |
| 176 | async fn effect_state( |
| 177 | &self, |
| 178 | intent: &EffectIntentId, |
| 179 | ) -> Result<Option<EffectState>, LookupError>; |
| 180 | /// `Ok(None)`: the desk never issued this grant. |
| 181 | async fn grant(&self, grant: &GrantId) -> Result<Option<GrantRecord>, LookupError>; |
| 182 | async fn receipt_present(&self, receipt: &ReceiptDigest) -> Result<bool, LookupError>; |
| 183 | } |
| 184 | |
| 185 | /// Why a rebuild was refused. Nothing is started after a refusal. |
| 186 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 187 | pub enum RecoveryRefusal { |
| 188 | /// The spec handed in is not the one the pointers were stored for. |
| 189 | SpecMismatch { |
| 190 | stored: String, |
| 191 | rebuilt: String, |
| 192 | }, |
| 193 | /// A task of the spec has no pointers, or an effect task has no grant. |
| 194 | MissingPointers(TaskId), |
| 195 | /// Pointers name a task the spec does not have. |
| 196 | UnknownTaskPointer(TaskId), |
| 197 | LookupUnavailable { |
| 198 | task: TaskId, |
| 199 | detail: String, |
| 200 | }, |
| 201 | /// A pointer names an effect intent the ledger does not hold. |
| 202 | EffectRecordMissing { |
| 203 | task: TaskId, |
| 204 | intent: EffectIntentId, |
| 205 | }, |
| 206 | /// A pointer names a grant the desk never issued. |
| 207 | GrantUnknown { |
| 208 | task: TaskId, |
| 209 | grant: GrantId, |
| 210 | }, |
| 211 | /// The stored intent and the desk's intent for the grant differ. |
| 212 | IntentMismatch { |
| 213 | task: TaskId, |
| 214 | stored: EffectIntentId, |
| 215 | desk: EffectIntentId, |
| 216 | }, |
| 217 | /// The ledger says DONE but no receipt exists for it. |
| 218 | DoneWithoutReceipt { |
| 219 | task: TaskId, |
| 220 | intent: EffectIntentId, |
| 221 | }, |
| 222 | } |
| 223 | |
| 224 | impl RecoveryRefusal { |
| 225 | pub fn name(&self) -> &'static str { |
| 226 | match self { |
| 227 | Self::SpecMismatch { .. } => "RECOVERY_SPEC_MISMATCH", |
| 228 | Self::MissingPointers(_) => "RECOVERY_MISSING_POINTERS", |
| 229 | Self::UnknownTaskPointer(_) => "RECOVERY_UNKNOWN_TASK_POINTER", |
| 230 | Self::LookupUnavailable { .. } => "RECOVERY_LOOKUP_UNAVAILABLE", |
| 231 | Self::EffectRecordMissing { .. } => "RECOVERY_EFFECT_RECORD_MISSING", |
| 232 | Self::GrantUnknown { .. } => "RECOVERY_GRANT_UNKNOWN", |
| 233 | Self::IntentMismatch { .. } => "RECOVERY_INTENT_MISMATCH", |
| 234 | Self::DoneWithoutReceipt { .. } => "RECOVERY_DONE_WITHOUT_RECEIPT", |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | impl fmt::Display for RecoveryRefusal { |
| 240 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 241 | write!(f, "{}: {self:?}", self.name()) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | impl std::error::Error for RecoveryRefusal {} |
| 246 | |
| 247 | /// SHA-256 over the task ids and their edges, each sorted, so insertion |
| 248 | /// order does not matter and any changed edge does. |
| 249 | pub fn spec_digest(spec: &WorkflowSpec) -> String { |
| 250 | let mut lines: Vec<String> = spec |
| 251 | .task_ids() |
| 252 | .into_iter() |
| 253 | .map(|id| { |
| 254 | let mut deps: Vec<&str> = spec |
| 255 | .dependencies(&id) |
| 256 | .unwrap_or_default() |
| 257 | .iter() |
| 258 | .map(|d| d.as_str()) |
| 259 | .collect(); |
| 260 | deps.sort_unstable(); |
| 261 | format!("{}\t{}\n", id.as_str(), deps.join(",")) |
| 262 | }) |
| 263 | .collect(); |
| 264 | lines.sort_unstable(); |
| 265 | let digest = Sha256::digest(lines.concat().as_bytes()); |
| 266 | let mut out = String::from("sha256:"); |
| 267 | for b in digest { |
| 268 | out.push_str(&format!("{b:02x}")); |
| 269 | } |
| 270 | out |
| 271 | } |
| 272 | |
| 273 | /// What the records alone say about one task, before dependencies. |
| 274 | enum Derived { |
| 275 | Done, |
| 276 | /// Never finished and safe to start (no effect, or a valid grant). |
| 277 | Runnable, |
| 278 | /// Needs a grant that is still valid or newly issued. |
| 279 | NeedsGrant, |
| 280 | Uncertain(String), |
| 281 | } |
| 282 | |
| 283 | /// Rebuilds the snapshot from the pointers and the authorities. Pure: the |
| 284 | /// same records give the same snapshot (timestamps in records are 0). No |
| 285 | /// task body is ever called. |
| 286 | pub async fn rebuild( |
| 287 | spec: &WorkflowSpec, |
| 288 | pointers: &StoredPointers, |
| 289 | lookup: &dyn AuthorityLookup, |
| 290 | ) -> Result<WorkflowSnapshot, RecoveryRefusal> { |
| 291 | let rebuilt = spec_digest(spec); |
| 292 | if rebuilt != pointers.spec_digest { |
| 293 | return Err(RecoveryRefusal::SpecMismatch { |
| 294 | stored: pointers.spec_digest.clone(), |
| 295 | rebuilt, |
| 296 | }); |
| 297 | } |
| 298 | let ids = spec.task_ids(); |
| 299 | if let Some(id) = ids.iter().find(|i| !pointers.tasks.contains_key(*i)) { |
| 300 | return Err(RecoveryRefusal::MissingPointers(id.clone())); |
| 301 | } |
| 302 | if let Some(id) = pointers.tasks.keys().find(|k| !ids.contains(k)) { |
| 303 | return Err(RecoveryRefusal::UnknownTaskPointer(id.clone())); |
| 304 | } |
| 305 | |
| 306 | let mut derived: BTreeMap<TaskId, Derived> = BTreeMap::new(); |
| 307 | let mut results: BTreeMap<TaskId, ResultHandle> = BTreeMap::new(); |
| 308 | for id in &ids { |
| 309 | let p = &pointers.tasks[id]; |
| 310 | let d = match p.effect_class { |
| 311 | EffectClass::None | EffectClass::Compute => match &p.result_digest { |
| 312 | Some(digest) => { |
| 313 | results.insert( |
| 314 | id.clone(), |
| 315 | ResultHandle { |
| 316 | digest: digest.clone(), |
| 317 | }, |
| 318 | ); |
| 319 | Derived::Done |
| 320 | } |
| 321 | None => Derived::Runnable, |
| 322 | }, |
| 323 | EffectClass::Effect => derive_effect(id, p, lookup).await?, |
| 324 | }; |
| 325 | derived.insert(id.clone(), d); |
| 326 | } |
| 327 | |
| 328 | let mut states: BTreeMap<TaskId, TaskState> = BTreeMap::new(); |
| 329 | for id in &ids { |
| 330 | let deps_done = spec |
| 331 | .dependencies(id) |
| 332 | .unwrap_or_default() |
| 333 | .iter() |
| 334 | .all(|d| matches!(derived[d], Derived::Done)); |
| 335 | let state = match &derived[id] { |
| 336 | Derived::Done => TaskState::Completed, |
| 337 | Derived::Uncertain(why) => { |
| 338 | TaskState::Uncertain(uncertain_record(&pointers.run_id, id, why)) |
| 339 | } |
| 340 | Derived::Runnable if deps_done => TaskState::Ready, |
| 341 | Derived::NeedsGrant if deps_done => TaskState::WaitingForApproval, |
| 342 | Derived::Runnable | Derived::NeedsGrant => TaskState::Pending, |
| 343 | }; |
| 344 | states.insert(id.clone(), state); |
| 345 | } |
| 346 | Ok(WorkflowSnapshot { |
| 347 | run_id: pointers.run_id.clone(), |
| 348 | last_seq: 0, |
| 349 | states, |
| 350 | results, |
| 351 | }) |
| 352 | } |
| 353 | |
| 354 | async fn derive_effect( |
| 355 | id: &TaskId, |
| 356 | p: &TaskPointers, |
| 357 | lookup: &dyn AuthorityLookup, |
| 358 | ) -> Result<Derived, RecoveryRefusal> { |
| 359 | let unavailable = |e: LookupError| RecoveryRefusal::LookupUnavailable { |
| 360 | task: id.clone(), |
| 361 | detail: e.detail, |
| 362 | }; |
| 363 | let grant_id = p |
| 364 | .grant |
| 365 | .as_ref() |
| 366 | .ok_or_else(|| RecoveryRefusal::MissingPointers(id.clone()))?; |
| 367 | let grant = lookup |
| 368 | .grant(grant_id) |
| 369 | .await |
| 370 | .map_err(unavailable)? |
| 371 | .ok_or_else(|| RecoveryRefusal::GrantUnknown { |
| 372 | task: id.clone(), |
| 373 | grant: grant_id.clone(), |
| 374 | })?; |
| 375 | let intent = match (&p.effect_intent, &grant.intent) { |
| 376 | (Some(stored), Some(desk)) if stored != desk => { |
| 377 | return Err(RecoveryRefusal::IntentMismatch { |
| 378 | task: id.clone(), |
| 379 | stored: stored.clone(), |
| 380 | desk: desk.clone(), |
| 381 | }) |
| 382 | } |
| 383 | (Some(stored), _) => Some(stored.clone()), |
| 384 | (None, desk) => desk.clone(), |
| 385 | }; |
| 386 | let Some(intent) = intent else { |
| 387 | return Ok(match grant.status { |
| 388 | GrantStatus::Available => Derived::Runnable, |
| 389 | // Spent, but nobody can name the effect: it may have happened. |
| 390 | GrantStatus::Spent => { |
| 391 | Derived::Uncertain("grant spent; no effect intent is named".into()) |
| 392 | } |
| 393 | GrantStatus::Expired | GrantStatus::Revoked => Derived::NeedsGrant, |
| 394 | }); |
| 395 | }; |
| 396 | let state = lookup |
| 397 | .effect_state(&intent) |
| 398 | .await |
| 399 | .map_err(unavailable)? |
| 400 | .ok_or_else(|| RecoveryRefusal::EffectRecordMissing { |
| 401 | task: id.clone(), |
| 402 | intent: intent.clone(), |
| 403 | })?; |
| 404 | Ok(match state { |
| 405 | EffectState::Done => { |
| 406 | let done_without_receipt = || RecoveryRefusal::DoneWithoutReceipt { |
| 407 | task: id.clone(), |
| 408 | intent: intent.clone(), |
| 409 | }; |
| 410 | let receipt = p.receipt.as_ref().ok_or_else(done_without_receipt)?; |
| 411 | if !lookup.receipt_present(receipt).await.map_err(unavailable)? { |
| 412 | return Err(done_without_receipt()); |
| 413 | } |
| 414 | Derived::Done |
| 415 | } |
| 416 | EffectState::Open | EffectState::Unresolved => { |
| 417 | Derived::Uncertain(format!("effect ledger says {}", state.name())) |
| 418 | } |
| 419 | EffectState::NotDone if grant.status == GrantStatus::Available => Derived::Runnable, |
| 420 | EffectState::NotDone => Derived::NeedsGrant, |
| 421 | }) |
| 422 | } |
| 423 | |
| 424 | fn uncertain_record(run_id: &str, id: &TaskId, why: &str) -> FailureRecord { |
| 425 | FailureRecord::new( |
| 426 | 0, |
| 427 | run_id, |
| 428 | 0, |
| 429 | id.to_string(), |
| 430 | None, |
| 431 | RECOVERY_TOOL_NAME, |
| 432 | 1, |
| 433 | FailureClass::Uncertain, |
| 434 | EffectCertainty::Uncertain, |
| 435 | 0, |
| 436 | 0, |
| 437 | ) |
| 438 | .with_cause("recovery", why, None) |
| 439 | } |