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
About Files History Releases Proposed changes Issues For developers
GitHub aien-dev/aegis-runtime-mv#62 (code only)
closed derived f98d72cf369add70 #62
Imported from GitHub aien-dev/aegis-runtime-mv#62 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base 727073e9f484e9558e6adbf69090c5ecccd250b3 · Head e72e6e740cf68578e4b1aa61abe3af0af963d8b8
drakestapleton reviewed (COMMENTED) on 2026-10-30 21:48 UTC
Verdict: hold, no code must-fix found in this pass.
This is G3 of the stacked Lane G series and targets lane-g/g2-uncertain-state, not main. Merging it now would only land it on the G2 branch. Land #61 (G2) into main first, then retarget this to main and merge, followed by #63, #64 and #65 in order.
— Grokbot
github-actions[bot] wrote on 2026-10-16 19:46 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-spark. I am AIEN , the automated review gate for the AIENOS project.
Your pull request #62 ("[ALLEN Pi/Spark G3] Rebuild a workflow after a restart from the authoritative records") has undergone automated auditing against the project standards.
✅ Doctrine Diff Audit: PASS
Telemetry Check : Clean (zero tracking or surveillance hooks detected).
Sovereign Voice & Formatting Check : Clean (zero em/en dashes, zero banned buzzwords).
Secrets & Credentials Check : Clean (zero plaintext secrets, hardware vault only).
Status : Project standards verified.
🌿 Sovereign Steward: Contributor Alignment Interview
Greetings @aien-spark. I am AIEN , the automated steward for the AIENOS project.
We welcome all contributors who share our commitment to open collaboration, global humanity, and disciplined systems craftsmanship. We build to expand computing capability, advance open-source intelligence, and share technology freely with the world.
Your pull request #62 ("[ALLEN Pi/Spark G3] Rebuild a workflow after a restart from the authoritative records") is ready for stewardship alignment.
Please respond directly to these four alignment inquiries:
Long-Term Mission Alignment :
This initiative is an enduring engineering commitment to open-source technology for humanity, not a vehicle for short-term hype, social media monetization, or get-rich-quick ventures. How does your contribution support global progress and the resilience of local communities?
Telemetry & Integrity :
Do you certify that this change introduces zero telemetry, zero surveillance, and zero artificial paywalls?
"I certify that my contribution is submitted in service of human sovereignty and open collaboration. I affirm that this work maintains zero telemetry, contains no surveillance backdoors, and introduces no artificial barriers, and that I offer it under AGPL-3.0-or-later, the license that governs this project. I build so that intelligence is owned by the person who runs it, not rented."
Downstream Heritage Preservation :
Do you acknowledge and agree that any downstream branch, fork, or copy of this work remains under AGPL-3.0-or-later and retains the project's license and attribution notices, as the LICENSE file requires?
Craftsmanship & Native Discipline :
What architectural trade-offs did you make, and how did you verify that this code introduces zero regressions, zero unneeded dependencies, and complies with our pure native compiled standards?
Reply to this comment with your affirmation. Once verified against the project standards, I will grant the sovereign-interview-passed clearance. For direct sovereign coordination: Drake Stapleton (drake@aienos.com) and AIEN (aien@aienos.com)
Fetch it
A git bundle of the pull request's head, 18277 bytes.
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/f98d72cf369add70 .bundle -o f98d72cf369add70 .bundle
git fetch f98d72cf369add70 .bundle refs/pull/62/head
Raw bundle · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aegis-runtime-mv
62
e72e6e740cf68578e4b1aa61abe3af0af963d8b8
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":62,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/62","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:39:38Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/docs/WORKFLOW-DAG.md b/docs/WORKFLOW-DAG.md
index bc581ae ..b1f8550 100644
--- a/docs/WORKFLOW-DAG.md
+++ b/docs/WORKFLOW-DAG.md
@@ -52,7 +52,7 @@ Results: `WorkflowSnapshot.results` maps task id to a sha256 digest of the resul
## Restart boundary
-Workflow state is in memory only. After a process restart nothing is recovered and no task is resumed or re-run. `WorkflowSnapshot` is serializable (tested) so a later change can persist it, but no schema, table or recovery path exists. A resumed workflow must not re-run a task whose effect is `Uncertain`; that recovery policy is not designed here. Which record owns each fact of a delegated task, and the rebuild rule after a restart, are in [DELEGATED-DAG.md](DELEGATED-DAG.md).
+Workflow state is in memory only. After a process restart nothing is recovered and no task is resumed or re-run. `WorkflowSnapshot` is serializable (tested) so a later change can persist it, but no schema, table or recovery path exists. A resumed workflow must not re-run a task whose effect is `Uncertain`; that recovery policy is not designed here. Which record owns each fact of a delegated task, and the rebuild rule after a restart, are in [DELEGATED-DAG.md](DELEGATED-DAG.md). `src/orchestration/recovery.rs` (#56) implements that rebuild as a pure host function over an `AuthorityLookup` trait, tested against in-memory fakes; nothing stores the pointers yet and no real authority client exists.
## Not claimed
diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs
index 47d90e2 ..e470366 100644
--- a/src/orchestration/mod.rs
+++ b/src/orchestration/mod.rs
@@ -1,4 +1,5 @@
pub mod budget;
+pub mod recovery;
pub mod run;
pub mod termination;
pub mod trigger;
diff --git a/src/orchestration/recovery.rs b/src/orchestration/recovery.rs
new file mode 100644
index 0000000 ..90abc3f
--- /dev/null
+++ b/src/orchestration/recovery.rs
@@ -0,0 +1,439 @@
+//! Rebuild a workflow's state after a restart by asking the authoritative
+//! records (G3, issue #56; authorities named in `docs/DELEGATED-DAG.md`).
+//!
+//! AEGIS keeps only pointers: per task, the effect intent id, the grant id,
+//! the receipt digest and, for a no-effect task, its result digest. The
+//! state of each task is derived from what the authorities say now, never
+//! from a saved copy. Anything not known stays `Uncertain` and is never run
+//! again; a missing pointer or an unreachable authority is a named refusal,
+//! never a silent fresh start.
+//!
+//! First cut: the lookup is a trait with in-memory fakes in tests. There is
+//! no storage, no sovereign-core client and no network here. The real
+//! adapter reads the sovereign-core effect ledger
+//! (`crates/aien-runtime/src/effects.rs`) and needs
+//! aien-dev/aien-sovereign-core-mv#379; this module does not reimplement it.
+
+use crate::failure::{EffectCertainty, FailureClass, FailureRecord};
+use crate::orchestration::workflow::{
+ ResultHandle, TaskId, TaskState, WorkflowSnapshot, WorkflowSpec,
+};
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::collections::BTreeMap;
+use std::fmt;
+
+/// Tool name stamped on failure records produced by a rebuild.
+pub const RECOVERY_TOOL_NAME: &str = "workflow_recovery";
+
+macro_rules! opaque_id {
+ ($(#[$m:meta])* $name:ident) => {
+ $(#[$m])*
+ #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+ #[serde(transparent)]
+ pub struct $name(String);
+
+ impl $name {
+ pub fn new(id: impl Into<String>) -> Self {
+ Self(id.into())
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+ }
+
+ impl fmt::Display for $name {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+ }
+ };
+}
+
+opaque_id!(
+ /// Names one effect intent record in the sovereign-core effect ledger.
+ EffectIntentId
+);
+opaque_id!(
+ /// Names one grant at the Spark approval desk. Carries no authority.
+ GrantId
+);
+opaque_id!(
+ /// Digest of a receipt held by the authority.
+ ReceiptDigest
+);
+
+/// Effect state as the sovereign-core effect ledger names it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum EffectState {
+ Open,
+ Done,
+ NotDone,
+ Unresolved,
+}
+
+impl EffectState {
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Open => "OPEN",
+ Self::Done => "DONE",
+ Self::NotDone => "NOT_DONE",
+ Self::Unresolved => "UNRESOLVED",
+ }
+ }
+}
+
+/// What the desk says about a grant now.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum GrantStatus {
+ /// Unspent and still valid.
+ Available,
+ /// Spent on an effect intent.
+ Spent,
+ Expired,
+ Revoked,
+}
+
+/// One grant as the desk reports it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct GrantRecord {
+ pub status: GrantStatus,
+ /// The effect intent this grant opened, when the desk can name it.
+ pub intent: Option<EffectIntentId>,
+}
+
+/// The work class of a task, as PST1 `effect_class` names it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EffectClass {
+ /// Touches nothing outside; safe to run again.
+ None,
+ /// Computes only; safe to run again.
+ Compute,
+ /// Changes something in the world; needs a grant.
+ Effect,
+}
+
+/// The pointers AEGIS keeps for one task (DELEGATED-DAG.md section 2).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TaskPointers {
+ pub effect_class: EffectClass,
+ pub effect_intent: Option<EffectIntentId>,
+ pub grant: Option<GrantId>,
+ pub receipt: Option<ReceiptDigest>,
+ /// Digest of a no-effect task's result, once it finished.
+ pub result_digest: Option<String>,
+}
+
+impl TaskPointers {
+ /// A no-effect task that has not finished.
+ pub fn no_effect() -> Self {
+ Self {
+ effect_class: EffectClass::None,
+ effect_intent: None,
+ grant: None,
+ receipt: None,
+ result_digest: None,
+ }
+ }
+}
+
+/// Every pointer AEGIS keeps for one workflow.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct StoredPointers {
+ pub run_id: String,
+ /// Copied from the Pi; never minted here.
+ pub cause_id: String,
+ pub objective_id: String,
+ /// `spec_digest` of the spec this workflow was started with.
+ pub spec_digest: String,
+ pub tasks: BTreeMap<TaskId, TaskPointers>,
+}
+
+/// The lookup could not reach its authority.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LookupError {
+ pub detail: String,
+}
+
+impl LookupError {
+ pub fn new(detail: impl Into<String>) -> Self {
+ Self {
+ detail: detail.into(),
+ }
+ }
+}
+
+/// Read-only questions to the authorities. Implementations must not
+/// change anything they read.
+#[async_trait]
+pub trait AuthorityLookup: Send + Sync {
+ /// `Ok(None)`: the ledger holds no such intent.
+ async fn effect_state(
+ &self,
+ intent: &EffectIntentId,
+ ) -> Result<Option<EffectState>, LookupError>;
+ /// `Ok(None)`: the desk never issued this grant.
+ async fn grant(&self, grant: &GrantId) -> Result<Option<GrantRecord>, LookupError>;
+ async fn receipt_present(&self, receipt: &ReceiptDigest) -> Result<bool, LookupError>;
+}
+
+/// Why a rebuild was refused. Nothing is started after a refusal.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum RecoveryRefusal {
+ /// The spec handed in is not the one the pointers were stored for.
+ SpecMismatch {
+ stored: String,
+ rebuilt: String,
+ },
+ /// A task of the spec has no pointers, or an effect task has no grant.
+ MissingPointers(TaskId),
+ /// Pointers name a task the spec does not have.
+ UnknownTaskPointer(TaskId),
+ LookupUnavailable {
+ task: TaskId,
+ detail: String,
+ },
+ /// A pointer names an effect intent the ledger does not hold.
+ EffectRecordMissing {
+ task: TaskId,
+ intent: EffectIntentId,
+ },
+ /// A pointer names a grant the desk never issued.
+ GrantUnknown {
+ task: TaskId,
+ grant: GrantId,
+ },
+ /// The stored intent and the desk's intent for the grant differ.
+ IntentMismatch {
+ task: TaskId,
+ stored: EffectIntentId,
+ desk: EffectIntentId,
+ },
+ /// The ledger says DONE but no receipt exists for it.
+ DoneWithoutReceipt {
+ task: TaskId,
+ intent: EffectIntentId,
+ },
+}
+
+impl RecoveryRefusal {
+ pub fn name(&self) -> &'static str {
+ match self {
+ Self::SpecMismatch { .. } => "RECOVERY_SPEC_MISMATCH",
+ Self::MissingPointers(_) => "RECOVERY_MISSING_POINTERS",
+ Self::UnknownTaskPointer(_) => "RECOVERY_UNKNOWN_TASK_POINTER",
+ Self::LookupUnavailable { .. } => "RECOVERY_LOOKUP_UNAVAILABLE",
+ Self::EffectRecordMissing { .. } => "RECOVERY_EFFECT_RECORD_MISSING",
+ Self::GrantUnknown { .. } => "RECOVERY_GRANT_UNKNOWN",
+ Self::IntentMismatch { .. } => "RECOVERY_INTENT_MISMATCH",
+ Self::DoneWithoutReceipt { .. } => "RECOVERY_DONE_WITHOUT_RECEIPT",
+ }
+ }
+}
+
+impl fmt::Display for RecoveryRefusal {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}: {self:?}", self.name())
+ }
+}
+
+impl std::error::Error for RecoveryRefusal {}
+
+/// SHA-256 over the task ids and their edges, each sorted, so insertion
+/// order does not matter and any changed edge does.
+pub fn spec_digest(spec: &WorkflowSpec) -> String {
+ let mut lines: Vec<String> = spec
+ .task_ids()
+ .into_iter()
+ .map(|id| {
+ let mut deps: Vec<&str> = spec
+ .dependencies(&id)
+ .unwrap_or_default()
+ .iter()
+ .map(|d| d.as_str())
+ .collect();
+ deps.sort_unstable();
+ format!("{}\t{}\n", id.as_str(), deps.join(","))
+ })
+ .collect();
+ lines.sort_unstable();
+ let digest = Sha256::digest(lines.concat().as_bytes());
+ let mut out = String::from("sha256:");
+ for b in digest {
+ out.push_str(&format!("{b:02x}"));
+ }
+ out
+}
+
+/// What the records alone say about one task, before dependencies.
+enum Derived {
+ Done,
+ /// Never finished and safe to start (no effect, or a valid grant).
+ Runnable,
+ /// Needs a grant that is still valid or newly issued.
+ NeedsGrant,
+ Uncertain(String),
+}
+
+/// Rebuilds the snapshot from the pointers and the authorities. Pure: the
+/// same records give the same snapshot (timestamps in records are 0). No
+/// task body is ever called.
+pub async fn rebuild(
+ spec: &WorkflowSpec,
+ pointers: &StoredPointers,
+ lookup: &dyn AuthorityLookup,
+) -> Result<WorkflowSnapshot, RecoveryRefusal> {
+ let rebuilt = spec_digest(spec);
+ if rebuilt != pointers.spec_digest {
+ return Err(RecoveryRefusal::SpecMismatch {
+ stored: pointers.spec_digest.clone(),
+ rebuilt,
+ });
+ }
+ let ids = spec.task_ids();
+ if let Some(id) = ids.iter().find(|i| !pointers.tasks.contains_key(*i)) {
+ return Err(RecoveryRefusal::MissingPointers(id.clone()));
+ }
+ if let Some(id) = pointers.tasks.keys().find(|k| !ids.contains(k)) {
+ return Err(RecoveryRefusal::UnknownTaskPointer(id.clone()));
+ }
+
+ let mut derived: BTreeMap<TaskId, Derived> = BTreeMap::new();
+ let mut results: BTreeMap<TaskId, ResultHandle> = BTreeMap::new();
+ for id in &ids {
+ let p = &pointers.tasks[id];
+ let d = match p.effect_class {
+ EffectClass::None | EffectClass::Compute => match &p.result_digest {
+ Some(digest) => {
+ results.insert(
+ id.clone(),
+ ResultHandle {
+ digest: digest.clone(),
+ },
+ );
+ Derived::Done
+ }
+ None => Derived::Runnable,
+ },
+ EffectClass::Effect => derive_effect(id, p, lookup).await?,
+ };
+ derived.insert(id.clone(), d);
+ }
+
+ let mut states: BTreeMap<TaskId, TaskState> = BTreeMap::new();
+ for id in &ids {
+ let deps_done = spec
+ .dependencies(id)
+ .unwrap_or_default()
+ .iter()
+ .all(|d| matches!(derived[d], Derived::Done));
+ let state = match &derived[id] {
+ Derived::Done => TaskState::Completed,
+ Derived::Uncertain(why) => {
+ TaskState::Uncertain(uncertain_record(&pointers.run_id, id, why))
+ }
+ Derived::Runnable if deps_done => TaskState::Ready,
+ Derived::NeedsGrant if deps_done => TaskState::WaitingForApproval,
+ Derived::Runnable | Derived::NeedsGrant => TaskState::Pending,
+ };
+ states.insert(id.clone(), state);
+ }
+ Ok(WorkflowSnapshot {
+ run_id: pointers.run_id.clone(),
+ last_seq: 0,
+ states,
+ results,
+ })
+}
+
+async fn derive_effect(
+ id: &TaskId,
+ p: &TaskPointers,
+ lookup: &dyn AuthorityLookup,
+) -> Result<Derived, RecoveryRefusal> {
+ let unavailable = |e: LookupError| RecoveryRefusal::LookupUnavailable {
+ task: id.clone(),
+ detail: e.detail,
+ };
+ let grant_id = p
+ .grant
+ .as_ref()
+ .ok_or_else(|| RecoveryRefusal::MissingPointers(id.clone()))?;
+ let grant = lookup
+ .grant(grant_id)
+ .await
+ .map_err(unavailable)?
+ .ok_or_else(|| RecoveryRefusal::GrantUnknown {
+ task: id.clone(),
+ grant: grant_id.clone(),
+ })?;
+ let intent = match (&p.effect_intent, &grant.intent) {
+ (Some(stored), Some(desk)) if stored != desk => {
+ return Err(RecoveryRefusal::IntentMismatch {
+ task: id.clone(),
+ stored: stored.clone(),
+ desk: desk.clone(),
+ })
+ }
+ (Some(stored), _) => Some(stored.clone()),
+ (None, desk) => desk.clone(),
+ };
+ let Some(intent) = intent else {
+ return Ok(match grant.status {
+ GrantStatus::Available => Derived::Runnable,
+ // Spent, but nobody can name the effect: it may have happened.
+ GrantStatus::Spent => {
+ Derived::Uncertain("grant spent; no effect intent is named".into())
+ }
+ GrantStatus::Expired | GrantStatus::Revoked => Derived::NeedsGrant,
+ });
+ };
+ let state = lookup
+ .effect_state(&intent)
+ .await
+ .map_err(unavailable)?
+ .ok_or_else(|| RecoveryRefusal::EffectRecordMissing {
+ task: id.clone(),
+ intent: intent.clone(),
+ })?;
+ Ok(match state {
+ EffectState::Done => {
+ let done_without_receipt = || RecoveryRefusal::DoneWithoutReceipt {
+ task: id.clone(),
+ intent: intent.clone(),
+ };
+ let receipt = p.receipt.as_ref().ok_or_else(done_without_receipt)?;
+ if !lookup.receipt_present(receipt).await.map_err(unavailable)? {
+ return Err(done_without_receipt());
+ }
+ Derived::Done
+ }
+ EffectState::Open | EffectState::Unresolved => {
+ Derived::Uncertain(format!("effect ledger says {}", state.name()))
+ }
+ EffectState::NotDone if grant.status == GrantStatus::Available => Derived::Runnable,
+ EffectState::NotDone => Derived::NeedsGrant,
+ })
+}
+
+fn uncertain_record(run_id: &str, id: &TaskId, why: &str) -> FailureRecord {
+ FailureRecord::new(
+ 0,
+ run_id,
+ 0,
+ id.to_string(),
+ None,
+ RECOVERY_TOOL_NAME,
+ 1,
+ FailureClass::Uncertain,
+ EffectCertainty::Uncertain,
+ 0,
+ 0,
+ )
+ .with_cause("recovery", why, None)
+}
diff --git a/src/orchestration/workflow.rs b/src/orchestration/workflow.rs
index 8700dff ..80fc836 100644
--- a/src/orchestration/workflow.rs
+++ b/src/orchestration/workflow.rs
@@ -232,6 +232,14 @@ impl WorkflowSpec {
self.tasks.iter().map(|t| t.id.clone()).collect()
}
+ /// The prerequisites of `id`, in the order they were listed.
+ pub fn dependencies(&self, id: &TaskId) -> Option<&[TaskId]> {
+ self.tasks
+ .iter()
+ .find(|t| &t.id == id)
+ .map(|t| t.deps.as_slice())
+ }
+
pub fn len(&self) -> usize {
self.tasks.len()
}
diff --git a/tests/workflow_recovery_tests.rs b/tests/workflow_recovery_tests.rs
new file mode 100644
index 0000000 ..9b4bf06
--- /dev/null
+++ b/tests/workflow_recovery_tests.rs
@@ -0,0 +1,369 @@
+//! Workflow rebuild after a restart (G3, issue #56). The authorities are
+//! in-memory fakes: no storage, no sovereign-core client, no network.
+
+use aegis::orchestration::recovery::{
+ rebuild, spec_digest, AuthorityLookup, EffectClass, EffectIntentId, EffectState, GrantId,
+ GrantRecord, GrantStatus, LookupError, ReceiptDigest, RecoveryRefusal, StoredPointers,
+ TaskPointers,
+};
+use aegis::orchestration::workflow::{runner_fn, WorkflowSpec};
+use aegis::{FailureClass, TaskId, TaskRunner, TaskState};
+use async_trait::async_trait;
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::sync::Arc;
+
+/// The authorities as one in-memory stand-in. `down` makes every call fail
+/// like an unreachable desk or ledger.
+#[derive(Default)]
+struct FakeAuthority {
+ effects: HashMap<EffectIntentId, EffectState>,
+ grants: HashMap<GrantId, GrantRecord>,
+ receipts: HashSet<ReceiptDigest>,
+ down: bool,
+}
+
+#[async_trait]
+impl AuthorityLookup for FakeAuthority {
+ async fn effect_state(
+ &self,
+ intent: &EffectIntentId,
+ ) -> Result<Option<EffectState>, LookupError> {
+ if self.down {
+ return Err(LookupError::new("effect ledger unreachable"));
+ }
+ Ok(self.effects.get(intent).copied())
+ }
+
+ async fn grant(&self, grant: &GrantId) -> Result<Option<GrantRecord>, LookupError> {
+ if self.down {
+ return Err(LookupError::new("approval desk unreachable"));
+ }
+ Ok(self.grants.get(grant).cloned())
+ }
+
+ async fn receipt_present(&self, receipt: &ReceiptDigest) -> Result<bool, LookupError> {
+ if self.down {
+ return Err(LookupError::new("receipt store unreachable"));
+ }
+ Ok(self.receipts.contains(receipt))
+ }
+}
+
+fn never() -> Arc<dyn TaskRunner> {
+ runner_fn(|_c| Box::pin(async { panic!("rebuild must never run a task body") }))
+}
+
+fn tid(s: &str) -> TaskId {
+ TaskId::new(s)
+}
+
+/// write (effect) -> report (no effect); lint (no effect) independent.
+fn spec() -> WorkflowSpec {
+ WorkflowSpec::builder()
+ .add_task("write", &[], never())
+ .unwrap()
+ .add_task("report", &["write"], never())
+ .unwrap()
+ .add_task("lint", &[], never())
+ .unwrap()
+ .build()
+ .unwrap()
+}
+
+fn intent(s: &str) -> EffectIntentId {
+ EffectIntentId::new(s)
+}
+fn grant(s: &str) -> GrantId {
+ GrantId::new(s)
+}
+fn receipt(s: &str) -> ReceiptDigest {
+ ReceiptDigest::new(s)
+}
+
+fn pointers(write: TaskPointers) -> StoredPointers {
+ let mut tasks = BTreeMap::new();
+ tasks.insert(tid("write"), write);
+ tasks.insert(tid("report"), TaskPointers::no_effect());
+ tasks.insert(tid("lint"), TaskPointers::no_effect());
+ StoredPointers {
+ run_id: "run_g3".into(),
+ cause_id: "cause-1".into(),
+ objective_id: "objective-1".into(),
+ spec_digest: spec_digest(&spec()),
+ tasks,
+ }
+}
+
+fn effect_pointers(i: Option<&str>, g: &str, r: Option<&str>) -> TaskPointers {
+ TaskPointers {
+ effect_class: EffectClass::Effect,
+ effect_intent: i.map(intent),
+ grant: Some(grant(g)),
+ receipt: r.map(receipt),
+ result_digest: None,
+ }
+}
+
+fn spent(i: &str) -> GrantRecord {
+ GrantRecord {
+ status: GrantStatus::Spent,
+ intent: Some(intent(i)),
+ }
+}
+
+#[tokio::test]
+async fn done_with_receipt_is_completed_and_never_runs_again() {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::Done);
+ a.grants.insert(grant("g1"), spent("i1"));
+ a.receipts.insert(receipt("r1"));
+ let p = pointers(effect_pointers(Some("i1"), "g1", Some("r1")));
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(s.states[&tid("write")], TaskState::Completed);
+ assert!(s.states[&tid("write")].is_terminal());
+ // Its no-effect dependent never finished, so it may run.
+ assert_eq!(s.states[&tid("report")], TaskState::Ready);
+ assert_eq!(s.states[&tid("lint")], TaskState::Ready);
+ assert_eq!(s.run_id, "run_g3");
+}
+
+#[tokio::test]
+async fn open_and_unresolved_are_uncertain_and_dependents_wait() {
+ for state in [EffectState::Open, EffectState::Unresolved] {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), state);
+ a.grants.insert(grant("g1"), spent("i1"));
+ let p = pointers(effect_pointers(Some("i1"), "g1", None));
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ match &s.states[&tid("write")] {
+ TaskState::Uncertain(f) => assert_eq!(f.class, FailureClass::Uncertain),
+ other => panic!("{state:?}: {other:?}"),
+ }
+ assert_eq!(s.states[&tid("report")], TaskState::Pending, "{state:?}");
+ }
+}
+
+#[tokio::test]
+async fn not_done_runs_again_only_under_a_valid_grant() {
+ // Still-valid grant: may run again.
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::NotDone);
+ a.grants.insert(
+ grant("g1"),
+ GrantRecord {
+ status: GrantStatus::Available,
+ intent: None,
+ },
+ );
+ let p = pointers(effect_pointers(Some("i1"), "g1", None));
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(s.states[&tid("write")], TaskState::Ready);
+
+ // Spent (or expired, or revoked) grant: needs a newly issued one.
+ for status in [
+ GrantStatus::Spent,
+ GrantStatus::Expired,
+ GrantStatus::Revoked,
+ ] {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::NotDone);
+ a.grants.insert(
+ grant("g1"),
+ GrantRecord {
+ status,
+ intent: Some(intent("i1")),
+ },
+ );
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(
+ s.states[&tid("write")],
+ TaskState::WaitingForApproval,
+ "{status:?}"
+ );
+ assert_eq!(s.states[&tid("report")], TaskState::Pending);
+ }
+}
+
+#[tokio::test]
+async fn spent_grant_without_effect_record_pointer_is_uncertain() {
+ // Kill between intent and pointer write: AEGIS never stored the intent
+ // id, but the desk says the grant was spent on one that is OPEN.
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::Open);
+ a.grants.insert(grant("g1"), spent("i1"));
+ let p = pointers(effect_pointers(None, "g1", None));
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert!(matches!(s.states[&tid("write")], TaskState::Uncertain(_)));
+ // Spent with no intent the desk can name: still not known.
+ let mut a = FakeAuthority::default();
+ a.grants.insert(
+ grant("g1"),
+ GrantRecord {
+ status: GrantStatus::Spent,
+ intent: None,
+ },
+ );
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert!(matches!(s.states[&tid("write")], TaskState::Uncertain(_)));
+}
+
+#[tokio::test]
+async fn unstarted_effect_task_with_available_grant_is_ready() {
+ let mut a = FakeAuthority::default();
+ a.grants.insert(
+ grant("g1"),
+ GrantRecord {
+ status: GrantStatus::Available,
+ intent: None,
+ },
+ );
+ let p = pointers(effect_pointers(None, "g1", None));
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(s.states[&tid("write")], TaskState::Ready);
+}
+
+#[tokio::test]
+async fn no_effect_task_with_result_is_completed() {
+ let a = FakeAuthority::default();
+ let mut p = pointers(TaskPointers::no_effect());
+ p.tasks.get_mut(&tid("lint")).unwrap().result_digest = Some("sha256:ab".into());
+ let s = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(s.states[&tid("lint")], TaskState::Completed);
+ assert_eq!(s.results[&tid("lint")].digest, "sha256:ab");
+ assert_eq!(s.states[&tid("write")], TaskState::Ready);
+}
+
+// ---- named refusals, never a silent fresh start ----
+
+#[tokio::test]
+async fn missing_pointers_are_refused_by_name() {
+ let a = FakeAuthority::default();
+ let mut p = pointers(TaskPointers::no_effect());
+ p.tasks.remove(&tid("report"));
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert_eq!(e, RecoveryRefusal::MissingPointers(tid("report")));
+ assert_eq!(e.name(), "RECOVERY_MISSING_POINTERS");
+}
+
+#[tokio::test]
+async fn unknown_task_pointer_is_refused() {
+ let a = FakeAuthority::default();
+ let mut p = pointers(TaskPointers::no_effect());
+ p.tasks.insert(tid("ghost"), TaskPointers::no_effect());
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert_eq!(e, RecoveryRefusal::UnknownTaskPointer(tid("ghost")));
+}
+
+#[tokio::test]
+async fn changed_spec_is_refused() {
+ let a = FakeAuthority::default();
+ let mut p = pointers(TaskPointers::no_effect());
+ p.spec_digest = "sha256:00".into();
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert!(matches!(e, RecoveryRefusal::SpecMismatch { .. }), "{e:?}");
+}
+
+#[tokio::test]
+async fn unreachable_authority_is_refused() {
+ let a = FakeAuthority {
+ down: true,
+ ..Default::default()
+ };
+ let p = pointers(effect_pointers(Some("i1"), "g1", None));
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert!(
+ matches!(&e, RecoveryRefusal::LookupUnavailable { task, .. } if *task == tid("write")),
+ "{e:?}"
+ );
+}
+
+#[tokio::test]
+async fn effect_task_without_grant_or_unknown_records_is_refused() {
+ let a = FakeAuthority::default();
+ // A pointer naming an intent the ledger does not hold.
+ let mut a2 = FakeAuthority::default();
+ a2.grants.insert(grant("g1"), spent("i1"));
+ let p = pointers(effect_pointers(Some("i1"), "g1", None));
+ let e = rebuild(&spec(), &p, &a2).await.unwrap_err();
+ assert!(
+ matches!(e, RecoveryRefusal::EffectRecordMissing { .. }),
+ "{e:?}"
+ );
+ // A grant the desk never issued.
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert!(matches!(e, RecoveryRefusal::GrantUnknown { .. }), "{e:?}");
+ // An effect task with no grant pointer at all.
+ let mut bare = effect_pointers(None, "g1", None);
+ bare.grant = None;
+ let e = rebuild(&spec(), &pointers(bare), &a).await.unwrap_err();
+ assert_eq!(e, RecoveryRefusal::MissingPointers(tid("write")));
+}
+
+#[tokio::test]
+async fn pointer_and_desk_disagreeing_on_the_intent_is_refused() {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::Done);
+ a.effects.insert(intent("i2"), EffectState::Done);
+ a.grants.insert(grant("g1"), spent("i2"));
+ let p = pointers(effect_pointers(Some("i1"), "g1", Some("r1")));
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert!(matches!(e, RecoveryRefusal::IntentMismatch { .. }), "{e:?}");
+}
+
+/// Negative control (#56 item 4): DONE without a receipt is refused, both
+/// when no receipt pointer was stored and when the authority does not hold
+/// the receipt the pointer names.
+#[tokio::test]
+async fn negative_control_done_without_receipt_is_refused() {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::Done);
+ a.grants.insert(grant("g1"), spent("i1"));
+ for r in [None, Some("r-missing")] {
+ let p = pointers(effect_pointers(Some("i1"), "g1", r));
+ let e = rebuild(&spec(), &p, &a).await.unwrap_err();
+ assert!(
+ matches!(&e, RecoveryRefusal::DoneWithoutReceipt { task, .. } if *task == tid("write")),
+ "{r:?}: {e:?}"
+ );
+ assert_eq!(e.name(), "RECOVERY_DONE_WITHOUT_RECEIPT");
+ }
+}
+
+#[tokio::test]
+async fn rebuild_is_a_pure_function_of_the_records() {
+ let mut a = FakeAuthority::default();
+ a.effects.insert(intent("i1"), EffectState::Unresolved);
+ a.grants.insert(grant("g1"), spent("i1"));
+ let p = pointers(effect_pointers(Some("i1"), "g1", None));
+ let s1 = rebuild(&spec(), &p, &a).await.unwrap();
+ let s2 = rebuild(&spec(), &p, &a).await.unwrap();
+ assert_eq!(
+ serde_json::to_string(&s1).unwrap(),
+ serde_json::to_string(&s2).unwrap()
+ );
+}
+
+#[test]
+fn spec_digest_ignores_insertion_order_and_sees_edges() {
+ let a = spec();
+ let b = WorkflowSpec::builder()
+ .add_task("lint", &[], never())
+ .unwrap()
+ .add_task("report", &["write"], never())
+ .unwrap()
+ .add_task("write", &[], never())
+ .unwrap()
+ .build()
+ .unwrap();
+ assert_eq!(spec_digest(&a), spec_digest(&b));
+ let c = WorkflowSpec::builder()
+ .add_task("write", &[], never())
+ .unwrap()
+ .add_task("report", &[], never())
+ .unwrap()
+ .add_task("lint", &[], never())
+ .unwrap()
+ .build()
+ .unwrap();
+ assert_ne!(spec_digest(&a), spec_digest(&c));
+}