interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aegis-runtime-mv / src / orchestration / progress.rs

401 lines · 13887 bytes Raw Blame History
1//! Workflow state to PST1 progress messages (issue #58, lane G5).
2//!
3//! A pure mapping from what the workflow recorded to the message types of
4//! PST1 Draft v0 section 5 (aien-dev/aien-protocols-mv#28). Nothing here
5//! encodes bytes or touches a network: the first cut stops at typed
6//! messages. Status comes only from recorded task state, never from model
7//! text, and a message is refused rather than filled with a guess.
8//!
9//! The type values are copied from the PST1 table here so AEGIS does not
10//! depend on the draft `aien-pi-spark-task` crate before it merges. When it
11//! does, `PstType` should become that crate's type (item 4, the bytes).
12//!
13//! Not here yet: `accepted` (the admission answer, owned by the request
14//! store), `text_chunk`, `receipt_reference`, the `resume_snapshot` built
15//! from `recovery::rebuild` (item 3), and encoding (item 4).
16
17use crate::failure::{EffectCertainty, FailureClass, FailureRecord};
18use crate::orchestration::recovery::{EffectClass, StoredPointers};
19use crate::orchestration::workflow::{TaskId, TaskState, WorkflowReport, WorkflowSnapshot};
20use std::collections::BTreeMap;
21use std::fmt;
22
23/// PST1 message types, section 5. The discriminant is the wire value.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum PstType {
26 Request = 1,
27 Accepted = 2,
28 Queued = 3,
29 Running = 4,
30 TextChunk = 5,
31 WaitingForApproval = 6,
32 Completed = 7,
33 Failed = 8,
34 Cancelled = 9,
35 UncertainAfterDisconnect = 10,
36 ResumeSnapshot = 11,
37 ReceiptReference = 12,
38 CancelRequest = 13,
39 ResumeRequest = 14,
40}
41
42impl PstType {
43 /// Every type in wire order.
44 pub const ALL: [PstType; 14] = [
45 Self::Request,
46 Self::Accepted,
47 Self::Queued,
48 Self::Running,
49 Self::TextChunk,
50 Self::WaitingForApproval,
51 Self::Completed,
52 Self::Failed,
53 Self::Cancelled,
54 Self::UncertainAfterDisconnect,
55 Self::ResumeSnapshot,
56 Self::ReceiptReference,
57 Self::CancelRequest,
58 Self::ResumeRequest,
59 ];
60
61 pub fn value(self) -> u8 {
62 self as u8
63 }
64
65 pub fn name(self) -> &'static str {
66 match self {
67 Self::Request => "request",
68 Self::Accepted => "accepted",
69 Self::Queued => "queued",
70 Self::Running => "running",
71 Self::TextChunk => "text_chunk",
72 Self::WaitingForApproval => "waiting_for_approval",
73 Self::Completed => "completed",
74 Self::Failed => "failed",
75 Self::Cancelled => "cancelled",
76 Self::UncertainAfterDisconnect => "uncertain_after_disconnect",
77 Self::ResumeSnapshot => "resume_snapshot",
78 Self::ReceiptReference => "receipt_reference",
79 Self::CancelRequest => "cancel_request",
80 Self::ResumeRequest => "resume_request",
81 }
82 }
83
84 /// The Pi sends `request`, `cancel_request` and `resume_request`; the
85 /// Spark sends every other type.
86 pub fn sent_by_spark(self) -> bool {
87 !matches!(
88 self,
89 Self::Request | Self::CancelRequest | Self::ResumeRequest
90 )
91 }
92}
93
94/// What the payload will carry once encoded. Digests stay in the
95/// `sha256:<64 hex>` form AEGIS records; encoding turns them into 32 bytes.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum ProgressPayload {
98 Empty,
99 /// `waiting_for_approval`: the action awaiting approval.
100 ActionDigest(String),
101 /// `completed`: the result digest from `WorkflowSnapshot.results`,
102 /// never the raw output.
103 ResultDigest(String),
104 /// `failed`: a short reason code and text.
105 Failure {
106 code: &'static str,
107 text: String,
108 },
109}
110
111/// One progress message, before encoding.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct ProgressMessage {
114 pub msg_type: PstType,
115 /// Copied from the Pi's request; never minted here.
116 pub cause_id: String,
117 pub origin_run_id: String,
118 pub objective_id: String,
119 pub task_id: TaskId,
120 /// Messages of one task, from 0, rising by one.
121 pub ordinal: u32,
122 pub effect_class: EffectClass,
123 pub payload: ProgressPayload,
124}
125
126/// The ids every message carries, read from the stored records.
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
128pub struct ProgressContext {
129 pub run_id: String,
130 pub cause_id: String,
131 pub objective_id: String,
132 pub effect_classes: BTreeMap<TaskId, EffectClass>,
133 /// Digest of the action each approval-waiting task asks about. AEGIS
134 /// records none yet; the approval desk will (G6, sovereign-core#379).
135 pub action_digests: BTreeMap<TaskId, String>,
136}
137
138impl ProgressContext {
139 /// The ids and effect classes from the G3 stored pointers. Action
140 /// digests are not in those pointers and start empty.
141 pub fn from_pointers(p: &StoredPointers) -> Self {
142 Self {
143 run_id: p.run_id.clone(),
144 cause_id: p.cause_id.clone(),
145 objective_id: p.objective_id.clone(),
146 effect_classes: p
147 .tasks
148 .iter()
149 .map(|(id, t)| (id.clone(), t.effect_class))
150 .collect(),
151 action_digests: BTreeMap::new(),
152 }
153 }
154}
155
156/// Why no message could be built. Nothing is sent in its place.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum ProgressRefusal {
159 /// No cause id: one is never minted here (PST1 section 7, `PST_NO_CAUSE`).
160 NoCause,
161 RunMismatch {
162 context: String,
163 report: String,
164 },
165 /// No effect class is recorded for this task.
166 UnknownTask {
167 task: TaskId,
168 },
169 UnknownEventState {
170 task: TaskId,
171 state: String,
172 },
173 MissingFailureRecord {
174 task: TaskId,
175 },
176 CompletedWithoutResult {
177 task: TaskId,
178 },
179 /// The recorded result is not a `sha256:<64 hex>` digest.
180 BadResultDigest {
181 task: TaskId,
182 },
183 WaitingWithoutActionDigest {
184 task: TaskId,
185 },
186}
187
188impl ProgressRefusal {
189 pub fn name(&self) -> &'static str {
190 match self {
191 Self::NoCause => "PROGRESS_NO_CAUSE",
192 Self::RunMismatch { .. } => "PROGRESS_RUN_MISMATCH",
193 Self::UnknownTask { .. } => "PROGRESS_UNKNOWN_TASK",
194 Self::UnknownEventState { .. } => "PROGRESS_UNKNOWN_EVENT_STATE",
195 Self::MissingFailureRecord { .. } => "PROGRESS_MISSING_FAILURE_RECORD",
196 Self::CompletedWithoutResult { .. } => "PROGRESS_COMPLETED_WITHOUT_RESULT",
197 Self::BadResultDigest { .. } => "PROGRESS_BAD_RESULT_DIGEST",
198 Self::WaitingWithoutActionDigest { .. } => "PROGRESS_WAITING_WITHOUT_ACTION_DIGEST",
199 }
200 }
201}
202
203impl fmt::Display for ProgressRefusal {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 write!(f, "{}: {self:?}", self.name())
206 }
207}
208
209impl std::error::Error for ProgressRefusal {}
210
211/// The one message type a task state is reported as.
212///
213/// Pending and Ready are both `queued`. Skipped is `failed` with the reason
214/// `PREREQUISITE_FAILED` (PST1 has no skipped type). A Failed task whose
215/// effect certainty is Uncertain is reported as not known, never as
216/// `failed` (PST1 section 8 item 3), even though the workflow keeps it
217/// Failed. PST1 names that type `uncertain_after_disconnect`; its meaning,
218/// "not known whether it happened", is what is reported.
219pub fn message_type(state: &TaskState) -> PstType {
220 match state {
221 TaskState::Pending | TaskState::Ready => PstType::Queued,
222 TaskState::Running => PstType::Running,
223 TaskState::WaitingForApproval => PstType::WaitingForApproval,
224 TaskState::Completed => PstType::Completed,
225 TaskState::Failed(f) if f.effect_certainty == EffectCertainty::Uncertain => {
226 PstType::UncertainAfterDisconnect
227 }
228 TaskState::Failed(_) | TaskState::Skipped { .. } => PstType::Failed,
229 TaskState::Cancelled => PstType::Cancelled,
230 TaskState::Uncertain(_) => PstType::UncertainAfterDisconnect,
231 }
232}
233
234/// One message for one task in one state, with the given ordinal.
235pub fn message_for_state(
236 ctx: &ProgressContext,
237 snapshot: &WorkflowSnapshot,
238 task: &TaskId,
239 state: &TaskState,
240 ordinal: u32,
241) -> Result<ProgressMessage, ProgressRefusal> {
242 check_context(ctx, snapshot)?;
243 let effect_class = *ctx
244 .effect_classes
245 .get(task)
246 .ok_or_else(|| ProgressRefusal::UnknownTask { task: task.clone() })?;
247 let msg_type = message_type(state);
248 let payload = match msg_type {
249 PstType::Completed => {
250 let r = snapshot
251 .results
252 .get(task)
253 .ok_or_else(|| ProgressRefusal::CompletedWithoutResult { task: task.clone() })?;
254 if !is_sha256(&r.digest) {
255 return Err(ProgressRefusal::BadResultDigest { task: task.clone() });
256 }
257 ProgressPayload::ResultDigest(r.digest.clone())
258 }
259 PstType::WaitingForApproval => {
260 let d = ctx.action_digests.get(task).ok_or_else(|| {
261 ProgressRefusal::WaitingWithoutActionDigest { task: task.clone() }
262 })?;
263 ProgressPayload::ActionDigest(d.clone())
264 }
265 PstType::Failed => match state {
266 TaskState::Skipped { prerequisite } => ProgressPayload::Failure {
267 code: "PREREQUISITE_FAILED",
268 text: format!("prerequisite {prerequisite} did not complete"),
269 },
270 TaskState::Failed(f) => ProgressPayload::Failure {
271 code: failure_code(f.class),
272 text: failure_text(f),
273 },
274 _ => ProgressPayload::Empty,
275 },
276 _ => ProgressPayload::Empty,
277 };
278 Ok(ProgressMessage {
279 msg_type,
280 cause_id: ctx.cause_id.clone(),
281 origin_run_id: snapshot.run_id.clone(),
282 objective_id: ctx.objective_id.clone(),
283 task_id: task.clone(),
284 ordinal,
285 effect_class,
286 payload,
287 })
288}
289
290/// Every progress message of a finished (or stopped) run, in ledger order.
291///
292/// Ordinals count each task's messages from 0. A transition that maps to
293/// the same type as that task's previous message adds nothing and is not
294/// repeated (for example Pending then Ready, both `queued`).
295pub fn messages_from_report(
296 ctx: &ProgressContext,
297 report: &WorkflowReport,
298) -> Result<Vec<ProgressMessage>, ProgressRefusal> {
299 let snap = &report.snapshot;
300 check_context(ctx, snap)?;
301 let mut last: BTreeMap<TaskId, (u32, PstType)> = BTreeMap::new();
302 let mut out = Vec::new();
303 for e in &report.events {
304 let Some(task) = &e.task_id else {
305 continue;
306 };
307 let state = state_for_event(report, task, &e.state)?;
308 let ty = message_type(&state);
309 let ordinal = match last.get(task) {
310 Some((_, prev)) if *prev == ty => continue,
311 Some((n, _)) => n + 1,
312 None => 0,
313 };
314 out.push(message_for_state(ctx, snap, task, &state, ordinal)?);
315 last.insert(task.clone(), (ordinal, ty));
316 }
317 Ok(out)
318}
319
320fn check_context(ctx: &ProgressContext, snap: &WorkflowSnapshot) -> Result<(), ProgressRefusal> {
321 if ctx.cause_id.is_empty() {
322 return Err(ProgressRefusal::NoCause);
323 }
324 if ctx.run_id != snap.run_id {
325 return Err(ProgressRefusal::RunMismatch {
326 context: ctx.run_id.clone(),
327 report: snap.run_id.clone(),
328 });
329 }
330 Ok(())
331}
332
333/// The ledger keeps a state name per event; the records behind a failed,
334/// uncertain or skipped state come from the report.
335fn state_for_event(
336 report: &WorkflowReport,
337 task: &TaskId,
338 name: &str,
339) -> Result<TaskState, ProgressRefusal> {
340 let record = || {
341 report
342 .failures
343 .get(task)
344 .cloned()
345 .ok_or_else(|| ProgressRefusal::MissingFailureRecord { task: task.clone() })
346 };
347 Ok(match name {
348 "pending" => TaskState::Pending,
349 "ready" => TaskState::Ready,
350 "running" => TaskState::Running,
351 "waiting_for_approval" => TaskState::WaitingForApproval,
352 "completed" => TaskState::Completed,
353 "cancelled" => TaskState::Cancelled,
354 "failed" => TaskState::Failed(record()?),
355 "uncertain" => TaskState::Uncertain(record()?),
356 "skipped" => match report.snapshot.states.get(task) {
357 Some(s @ TaskState::Skipped { .. }) => s.clone(),
358 _ => return Err(ProgressRefusal::MissingFailureRecord { task: task.clone() }),
359 },
360 other => {
361 return Err(ProgressRefusal::UnknownEventState {
362 task: task.clone(),
363 state: other.to_string(),
364 })
365 }
366 })
367}
368
369fn failure_code(class: FailureClass) -> &'static str {
370 match class {
371 FailureClass::Rejected => "REJECTED",
372 FailureClass::Unavailable => "UNAVAILABLE",
373 FailureClass::Timeout => "TIMEOUT",
374 FailureClass::Cancelled => "CANCELLED",
375 FailureClass::Uncertain => "UNCERTAIN",
376 FailureClass::Failed => "FAILED",
377 FailureClass::Malformed => "MALFORMED",
378 FailureClass::ApprovalPending => "APPROVAL_PENDING",
379 }
380}
381
382/// The recorded cause messages (already length capped by the failure
383/// record), joined; the class name when there are none.
384fn failure_text(f: &FailureRecord) -> String {
385 if f.cause.is_empty() {
386 return failure_code(f.class).to_lowercase();
387 }
388 f.cause
389 .iter()
390 .map(|c| c.message.as_str())
391 .collect::<Vec<_>>()
392 .join("; ")
393}
394
395fn is_sha256(d: &str) -> bool {
396 d.strip_prefix("sha256:").is_some_and(|h| {
397 h.len() == 64
398 && h.bytes()
399 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
400 })
401}