diff --git a/docs/WORKFLOW-DAG.md b/docs/WORKFLOW-DAG.md index df42b1b..578e0ef 100644 --- a/docs/WORKFLOW-DAG.md +++ b/docs/WORKFLOW-DAG.md @@ -61,3 +61,7 @@ AEGIS is outside release v1; nothing here is wired into a release path or the fr ## Progress messages for the Pi `src/orchestration/progress.rs` (#58) maps recorded task state to the PST1 Draft v0 message types (aien-dev/aien-protocols-mv#28): Pending and Ready are `queued`; Skipped is `failed` with reason `PREREQUISITE_FAILED`; Uncertain, and Failed with Uncertain effect certainty, are `uncertain_after_disconnect` (not known), never `failed`. Ids come from the stored records, ordinals count each task's messages from 0, and a completed task carries its result digest, never raw output. A message that would need a guess (no cause id, no result digest, no action digest) is refused. The first cut has no encoding and no network; the resume summary and the bytes are later. + +## Grant gate for effectful tasks + +`src/orchestration/grant_gate.rs` (#59) wraps an effectful task body. It starts only under a desk grant bound to the request's objective id and cause id, and checks the grant again after preparation, immediately before the effect. No grant leaves the task waiting for approval; an unbound binding, a forged id, a spent, expired or revoked grant, a foreign objective or cause, and an unreachable desk are refused with a named reason and no effect. The gate checks and never spends: the effect ledger spends the grant when it opens the effect intent. The desk is a trait tested with a fake; the real adapter waits on sovereign-core#379, and binding to the INTERPLANE canonical request digest waits on aien-protocols-mv#33. diff --git a/src/orchestration/grant_gate.rs b/src/orchestration/grant_gate.rs new file mode 100644 index 0000000..4da429e --- /dev/null +++ b/src/orchestration/grant_gate.rs @@ -0,0 +1,208 @@ +//! Grant gate for effectful workflow tasks (issue #59, lane G6). +//! +//! A task that changes the world starts only under a grant from the Spark +//! approval desk that is bound to this request's objective id and cause id. +//! The grant is checked when the task starts and again immediately before +//! the effect, after any preparation. A missing grant asks for approval; a +//! stale, foreign, forged or unbound one is refused with a named reason and +//! no effect. +//! +//! The desk is a trait. The authority is the durable, objective-bound grant +//! in the sovereign-core compose ledger (docs/DELEGATED-DAG.md, proposed +//! decision D3); no client to it exists yet (sovereign-core#379), so tests +//! use a fake. The gate checks; it does not spend. Spending the grant +//! belongs to the effect ledger when it opens the effect intent, so there +//! is one authority for that fact. +//! +//! Not here yet: binding the grant to the INTERPLANE canonical request +//! digest (item 3, after aien-protocols-mv#33) and the real desk adapter +//! (item 4). + +use crate::failure::{EffectCertainty, FailureClass, ToolFault}; +use crate::orchestration::recovery::{GrantId, GrantStatus, LookupError}; +use crate::orchestration::workflow::{TaskContext, TaskOutcome, TaskRunner}; +use async_trait::async_trait; +use std::fmt; +use std::sync::Arc; + +/// What the desk holds for one grant id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeskGrant { + pub status: GrantStatus, + pub objective_id: String, + pub cause_id: String, +} + +/// Read access to the approval desk. +#[async_trait] +pub trait GrantDesk: Send + Sync { + /// `Ok(None)` means the desk never issued this id. + async fn grant(&self, id: &GrantId) -> Result, LookupError>; +} + +/// The request this task belongs to, and the grant id it was handed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GrantBinding { + pub objective_id: String, + /// Copied from the Pi; never minted here. + pub cause_id: String, + pub grant: Option, +} + +/// Why the gate stopped the task. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GrantRefusal { + /// The binding has no objective id or no cause id, so nothing can match. + Unbound, + /// No grant id was handed over: the task waits for approval. + NoGrant, + /// The desk never issued this id. + Forged { + grant: GrantId, + }, + /// Spent, expired or revoked. + Stale { + grant: GrantId, + status: GrantStatus, + }, + ForeignObjective { + grant: GrantId, + }, + ForeignCause { + grant: GrantId, + }, + DeskUnavailable { + detail: String, + }, +} + +impl GrantRefusal { + pub fn name(&self) -> &'static str { + match self { + Self::Unbound => "GRANT_GATE_UNBOUND", + Self::NoGrant => "GRANT_GATE_NO_GRANT", + Self::Forged { .. } => "GRANT_GATE_FORGED", + Self::Stale { .. } => "GRANT_GATE_STALE", + Self::ForeignObjective { .. } => "GRANT_GATE_FOREIGN_OBJECTIVE", + Self::ForeignCause { .. } => "GRANT_GATE_FOREIGN_CAUSE", + Self::DeskUnavailable { .. } => "GRANT_GATE_DESK_UNAVAILABLE", + } + } + + /// What the workflow records. A missing grant is a wait for a human, + /// not a failure; every other refusal is a no-effect failure. + pub fn outcome(&self) -> TaskOutcome { + let class = match self { + Self::NoGrant => return TaskOutcome::ApprovalPending, + Self::DeskUnavailable { .. } => FailureClass::Unavailable, + _ => FailureClass::Rejected, + }; + TaskOutcome::Failed(ToolFault::new( + class, + EffectCertainty::NoEffect, + self.to_string(), + )) + } +} + +impl fmt::Display for GrantRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unbound => write!(f, "{}: binding has no objective or cause", self.name()), + Self::NoGrant => write!(f, "{}: no grant id", self.name()), + Self::Forged { grant } + | Self::ForeignObjective { grant } + | Self::ForeignCause { grant } => write!(f, "{}: {grant}", self.name()), + Self::Stale { grant, status } => write!(f, "{}: {grant} is {status:?}", self.name()), + Self::DeskUnavailable { detail } => write!(f, "{}: {detail}", self.name()), + } + } +} + +impl std::error::Error for GrantRefusal {} + +/// One check against the desk. Returns the grant id the effect may run +/// under. +pub async fn check(desk: &dyn GrantDesk, b: &GrantBinding) -> Result { + if b.objective_id.is_empty() || b.cause_id.is_empty() { + return Err(GrantRefusal::Unbound); + } + let id = b.grant.clone().ok_or(GrantRefusal::NoGrant)?; + let g = desk + .grant(&id) + .await + .map_err(|e| GrantRefusal::DeskUnavailable { detail: e.detail })? + .ok_or_else(|| GrantRefusal::Forged { grant: id.clone() })?; + if g.objective_id != b.objective_id { + return Err(GrantRefusal::ForeignObjective { grant: id }); + } + if g.cause_id != b.cause_id { + return Err(GrantRefusal::ForeignCause { grant: id }); + } + if g.status != GrantStatus::Available { + return Err(GrantRefusal::Stale { + grant: id, + status: g.status, + }); + } + Ok(id) +} + +/// An effectful task body, split so the gate can check between the parts. +#[async_trait] +pub trait EffectBody: Send + Sync { + /// Work that changes nothing outside (building the request, reading). + /// An `Err` ends the task with that outcome and no effect. + async fn prepare(&self, _ctx: &TaskContext) -> Result<(), TaskOutcome> { + Ok(()) + } + + /// The effect, under the grant the gate just checked. + async fn apply(&self, ctx: TaskContext, grant: GrantId) -> TaskOutcome; + + /// Passed through to the workflow on timeout or cancel. + fn certainty_on_interrupt(&self) -> EffectCertainty { + EffectCertainty::Uncertain + } +} + +/// Wraps an effectful body: check, prepare, check again, apply. +pub struct GrantGate { + desk: Arc, + binding: GrantBinding, + body: Arc, +} + +impl GrantGate { + pub fn new( + desk: Arc, + binding: GrantBinding, + body: Arc, + ) -> Arc { + Arc::new(Self { + desk, + binding, + body, + }) + } +} + +#[async_trait] +impl TaskRunner for GrantGate { + async fn run(&self, ctx: TaskContext) -> TaskOutcome { + if let Err(r) = check(self.desk.as_ref(), &self.binding).await { + return r.outcome(); + } + if let Err(out) = self.body.prepare(&ctx).await { + return out; + } + match check(self.desk.as_ref(), &self.binding).await { + Ok(grant) => self.body.apply(ctx, grant).await, + Err(r) => r.outcome(), + } + } + + fn certainty_on_interrupt(&self) -> EffectCertainty { + self.body.certainty_on_interrupt() + } +} diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs index cad20ad..846bd53 100644 --- a/src/orchestration/mod.rs +++ b/src/orchestration/mod.rs @@ -1,4 +1,5 @@ pub mod budget; +pub mod grant_gate; pub mod progress; pub mod recovery; pub mod run; diff --git a/tests/workflow_grant_gate_tests.rs b/tests/workflow_grant_gate_tests.rs new file mode 100644 index 0000000..593de17 --- /dev/null +++ b/tests/workflow_grant_gate_tests.rs @@ -0,0 +1,326 @@ +//! G6 (#59): an effectful task starts only under a desk grant bound to its +//! objective and cause, checked again right before the effect. Fake desk; +//! no sovereign-core client. + +use aegis::orchestration::grant_gate::{ + check, DeskGrant, EffectBody, GrantBinding, GrantDesk, GrantGate, GrantRefusal, +}; +use aegis::orchestration::recovery::{GrantId, GrantStatus, LookupError}; +use aegis::orchestration::workflow::{TaskContext, TaskOutcome, WorkflowBuilder}; +use aegis::{ + CancelToken, EffectCertainty, FailureClass, RunId, SessionId, TaskId, TaskRunner, TaskState, + WorkflowConfig, WorkflowExecutor, +}; +use async_trait::async_trait; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +const OBJECTIVE: &str = "sha256:objective_mine"; +const CAUSE: &str = "cause_mine"; + +fn gid(s: &str) -> GrantId { + GrantId::new(s) +} + +#[derive(Default)] +struct FakeDesk { + grants: Mutex>, + down: Mutex, +} + +impl FakeDesk { + fn with(id: &str, status: GrantStatus, objective: &str, cause: &str) -> Arc { + let d = Arc::new(Self::default()); + d.put(id, status, objective, cause); + d + } + + fn put(&self, id: &str, status: GrantStatus, objective: &str, cause: &str) { + self.grants.lock().unwrap().insert( + gid(id), + DeskGrant { + status, + objective_id: objective.into(), + cause_id: cause.into(), + }, + ); + } + + fn set_status(&self, id: &str, status: GrantStatus) { + self.grants + .lock() + .unwrap() + .get_mut(&gid(id)) + .unwrap() + .status = status; + } +} + +#[async_trait] +impl GrantDesk for FakeDesk { + async fn grant(&self, id: &GrantId) -> Result, LookupError> { + if *self.down.lock().unwrap() { + return Err(LookupError::new("desk unreachable")); + } + Ok(self.grants.lock().unwrap().get(id).cloned()) + } +} + +/// Counts preparation and effects. `during_prepare` runs inside prepare, +/// so a test can change the desk between the two checks. +#[derive(Default)] +struct Body { + prepared: AtomicUsize, + applied: AtomicUsize, + applied_with: Mutex>, + during_prepare: Mutex>>, +} + +#[async_trait] +impl EffectBody for Body { + async fn prepare(&self, _ctx: &TaskContext) -> Result<(), TaskOutcome> { + self.prepared.fetch_add(1, Ordering::SeqCst); + if let Some(f) = self.during_prepare.lock().unwrap().as_ref() { + f(); + } + Ok(()) + } + + async fn apply(&self, _ctx: TaskContext, grant: GrantId) -> TaskOutcome { + self.applied.fetch_add(1, Ordering::SeqCst); + self.applied_with.lock().unwrap().push(grant); + TaskOutcome::Completed(serde_json::json!({ "written": true })) + } +} + +fn binding(grant: Option<&str>) -> GrantBinding { + GrantBinding { + objective_id: OBJECTIVE.into(), + cause_id: CAUSE.into(), + grant: grant.map(gid), + } +} + +fn ctx() -> TaskContext { + TaskContext { + task_id: TaskId::new("write"), + run_id: RunId::from_string("run_g6"), + session_id: SessionId::from_string("sess_g6"), + cancel: CancelToken::new(), + } +} + +async fn gate(desk: Arc, b: GrantBinding) -> (TaskOutcome, Arc) { + let body = Arc::new(Body::default()); + let out = GrantGate::new(desk, b, body.clone()).run(ctx()).await; + (out, body) +} + +/// A refusal is a Rejected, no-effect failure carrying the refusal name. +fn assert_refused(out: &TaskOutcome, body: &Body, name: &str) { + match out { + TaskOutcome::Failed(f) => { + assert!(f.message.starts_with(name), "{}", f.message); + assert_eq!(f.certainty, EffectCertainty::NoEffect); + } + other => panic!("expected refusal {name}, got {other:?}"), + } + assert_eq!(body.applied.load(Ordering::SeqCst), 0, "{name}: effect ran"); +} + +/// Negative control: a good grant runs the effect once, under that grant. +#[tokio::test] +async fn g6_bound_available_grant_runs_the_effect_once() { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); + let (out, body) = gate(desk, binding(Some("g1"))).await; + assert!(matches!(out, TaskOutcome::Completed(_)), "{out:?}"); + assert_eq!(body.applied.load(Ordering::SeqCst), 1); + assert_eq!(*body.applied_with.lock().unwrap(), vec![gid("g1")]); +} + +/// Refusal 1: no grant. The task asks for approval and nothing runs. +#[tokio::test] +async fn g6_no_grant_waits_for_approval_and_runs_nothing() { + let desk = Arc::new(FakeDesk::default()); + let (out, body) = gate(desk.clone(), binding(None)).await; + assert!(matches!(out, TaskOutcome::ApprovalPending), "{out:?}"); + assert_eq!(body.prepared.load(Ordering::SeqCst), 0); + assert_eq!(body.applied.load(Ordering::SeqCst), 0); + assert_eq!( + check(desk.as_ref(), &binding(None)).await, + Err(GrantRefusal::NoGrant) + ); +} + +/// Refusal 2: stale grant (spent, expired or revoked). +#[tokio::test] +async fn g6_stale_grant_is_refused() { + for status in [ + GrantStatus::Spent, + GrantStatus::Expired, + GrantStatus::Revoked, + ] { + let desk = FakeDesk::with("g1", status, OBJECTIVE, CAUSE); + let (out, body) = gate(desk, binding(Some("g1"))).await; + assert_refused(&out, &body, "GRANT_GATE_STALE"); + assert_eq!(body.prepared.load(Ordering::SeqCst), 0); + } +} + +/// Refusal 3: a grant for another objective. +#[tokio::test] +async fn g6_foreign_objective_grant_is_refused() { + let desk = FakeDesk::with( + "g1", + GrantStatus::Available, + "sha256:objective_other", + CAUSE, + ); + let (out, body) = gate(desk, binding(Some("g1"))).await; + assert_refused(&out, &body, "GRANT_GATE_FOREIGN_OBJECTIVE"); +} + +/// Refusal 4: an id the desk never issued. +#[tokio::test] +async fn g6_forged_grant_id_is_refused() { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); + let (out, body) = gate(desk, binding(Some("g1-forged"))).await; + assert_refused(&out, &body, "GRANT_GATE_FORGED"); +} + +#[tokio::test] +async fn g6_foreign_cause_grant_is_refused() { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, "cause_other"); + let (out, body) = gate(desk, binding(Some("g1"))).await; + assert_refused(&out, &body, "GRANT_GATE_FOREIGN_CAUSE"); +} + +#[tokio::test] +async fn g6_unbound_binding_is_refused_even_if_the_desk_matches() { + let desk = FakeDesk::with("g1", GrantStatus::Available, "", CAUSE); + let mut b = binding(Some("g1")); + b.objective_id.clear(); + let (out, body) = gate(desk, b).await; + assert_refused(&out, &body, "GRANT_GATE_UNBOUND"); +} + +#[tokio::test] +async fn g6_unreachable_desk_is_unavailable_with_no_effect() { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); + *desk.down.lock().unwrap() = true; + let (out, body) = gate(desk, binding(Some("g1"))).await; + match &out { + TaskOutcome::Failed(f) => { + assert_eq!(f.class, FailureClass::Unavailable); + assert_eq!(f.certainty, EffectCertainty::NoEffect); + assert!(f.message.starts_with("GRANT_GATE_DESK_UNAVAILABLE")); + } + other => panic!("{other:?}"), + } + assert_eq!(body.applied.load(Ordering::SeqCst), 0); +} + +/// DoD item 2: the grant is checked again right before the effect. The +/// desk revokes it while the body prepares; the effect must not run. +#[tokio::test] +async fn g6_grant_revoked_during_prepare_stops_the_effect() { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); + let body = Arc::new(Body::default()); + let d = desk.clone(); + *body.during_prepare.lock().unwrap() = + Some(Box::new(move || d.set_status("g1", GrantStatus::Revoked))); + let out = GrantGate::new(desk, binding(Some("g1")), body.clone()) + .run(ctx()) + .await; + assert_eq!(body.prepared.load(Ordering::SeqCst), 1); + assert_refused(&out, &body, "GRANT_GATE_STALE"); +} + +/// Through the DAG: no grant leaves the task waiting for approval and its +/// dependent untouched; a forged grant fails it and skips the dependent. +#[tokio::test] +async fn g6_gate_inside_a_workflow() { + let run = |b: GrantBinding| async move { + let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); + let body = Arc::new(Body::default()); + let spec = WorkflowBuilder::default() + .add_task("write", &[], GrantGate::new(desk, b, body.clone())) + .unwrap() + .add_task( + "report", + &["write"], + GrantGate::new( + Arc::new(FakeDesk::default()), + binding(None), + Arc::new(Body::default()), + ), + ) + .unwrap() + .build() + .unwrap(); + let cfg = WorkflowConfig::new( + RunId::from_string("run_g6"), + SessionId::from_string("sess_g6"), + 1, + ); + let r = WorkflowExecutor::new(cfg).unwrap().run(spec).await; + (r, body.applied.load(Ordering::SeqCst)) + }; + let (r, n) = run(binding(None)).await; + assert_eq!( + r.snapshot.states[&TaskId::new("write")], + TaskState::WaitingForApproval + ); + assert_eq!( + r.snapshot.states[&TaskId::new("report")], + TaskState::Pending + ); + assert_eq!(n, 0); + + let (r, n) = run(binding(Some("forged"))).await; + assert!(matches!( + r.snapshot.states[&TaskId::new("write")], + TaskState::Failed(_) + )); + assert!(matches!( + r.snapshot.states[&TaskId::new("report")], + TaskState::Skipped { .. } + )); + assert_eq!(n, 0); +} + +#[test] +fn g6_refusal_names() { + let g = gid("g"); + let all = [ + (GrantRefusal::Unbound, "GRANT_GATE_UNBOUND"), + (GrantRefusal::NoGrant, "GRANT_GATE_NO_GRANT"), + ( + GrantRefusal::Forged { grant: g.clone() }, + "GRANT_GATE_FORGED", + ), + ( + GrantRefusal::Stale { + grant: g.clone(), + status: GrantStatus::Spent, + }, + "GRANT_GATE_STALE", + ), + ( + GrantRefusal::ForeignObjective { grant: g.clone() }, + "GRANT_GATE_FOREIGN_OBJECTIVE", + ), + ( + GrantRefusal::ForeignCause { grant: g }, + "GRANT_GATE_FOREIGN_CAUSE", + ), + ( + GrantRefusal::DeskUnavailable { detail: "x".into() }, + "GRANT_GATE_DESK_UNAVAILABLE", + ), + ]; + for (r, n) in all { + assert_eq!(r.name(), n); + } +}