diff --git a/docs/DELEGATED-DAG.md b/docs/DELEGATED-DAG.md index b89dcfb..24e638c 100644 --- a/docs/DELEGATED-DAG.md +++ b/docs/DELEGATED-DAG.md @@ -93,6 +93,24 @@ Reasons: 1. README line 3: the desk, effect authorization and fail-closed behaviour live in aien-sovereign-core, and AEGIS is outside release v1. A delegated DAG that runs real effects must sit beside them. 2. The existing DAG (`workflow.rs`, 1022 lines at `971d450`, and 25 tests in `tests/workflow_dag_tests.rs`) lives here. Moving it first would add a port to every child issue without changing what they prove. The trait seams make the later move a change of host, not of rules. -## 5. What is not here +## 5. Fire drills (G4, aegis-runtime-mv#57), frozen before code -No code, no schema, no wire bytes. The fire-drill table is added by G4 (aegis-runtime-mv#57). The physical Pi and Spark run belongs to lane H. +Frozen 2026-10-16 in its own commit, before any drill test was written. A row changes only by a later commit that says why; the tests are fitted to the rows, never the reverse. + +Host stand-ins only. The stand-in world plays the authorities of section 2: a desk that issues single-use grants and opens one effect intent per grant, an effect ledger (OPEN, DONE, NOT_DONE, UNRESOLVED) whose reconcile checks the world, receipts, and an **effect counter** that counts every time the effect touches the world. A "kill" drops everything AEGIS holds in memory; the stand-in world survives, as durable records would. "Restart" is `rebuild` (G3) over the pointers AEGIS had stored before the kill. A human re-approval is the test issuing a new grant only when the rebuilt status asks for one. + +Every row checks two things at the end: the effect counter shows no duplicate final effect, and every status reported on the way was true when it was reported. With one task at a time, every row gives the identical sequence of steps and states on two runs. + +| Row | Drill | Stand-in setup | Truthful status after the restart | Final effect count | Deliberate break that must turn the row red | First cut | +|---|---|---|---|---|---|---| +| 1 | Kill between approval and effect | Grant issued and its id stored; the desk opened the intent; the kill comes before AEGIS stored the intent id and before the effect | `write` Uncertain (the desk names the OPEN intent), `report` Pending. After reconcile (NOT_DONE): `write` WaitingForApproval, since the grant is spent. After a new grant and the resumed run: Completed | 1 | A task with no stored intent id is treated as not started (the desk's intent is ignored) | Test | +| 2 | Kill after the effect, before acknowledgement | Intent opened, effect applied, kill before the ack and before the receipt is stored | `write` Uncertain, `report` Pending, no new approval asked. After reconcile (DONE, receipt): Completed, and `report` Ready | 1 | Retry when uncertain: an OPEN intent is treated as needing a new approval, so a human approves it again | Test | +| 3 | The same request sent twice with one idempotence key | The first request ran to Completed and its pointers are stored under its key | The second request is answered with the first run id and Completed; nothing starts | 1 | Admission ignores the key and starts a fresh run for the repeat | Test | +| 4 | Link cut while text is streaming | `text_chunk` ordinals 0 to n sent, link drops mid stream | Task state comes from the records, unchanged by the cut; chunks resume after the last ordinal the Pi holds, none repeated as new | 0 (compute only) | Resend from ordinal 0 as new chunks | Later | +| 5 | Pi restart, then a resume request carrying the old cause id | Workflow mid run when the Pi restarts | Resume summary built from `rebuild`; a resume request with a different cause id is refused | 1 | Accept a resume request whose cause id differs from the stored one | Later | +| 6 | Cancel racing a completion | Cancel arrives while the effect is being acknowledged | Completed if the ledger says DONE with a receipt; Cancelled only if no intent was opened; Uncertain otherwise. Never Cancelled while the ledger says DONE | At most 1 | Report Cancelled whenever a cancel was received | Later | +| 7 | A prerequisite failing | `write` fails with no effect | `write` Failed, `report` Skipped and never run | 0 | Run the dependent anyway | Later | + +## 6. What is not here + +No schema and no wire bytes. The physical Pi and Spark run belongs to lane H. diff --git a/tests/workflow_recovery_tests.rs b/tests/workflow_recovery_tests.rs index 9b4bf06..638d0a7 100644 --- a/tests/workflow_recovery_tests.rs +++ b/tests/workflow_recovery_tests.rs @@ -367,3 +367,314 @@ fn spec_digest_ignores_insertion_order_and_sees_edges() { .unwrap(); assert_ne!(spec_digest(&a), spec_digest(&c)); } + +// ---- G4 (#57): fire drills, rows 1 to 3 of docs/DELEGATED-DAG.md section 5 ---- +// +// The stand-in world plays the authorities: a single-use grant desk that +// opens one effect intent per grant, an effect ledger whose reconcile looks +// at the world, receipts, and an effect counter. A kill drops what AEGIS +// holds in memory; the world and the stored pointers survive. + +#[derive(Default)] +struct WorldState { + next: u32, + grants: HashMap, + /// Intent state and whether the effect touched the world. + intents: HashMap, + receipts: HashSet, + effects: u32, +} + +#[derive(Default)] +struct World(std::sync::Mutex); + +impl World { + fn issue_grant(&self) -> GrantId { + let mut w = self.0.lock().unwrap(); + w.next += 1; + let g = grant(&format!("g{}", w.next)); + w.grants.insert( + g.clone(), + GrantRecord { + status: GrantStatus::Available, + intent: None, + }, + ); + g + } + + /// The desk spends the grant and opens one intent, or refuses. + fn open_intent(&self, g: &GrantId) -> Result { + let mut w = self.0.lock().unwrap(); + match w.grants.get(g).map(|r| r.status) { + Some(GrantStatus::Available) => {} + other => return Err(format!("desk refuses {g}: {other:?}")), + } + w.next += 1; + let i = intent(&format!("i{}", w.next)); + w.grants.insert( + g.clone(), + GrantRecord { + status: GrantStatus::Spent, + intent: Some(i.clone()), + }, + ); + w.intents.insert(i.clone(), (EffectState::Open, false)); + Ok(i) + } + + /// The effect itself: the only place the counter moves. + fn apply(&self, i: &EffectIntentId) { + let mut w = self.0.lock().unwrap(); + w.effects += 1; + w.intents.get_mut(i).unwrap().1 = true; + } + + fn ack(&self, i: &EffectIntentId) -> ReceiptDigest { + let mut w = self.0.lock().unwrap(); + w.intents.get_mut(i).unwrap().0 = EffectState::Done; + let r = receipt(&format!("r-{i}")); + w.receipts.insert(r.clone()); + r + } + + /// The authority settles an open intent by looking at the world. The + /// terminal record is the receipt. + fn reconcile(&self, i: &EffectIntentId) -> Option { + let mut w = self.0.lock().unwrap(); + let (state, applied) = w.intents[i]; + if !matches!(state, EffectState::Open | EffectState::Unresolved) { + return None; + } + if applied { + w.intents.get_mut(i).unwrap().0 = EffectState::Done; + let r = receipt(&format!("r-{i}")); + w.receipts.insert(r.clone()); + Some(r) + } else { + w.intents.get_mut(i).unwrap().0 = EffectState::NotDone; + None + } + } + + fn effects(&self) -> u32 { + self.0.lock().unwrap().effects + } +} + +#[async_trait] +impl AuthorityLookup for World { + async fn effect_state(&self, i: &EffectIntentId) -> Result, LookupError> { + Ok(self.0.lock().unwrap().intents.get(i).map(|(s, _)| *s)) + } + + async fn grant(&self, g: &GrantId) -> Result, LookupError> { + Ok(self.0.lock().unwrap().grants.get(g).cloned()) + } + + async fn receipt_present(&self, r: &ReceiptDigest) -> Result { + Ok(self.0.lock().unwrap().receipts.contains(r)) + } +} + +fn line(spec: &WorkflowSpec, s: &aegis::orchestration::workflow::WorkflowSnapshot) -> String { + spec.task_ids() + .iter() + .map(|id| format!("{id}={}", s.states[id].name())) + .collect::>() + .join(" ") +} + +/// The resume step after a restart: rebuild from the records, run exactly +/// the tasks that came back Ready (one at a time, in spec order), store +/// their pointers, and repeat until nothing is Ready. Uncertain and +/// WaitingForApproval tasks are never run. +async fn resume( + spec: &WorkflowSpec, + stored: &mut StoredPointers, + world: &World, + trace: &mut Vec, +) -> aegis::orchestration::workflow::WorkflowSnapshot { + loop { + let snap = rebuild(spec, stored, world).await.expect("rebuild"); + trace.push(format!("rebuild {}", line(spec, &snap))); + let ready: Vec = spec + .task_ids() + .into_iter() + .filter(|id| snap.states[id] == TaskState::Ready) + .collect(); + if ready.is_empty() { + return snap; + } + for id in ready { + let p = stored.tasks.get_mut(&id).unwrap(); + if p.effect_class == EffectClass::Effect { + let g = p.grant.clone().expect("grant pointer"); + let i = world.open_intent(&g).expect("desk"); + p.effect_intent = Some(i.clone()); + world.apply(&i); + p.receipt = Some(world.ack(&i)); + } else { + p.result_digest = Some(format!("sha256:{id}")); + } + trace.push(format!("run {id}")); + } + } +} + +/// A human approves again only when the rebuilt status asks for it. +fn approve_if_asked( + snap: &aegis::orchestration::workflow::WorkflowSnapshot, + stored: &mut StoredPointers, + world: &World, + trace: &mut Vec, +) { + if snap.states[&tid("write")] == TaskState::WaitingForApproval { + let g = world.issue_grant(); + trace.push(format!("approve {g}")); + stored.tasks.get_mut(&tid("write")).unwrap().grant = Some(g); + } +} + +fn fresh(world: &World) -> StoredPointers { + let g = world.issue_grant(); + pointers(effect_pointers(None, g.as_str(), None)) +} + +/// Row 1: kill between approval and effect. The desk opened the intent, +/// AEGIS had not stored its id yet, and the effect never ran. +async fn drill_row1() -> (Vec, u32) { + let (w, spec) = (World::default(), spec()); + let mut stored = fresh(&w); + let g1 = stored.tasks[&tid("write")].grant.clone().unwrap(); + let i1 = w.open_intent(&g1).unwrap(); + let mut t = vec!["kill after intent, before pointer and effect".to_string()]; + + let s = resume(&spec, &mut stored, &w, &mut t).await; + assert!( + matches!(s.states[&tid("write")], TaskState::Uncertain(_)), + "{}", + line(&spec, &s) + ); + assert_eq!(s.states[&tid("report")], TaskState::Pending); + approve_if_asked(&s, &mut stored, &w, &mut t); + assert_eq!(w.effects(), 0); + + assert_eq!(w.reconcile(&i1), None); + t.push("reconcile NOT_DONE".into()); + let s = resume(&spec, &mut stored, &w, &mut t).await; + assert_eq!(s.states[&tid("write")], TaskState::WaitingForApproval); + approve_if_asked(&s, &mut stored, &w, &mut t); + + let s = resume(&spec, &mut stored, &w, &mut t).await; + for id in ["write", "report", "lint"] { + assert_eq!(s.states[&tid(id)], TaskState::Completed, "{id}"); + } + (t, w.effects()) +} + +/// Row 2: kill after the effect, before acknowledgement. +async fn drill_row2() -> (Vec, u32) { + let (w, spec) = (World::default(), spec()); + let mut stored = fresh(&w); + let g1 = stored.tasks[&tid("write")].grant.clone().unwrap(); + let i1 = w.open_intent(&g1).unwrap(); + stored.tasks.get_mut(&tid("write")).unwrap().effect_intent = Some(i1.clone()); + w.apply(&i1); + let mut t = vec!["kill after effect, before ack".to_string()]; + + let s = resume(&spec, &mut stored, &w, &mut t).await; + assert!( + matches!(s.states[&tid("write")], TaskState::Uncertain(_)), + "{}", + line(&spec, &s) + ); + assert_eq!(s.states[&tid("report")], TaskState::Pending); + approve_if_asked(&s, &mut stored, &w, &mut t); + + let r = w.reconcile(&i1).expect("world changed, so DONE"); + stored.tasks.get_mut(&tid("write")).unwrap().receipt = Some(r); + t.push("reconcile DONE".into()); + let s = resume(&spec, &mut stored, &w, &mut t).await; + approve_if_asked(&s, &mut stored, &w, &mut t); + for id in ["write", "report", "lint"] { + assert_eq!(s.states[&tid(id)], TaskState::Completed, "{id}"); + } + (t, w.effects()) +} + +/// Admission stand-in for PST1 section 8 item 2: a repeated request with +/// the same idempotence key is the same request. No request store exists +/// in AEGIS yet, so this map lives here. +#[derive(Default)] +struct Admissions(HashMap); + +impl Admissions { + /// Returns the stored pointers of an earlier request with this key, or + /// registers `fresh` as a new run. + fn admit(&mut self, key: &str, fresh: StoredPointers) -> (StoredPointers, bool) { + match self.0.get(key) { + Some(p) => (p.clone(), false), + None => { + self.0.insert(key.into(), fresh.clone()); + (fresh, true) + } + } + } +} + +/// Row 3: the same request twice with one idempotence key. +async fn drill_row3() -> (Vec, u32) { + let (w, spec) = (World::default(), spec()); + let mut adm = Admissions::default(); + let mut t = Vec::new(); + + let (mut stored, new) = adm.admit("k1", fresh(&w)); + assert!(new); + let s = resume(&spec, &mut stored, &w, &mut t).await; + assert_eq!(s.states[&tid("write")], TaskState::Completed); + adm.0.insert("k1".into(), stored.clone()); + let first_run = s.run_id.clone(); + t.push("request 1 answered".into()); + + // The repeat carries the same key; a fresh run would get its own id. + let mut repeat = fresh(&w); + repeat.run_id = "run_repeat".into(); + let (mut stored2, new) = adm.admit("k1", repeat); + let s = resume(&spec, &mut stored2, &w, &mut t).await; + t.push(format!("request 2 answered new={new}")); + assert_eq!(s.run_id, first_run, "repeat must map to the first run"); + for id in ["write", "report", "lint"] { + assert_eq!(s.states[&tid(id)], TaskState::Completed, "{id}"); + } + (t, w.effects()) +} + +async fn twice( + row: fn() -> futures_util::future::BoxFuture<'static, (Vec, u32)>, +) -> Vec { + let (t1, e1) = row().await; + let (t2, e2) = row().await; + assert_eq!(e1, 1, "duplicate or missing final effect: {t1:?}"); + assert_eq!(e2, 1); + assert_eq!(t1, t2, "event order differs between two runs"); + t1 +} + +#[tokio::test] +async fn drill_row1_kill_between_approval_and_effect() { + let t = twice(|| Box::pin(drill_row1())).await; + assert!(t.contains(&"approve g3".to_string()), "{t:?}"); +} + +#[tokio::test] +async fn drill_row2_kill_after_effect_before_ack() { + let t = twice(|| Box::pin(drill_row2())).await; + assert!(!t.iter().any(|l| l.starts_with("approve")), "{t:?}"); +} + +#[tokio::test] +async fn drill_row3_duplicate_request_one_idempotence_key() { + let t = twice(|| Box::pin(drill_row3())).await; + assert_eq!(t.iter().filter(|l| *l == "run write").count(), 1, "{t:?}"); +}