diff --git a/docs/WORKFLOW-DAG.md b/docs/WORKFLOW-DAG.md index b1f8550..df42b1b 100644 --- a/docs/WORKFLOW-DAG.md +++ b/docs/WORKFLOW-DAG.md @@ -57,3 +57,7 @@ Workflow state is in memory only. After a process restart nothing is recovered a ## 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. + +## 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. diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs index e470366..cad20ad 100644 --- a/src/orchestration/mod.rs +++ b/src/orchestration/mod.rs @@ -1,4 +1,5 @@ pub mod budget; +pub mod progress; pub mod recovery; pub mod run; pub mod termination; diff --git a/src/orchestration/progress.rs b/src/orchestration/progress.rs new file mode 100644 index 0000000..f88abc2 --- /dev/null +++ b/src/orchestration/progress.rs @@ -0,0 +1,401 @@ +//! Workflow state to PST1 progress messages (issue #58, lane G5). +//! +//! A pure mapping from what the workflow recorded to the message types of +//! PST1 Draft v0 section 5 (aien-dev/aien-protocols-mv#28). Nothing here +//! encodes bytes or touches a network: the first cut stops at typed +//! messages. Status comes only from recorded task state, never from model +//! text, and a message is refused rather than filled with a guess. +//! +//! The type values are copied from the PST1 table here so AEGIS does not +//! depend on the draft `aien-pi-spark-task` crate before it merges. When it +//! does, `PstType` should become that crate's type (item 4, the bytes). +//! +//! Not here yet: `accepted` (the admission answer, owned by the request +//! store), `text_chunk`, `receipt_reference`, the `resume_snapshot` built +//! from `recovery::rebuild` (item 3), and encoding (item 4). + +use crate::failure::{EffectCertainty, FailureClass, FailureRecord}; +use crate::orchestration::recovery::{EffectClass, StoredPointers}; +use crate::orchestration::workflow::{TaskId, TaskState, WorkflowReport, WorkflowSnapshot}; +use std::collections::BTreeMap; +use std::fmt; + +/// PST1 message types, section 5. The discriminant is the wire value. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PstType { + Request = 1, + Accepted = 2, + Queued = 3, + Running = 4, + TextChunk = 5, + WaitingForApproval = 6, + Completed = 7, + Failed = 8, + Cancelled = 9, + UncertainAfterDisconnect = 10, + ResumeSnapshot = 11, + ReceiptReference = 12, + CancelRequest = 13, + ResumeRequest = 14, +} + +impl PstType { + /// Every type in wire order. + pub const ALL: [PstType; 14] = [ + Self::Request, + Self::Accepted, + Self::Queued, + Self::Running, + Self::TextChunk, + Self::WaitingForApproval, + Self::Completed, + Self::Failed, + Self::Cancelled, + Self::UncertainAfterDisconnect, + Self::ResumeSnapshot, + Self::ReceiptReference, + Self::CancelRequest, + Self::ResumeRequest, + ]; + + pub fn value(self) -> u8 { + self as u8 + } + + pub fn name(self) -> &'static str { + match self { + Self::Request => "request", + Self::Accepted => "accepted", + Self::Queued => "queued", + Self::Running => "running", + Self::TextChunk => "text_chunk", + Self::WaitingForApproval => "waiting_for_approval", + Self::Completed => "completed", + Self::Failed => "failed", + Self::Cancelled => "cancelled", + Self::UncertainAfterDisconnect => "uncertain_after_disconnect", + Self::ResumeSnapshot => "resume_snapshot", + Self::ReceiptReference => "receipt_reference", + Self::CancelRequest => "cancel_request", + Self::ResumeRequest => "resume_request", + } + } + + /// The Pi sends `request`, `cancel_request` and `resume_request`; the + /// Spark sends every other type. + pub fn sent_by_spark(self) -> bool { + !matches!( + self, + Self::Request | Self::CancelRequest | Self::ResumeRequest + ) + } +} + +/// What the payload will carry once encoded. Digests stay in the +/// `sha256:<64 hex>` form AEGIS records; encoding turns them into 32 bytes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProgressPayload { + Empty, + /// `waiting_for_approval`: the action awaiting approval. + ActionDigest(String), + /// `completed`: the result digest from `WorkflowSnapshot.results`, + /// never the raw output. + ResultDigest(String), + /// `failed`: a short reason code and text. + Failure { + code: &'static str, + text: String, + }, +} + +/// One progress message, before encoding. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProgressMessage { + pub msg_type: PstType, + /// Copied from the Pi's request; never minted here. + pub cause_id: String, + pub origin_run_id: String, + pub objective_id: String, + pub task_id: TaskId, + /// Messages of one task, from 0, rising by one. + pub ordinal: u32, + pub effect_class: EffectClass, + pub payload: ProgressPayload, +} + +/// The ids every message carries, read from the stored records. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ProgressContext { + pub run_id: String, + pub cause_id: String, + pub objective_id: String, + pub effect_classes: BTreeMap, + /// Digest of the action each approval-waiting task asks about. AEGIS + /// records none yet; the approval desk will (G6, sovereign-core#379). + pub action_digests: BTreeMap, +} + +impl ProgressContext { + /// The ids and effect classes from the G3 stored pointers. Action + /// digests are not in those pointers and start empty. + pub fn from_pointers(p: &StoredPointers) -> Self { + Self { + run_id: p.run_id.clone(), + cause_id: p.cause_id.clone(), + objective_id: p.objective_id.clone(), + effect_classes: p + .tasks + .iter() + .map(|(id, t)| (id.clone(), t.effect_class)) + .collect(), + action_digests: BTreeMap::new(), + } + } +} + +/// Why no message could be built. Nothing is sent in its place. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProgressRefusal { + /// No cause id: one is never minted here (PST1 section 7, `PST_NO_CAUSE`). + NoCause, + RunMismatch { + context: String, + report: String, + }, + /// No effect class is recorded for this task. + UnknownTask { + task: TaskId, + }, + UnknownEventState { + task: TaskId, + state: String, + }, + MissingFailureRecord { + task: TaskId, + }, + CompletedWithoutResult { + task: TaskId, + }, + /// The recorded result is not a `sha256:<64 hex>` digest. + BadResultDigest { + task: TaskId, + }, + WaitingWithoutActionDigest { + task: TaskId, + }, +} + +impl ProgressRefusal { + pub fn name(&self) -> &'static str { + match self { + Self::NoCause => "PROGRESS_NO_CAUSE", + Self::RunMismatch { .. } => "PROGRESS_RUN_MISMATCH", + Self::UnknownTask { .. } => "PROGRESS_UNKNOWN_TASK", + Self::UnknownEventState { .. } => "PROGRESS_UNKNOWN_EVENT_STATE", + Self::MissingFailureRecord { .. } => "PROGRESS_MISSING_FAILURE_RECORD", + Self::CompletedWithoutResult { .. } => "PROGRESS_COMPLETED_WITHOUT_RESULT", + Self::BadResultDigest { .. } => "PROGRESS_BAD_RESULT_DIGEST", + Self::WaitingWithoutActionDigest { .. } => "PROGRESS_WAITING_WITHOUT_ACTION_DIGEST", + } + } +} + +impl fmt::Display for ProgressRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {self:?}", self.name()) + } +} + +impl std::error::Error for ProgressRefusal {} + +/// The one message type a task state is reported as. +/// +/// Pending and Ready are both `queued`. Skipped is `failed` with the reason +/// `PREREQUISITE_FAILED` (PST1 has no skipped type). A Failed task whose +/// effect certainty is Uncertain is reported as not known, never as +/// `failed` (PST1 section 8 item 3), even though the workflow keeps it +/// Failed. PST1 names that type `uncertain_after_disconnect`; its meaning, +/// "not known whether it happened", is what is reported. +pub fn message_type(state: &TaskState) -> PstType { + match state { + TaskState::Pending | TaskState::Ready => PstType::Queued, + TaskState::Running => PstType::Running, + TaskState::WaitingForApproval => PstType::WaitingForApproval, + TaskState::Completed => PstType::Completed, + TaskState::Failed(f) if f.effect_certainty == EffectCertainty::Uncertain => { + PstType::UncertainAfterDisconnect + } + TaskState::Failed(_) | TaskState::Skipped { .. } => PstType::Failed, + TaskState::Cancelled => PstType::Cancelled, + TaskState::Uncertain(_) => PstType::UncertainAfterDisconnect, + } +} + +/// One message for one task in one state, with the given ordinal. +pub fn message_for_state( + ctx: &ProgressContext, + snapshot: &WorkflowSnapshot, + task: &TaskId, + state: &TaskState, + ordinal: u32, +) -> Result { + check_context(ctx, snapshot)?; + let effect_class = *ctx + .effect_classes + .get(task) + .ok_or_else(|| ProgressRefusal::UnknownTask { task: task.clone() })?; + let msg_type = message_type(state); + let payload = match msg_type { + PstType::Completed => { + let r = snapshot + .results + .get(task) + .ok_or_else(|| ProgressRefusal::CompletedWithoutResult { task: task.clone() })?; + if !is_sha256(&r.digest) { + return Err(ProgressRefusal::BadResultDigest { task: task.clone() }); + } + ProgressPayload::ResultDigest(r.digest.clone()) + } + PstType::WaitingForApproval => { + let d = ctx.action_digests.get(task).ok_or_else(|| { + ProgressRefusal::WaitingWithoutActionDigest { task: task.clone() } + })?; + ProgressPayload::ActionDigest(d.clone()) + } + PstType::Failed => match state { + TaskState::Skipped { prerequisite } => ProgressPayload::Failure { + code: "PREREQUISITE_FAILED", + text: format!("prerequisite {prerequisite} did not complete"), + }, + TaskState::Failed(f) => ProgressPayload::Failure { + code: failure_code(f.class), + text: failure_text(f), + }, + _ => ProgressPayload::Empty, + }, + _ => ProgressPayload::Empty, + }; + Ok(ProgressMessage { + msg_type, + cause_id: ctx.cause_id.clone(), + origin_run_id: snapshot.run_id.clone(), + objective_id: ctx.objective_id.clone(), + task_id: task.clone(), + ordinal, + effect_class, + payload, + }) +} + +/// Every progress message of a finished (or stopped) run, in ledger order. +/// +/// Ordinals count each task's messages from 0. A transition that maps to +/// the same type as that task's previous message adds nothing and is not +/// repeated (for example Pending then Ready, both `queued`). +pub fn messages_from_report( + ctx: &ProgressContext, + report: &WorkflowReport, +) -> Result, ProgressRefusal> { + let snap = &report.snapshot; + check_context(ctx, snap)?; + let mut last: BTreeMap = BTreeMap::new(); + let mut out = Vec::new(); + for e in &report.events { + let Some(task) = &e.task_id else { + continue; + }; + let state = state_for_event(report, task, &e.state)?; + let ty = message_type(&state); + let ordinal = match last.get(task) { + Some((_, prev)) if *prev == ty => continue, + Some((n, _)) => n + 1, + None => 0, + }; + out.push(message_for_state(ctx, snap, task, &state, ordinal)?); + last.insert(task.clone(), (ordinal, ty)); + } + Ok(out) +} + +fn check_context(ctx: &ProgressContext, snap: &WorkflowSnapshot) -> Result<(), ProgressRefusal> { + if ctx.cause_id.is_empty() { + return Err(ProgressRefusal::NoCause); + } + if ctx.run_id != snap.run_id { + return Err(ProgressRefusal::RunMismatch { + context: ctx.run_id.clone(), + report: snap.run_id.clone(), + }); + } + Ok(()) +} + +/// The ledger keeps a state name per event; the records behind a failed, +/// uncertain or skipped state come from the report. +fn state_for_event( + report: &WorkflowReport, + task: &TaskId, + name: &str, +) -> Result { + let record = || { + report + .failures + .get(task) + .cloned() + .ok_or_else(|| ProgressRefusal::MissingFailureRecord { task: task.clone() }) + }; + Ok(match name { + "pending" => TaskState::Pending, + "ready" => TaskState::Ready, + "running" => TaskState::Running, + "waiting_for_approval" => TaskState::WaitingForApproval, + "completed" => TaskState::Completed, + "cancelled" => TaskState::Cancelled, + "failed" => TaskState::Failed(record()?), + "uncertain" => TaskState::Uncertain(record()?), + "skipped" => match report.snapshot.states.get(task) { + Some(s @ TaskState::Skipped { .. }) => s.clone(), + _ => return Err(ProgressRefusal::MissingFailureRecord { task: task.clone() }), + }, + other => { + return Err(ProgressRefusal::UnknownEventState { + task: task.clone(), + state: other.to_string(), + }) + } + }) +} + +fn failure_code(class: FailureClass) -> &'static str { + match class { + FailureClass::Rejected => "REJECTED", + FailureClass::Unavailable => "UNAVAILABLE", + FailureClass::Timeout => "TIMEOUT", + FailureClass::Cancelled => "CANCELLED", + FailureClass::Uncertain => "UNCERTAIN", + FailureClass::Failed => "FAILED", + FailureClass::Malformed => "MALFORMED", + FailureClass::ApprovalPending => "APPROVAL_PENDING", + } +} + +/// The recorded cause messages (already length capped by the failure +/// record), joined; the class name when there are none. +fn failure_text(f: &FailureRecord) -> String { + if f.cause.is_empty() { + return failure_code(f.class).to_lowercase(); + } + f.cause + .iter() + .map(|c| c.message.as_str()) + .collect::>() + .join("; ") +} + +fn is_sha256(d: &str) -> bool { + d.strip_prefix("sha256:").is_some_and(|h| { + h.len() == 64 + && h.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} diff --git a/tests/workflow_progress_tests.rs b/tests/workflow_progress_tests.rs new file mode 100644 index 0000000..5e94365 --- /dev/null +++ b/tests/workflow_progress_tests.rs @@ -0,0 +1,352 @@ +//! G5 (#58): workflow state to PST1 progress message types. Pure mapping, +//! no encoding, no network. The message types are PST1 Draft v0 section 5 +//! (aien-dev/aien-protocols-mv#28). + +use aegis::orchestration::progress::{ + message_type, messages_from_report, ProgressContext, ProgressMessage, ProgressPayload, + ProgressRefusal, PstType, +}; +use aegis::orchestration::recovery::{EffectClass, StoredPointers, TaskPointers}; +use aegis::orchestration::workflow::{runner_fn, TaskContext, TaskOutcome, WorkflowBuilder}; +use aegis::{ + EffectCertainty, FailureClass, FailureRecord, RunId, SessionId, TaskId, TaskRunner, TaskState, + ToolFault, WorkflowConfig, WorkflowExecutor, WorkflowReport, WorkflowSpec, +}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +const RUN: &str = "run_g5"; +const CAUSE: &str = "cause_from_the_pi"; +const OBJECTIVE: &str = "sha256:objective"; +const ACTION: &str = "sha256:action_awaiting_approval"; + +fn tid(s: &str) -> TaskId { + TaskId::new(s) +} + +fn record(class: FailureClass, cert: EffectCertainty) -> FailureRecord { + FailureRecord::new(1, RUN, 0, "t", None, "tool", 1, class, cert, 0, 0) +} + +fn ok() -> Arc { + runner_fn(|_c: TaskContext| { + Box::pin(async { TaskOutcome::Completed(serde_json::json!({ "ok": true })) }) + }) +} + +fn failing(class: FailureClass, cert: EffectCertainty) -> Arc { + runner_fn(move |_c: TaskContext| { + Box::pin(async move { TaskOutcome::Failed(ToolFault::new(class, cert, "boom")) }) + }) +} + +fn approval() -> Arc { + runner_fn(|_c| Box::pin(async { TaskOutcome::ApprovalPending })) +} + +async fn run(spec: WorkflowSpec) -> WorkflowReport { + let cfg = WorkflowConfig::new( + RunId::from_string(RUN), + SessionId::from_string("sess_g5"), + 1, + ); + WorkflowExecutor::new(cfg).unwrap().run(spec).await +} + +fn ctx(tasks: &[(&str, EffectClass)]) -> ProgressContext { + ProgressContext { + run_id: RUN.into(), + cause_id: CAUSE.into(), + objective_id: OBJECTIVE.into(), + effect_classes: tasks.iter().map(|(t, c)| (tid(t), *c)).collect(), + action_digests: BTreeMap::new(), + } +} + +fn of<'a>(msgs: &'a [ProgressMessage], task: &str) -> Vec<&'a ProgressMessage> { + msgs.iter().filter(|m| m.task_id == tid(task)).collect() +} + +fn types(msgs: &[&ProgressMessage]) -> Vec { + msgs.iter().map(|m| m.msg_type).collect() +} + +/// a -> b, plus an independent gate that waits for approval. +fn approval_spec() -> WorkflowSpec { + WorkflowBuilder::default() + .add_task("a", &[], ok()) + .unwrap() + .add_task("b", &["a"], ok()) + .unwrap() + .add_task("gate", &[], approval()) + .unwrap() + .build() + .unwrap() +} + +fn approval_ctx() -> ProgressContext { + let mut c = ctx(&[ + ("a", EffectClass::Compute), + ("b", EffectClass::Compute), + ("gate", EffectClass::Effect), + ]); + c.action_digests.insert(tid("gate"), ACTION.into()); + c +} + +#[test] +fn g5_message_type_values_match_pst1_section_5() { + let want = [ + (1, "request", false), + (2, "accepted", true), + (3, "queued", true), + (4, "running", true), + (5, "text_chunk", true), + (6, "waiting_for_approval", true), + (7, "completed", true), + (8, "failed", true), + (9, "cancelled", true), + (10, "uncertain_after_disconnect", true), + (11, "resume_snapshot", true), + (12, "receipt_reference", true), + (13, "cancel_request", false), + (14, "resume_request", false), + ]; + for (t, (v, n, spark)) in PstType::ALL.iter().zip(want) { + assert_eq!((t.value(), t.name(), t.sent_by_spark()), (v, n, spark)); + } +} + +/// DoD item 4 (first half): every state maps to exactly one message type, +/// always one the Spark sends. +#[test] +fn g5_every_task_state_maps_to_exactly_one_spark_message_type() { + let table = [ + (TaskState::Pending, PstType::Queued), + (TaskState::Ready, PstType::Queued), + (TaskState::Running, PstType::Running), + (TaskState::WaitingForApproval, PstType::WaitingForApproval), + (TaskState::Completed, PstType::Completed), + ( + TaskState::Failed(record(FailureClass::Failed, EffectCertainty::NoEffect)), + PstType::Failed, + ), + ( + TaskState::Failed(record( + FailureClass::Failed, + EffectCertainty::EffectOccurred, + )), + PstType::Failed, + ), + // Failed, but not known whether the effect happened: PST1 section 8 + // item 3 says never report failed when it does not know. + ( + TaskState::Failed(record(FailureClass::Uncertain, EffectCertainty::Uncertain)), + PstType::UncertainAfterDisconnect, + ), + (TaskState::Cancelled, PstType::Cancelled), + ( + TaskState::Skipped { + prerequisite: tid("a"), + }, + PstType::Failed, + ), + ( + TaskState::Uncertain(record(FailureClass::Timeout, EffectCertainty::Uncertain)), + PstType::UncertainAfterDisconnect, + ), + ]; + let names: BTreeSet<&str> = table.iter().map(|(s, _)| s.name()).collect(); + let all: BTreeSet<&str> = [ + "pending", + "ready", + "running", + "waiting_for_approval", + "completed", + "failed", + "cancelled", + "skipped", + "uncertain", + ] + .into(); + assert_eq!(names, all, "the table must cover every TaskState"); + for (state, want) in &table { + let got = message_type(state); + assert_eq!(got, *want, "{}", state.name()); + assert!(got.sent_by_spark(), "{}", state.name()); + } +} + +/// DoD items 1 and 2: ids from the records, ordinals from 0 per task, the +/// result digest from the snapshot, never raw output. +#[tokio::test] +async fn g5_messages_from_a_real_run_carry_ids_ordinals_and_digests() { + let r = run(approval_spec()).await; + let msgs = messages_from_report(&approval_ctx(), &r).expect("mapping"); + assert!(!msgs.is_empty()); + for m in &msgs { + assert_eq!(m.cause_id, CAUSE); + assert_eq!(m.objective_id, OBJECTIVE); + assert_eq!(m.origin_run_id, r.snapshot.run_id); + assert!(m.msg_type.sent_by_spark()); + } + for task in ["a", "b", "gate"] { + let ms = of(&msgs, task); + let ords: Vec = ms.iter().map(|m| m.ordinal).collect(); + assert_eq!(ords, (0..ms.len() as u32).collect::>(), "{task}"); + } + let a = of(&msgs, "a"); + assert_eq!( + types(&a), + vec![PstType::Queued, PstType::Running, PstType::Completed] + ); + assert_eq!(a[0].effect_class, EffectClass::Compute); + assert_eq!( + a[2].payload, + ProgressPayload::ResultDigest(r.snapshot.results[&tid("a")].digest.clone()) + ); + let gate = of(&msgs, "gate"); + assert_eq!(gate.last().unwrap().msg_type, PstType::WaitingForApproval); + assert_eq!( + gate.last().unwrap().payload, + ProgressPayload::ActionDigest(ACTION.into()) + ); + assert_eq!(gate[0].effect_class, EffectClass::Effect); + for m in &msgs { + if matches!(m.msg_type, PstType::Queued | PstType::Running) { + assert_eq!(m.payload, ProgressPayload::Empty); + } + } +} + +#[tokio::test] +async fn g5_same_run_twice_gives_the_same_messages() { + let one = messages_from_report(&approval_ctx(), &run(approval_spec()).await).unwrap(); + let two = messages_from_report(&approval_ctx(), &run(approval_spec()).await).unwrap(); + assert_eq!(one, two); +} + +#[tokio::test] +async fn g5_failed_with_unknown_effect_is_reported_as_not_known() { + let spec = WorkflowBuilder::default() + .add_task( + "w", + &[], + failing(FailureClass::Uncertain, EffectCertainty::Uncertain), + ) + .unwrap() + .build() + .unwrap(); + let r = run(spec).await; + let msgs = messages_from_report(&ctx(&[("w", EffectClass::Effect)]), &r).unwrap(); + let w = of(&msgs, "w"); + assert_eq!( + w.last().unwrap().msg_type, + PstType::UncertainAfterDisconnect + ); + assert!(!types(&w).contains(&PstType::Failed)); +} + +#[tokio::test] +async fn g5_failure_and_skip_carry_a_reason_code() { + let spec = WorkflowBuilder::default() + .add_task( + "a", + &[], + failing(FailureClass::Rejected, EffectCertainty::NoEffect), + ) + .unwrap() + .add_task("b", &["a"], ok()) + .unwrap() + .build() + .unwrap(); + let r = run(spec).await; + let c = ctx(&[("a", EffectClass::Compute), ("b", EffectClass::Compute)]); + let msgs = messages_from_report(&c, &r).unwrap(); + let a = of(&msgs, "a"); + assert_eq!(a.last().unwrap().msg_type, PstType::Failed); + assert!(matches!( + &a.last().unwrap().payload, + ProgressPayload::Failure { code: "REJECTED", text } if text.contains("boom") + )); + let b = of(&msgs, "b"); + assert_eq!(types(&b), vec![PstType::Failed]); + assert!(matches!( + &b[0].payload, + ProgressPayload::Failure { code: "PREREQUISITE_FAILED", text } if text.contains('a') + )); +} + +#[tokio::test] +async fn g5_refusals() { + let r = run(approval_spec()).await; + + let mut c = approval_ctx(); + c.cause_id.clear(); + assert_eq!( + messages_from_report(&c, &r).unwrap_err(), + ProgressRefusal::NoCause + ); + + let mut c = approval_ctx(); + c.run_id = "run_other".into(); + assert!(matches!( + messages_from_report(&c, &r).unwrap_err(), + ProgressRefusal::RunMismatch { .. } + )); + + let mut c = approval_ctx(); + c.effect_classes.remove(&tid("b")); + assert_eq!( + messages_from_report(&c, &r).unwrap_err(), + ProgressRefusal::UnknownTask { task: tid("b") } + ); + + let mut c = approval_ctx(); + c.action_digests.clear(); + assert_eq!( + messages_from_report(&c, &r).unwrap_err(), + ProgressRefusal::WaitingWithoutActionDigest { task: tid("gate") } + ); + + let mut bad = r.clone(); + bad.snapshot.results.remove(&tid("a")); + assert_eq!( + messages_from_report(&approval_ctx(), &bad).unwrap_err(), + ProgressRefusal::CompletedWithoutResult { task: tid("a") } + ); + + let mut bad = r.clone(); + bad.snapshot.results.get_mut(&tid("a")).unwrap().digest = "raw output".into(); + let e = messages_from_report(&approval_ctx(), &bad).unwrap_err(); + assert_eq!(e, ProgressRefusal::BadResultDigest { task: tid("a") }); + assert_eq!(e.name(), "PROGRESS_BAD_RESULT_DIGEST"); +} + +#[test] +fn g5_context_comes_from_the_stored_pointers() { + let mut tasks = BTreeMap::new(); + tasks.insert(tid("a"), TaskPointers::no_effect()); + let mut w = TaskPointers::no_effect(); + w.effect_class = EffectClass::Effect; + tasks.insert(tid("w"), w); + let p = StoredPointers { + run_id: RUN.into(), + cause_id: CAUSE.into(), + objective_id: OBJECTIVE.into(), + spec_digest: "sha256:spec".into(), + tasks, + }; + let c = ProgressContext::from_pointers(&p); + assert_eq!( + ( + c.run_id.as_str(), + c.cause_id.as_str(), + c.objective_id.as_str() + ), + (RUN, CAUSE, OBJECTIVE) + ); + assert_eq!(c.effect_classes[&tid("a")], EffectClass::None); + assert_eq!(c.effect_classes[&tid("w")], EffectClass::Effect); + assert!(c.action_digests.is_empty()); +}