Skip to main content

engenho_controllers/
roceiro.rs

1//! Roceiro — the materializer trait.
2//!
3//! Wraps a [`BuildBackend`](crate::drv_build::BuildBackend) + a
4//! [`Verifier`](engenho_substrate::Verifier) into one typed surface the
5//! [`PlantioController`](crate::plantio::PlantioController) dispatches:
6//! "materialize this Stage on this node, run its verifiers,
7//! return a typed `MaterializationReceipt`."
8//!
9//! ## Trait shape
10//!
11//! Pluggable so consumers can swap in:
12//!   * `FakeRoceiro` — deterministic for tests
13//!   * `BuildBackendRoceiro` — production: drives a `BuildBackend`
14//!      + a Verifier + ingests into a `DerivationCacheBackend`
15//!   * `SuiRoceiro` (future) — production: invokes sui directly
16//!
17//! ## Composition
18//!
19//! ```text
20//! PlantioController.tick():
21//!     for each ready stage in topo order:
22//!         for each placement target:
23//!             roceiro.materialize(stage, target) → MaterializationReceipt
24//!             ledger.ingest(stage.id, threshold, &receipt)
25//!             if ledger says Reached: mark stage Confirmed, unblock deps
26//!             if ledger says Dissent: emit Anomaly
27//! ```
28
29use std::sync::Arc;
30
31use async_trait::async_trait;
32use engenho_substrate::{MaterializationReceipt, NodeId, ReceiptKind, Stage, StageId};
33use thiserror::Error;
34use tokio::sync::Mutex;
35
36/// Errors the materializer surfaces.
37#[derive(Debug, Clone, Error)]
38pub enum RoceiroError {
39    /// Backend (build / verifier / cache) failed.
40    #[error("backend: {0}")]
41    Backend(String),
42    /// Stage is malformed for this materializer (e.g. shape
43    /// unsupported by the backend).
44    #[error("unsupported stage {stage}: {detail}")]
45    UnsupportedStage {
46        /// The stage that couldn't be materialized.
47        stage: StageId,
48        /// Why.
49        detail: String,
50    },
51    /// Verification produced a typed denial.
52    #[error("verification denied for stage {stage}: {detail}")]
53    VerificationDenied {
54        /// The stage that failed verification.
55        stage: StageId,
56        /// Verifier's reason.
57        detail: String,
58    },
59}
60
61engenho_substrate::impl_error_kind! {
62    RoceiroError {
63        (Backend(_)) => "backend",
64        { UnsupportedStage { .. } } => "unsupported_stage",
65        { VerificationDenied { .. } } => "verification_denied",
66    }
67}
68
69/// The materializer trait.
70#[async_trait]
71pub trait Roceiro: Send + Sync {
72    /// Backend identifier for telemetry.
73    fn name(&self) -> &'static str;
74
75    /// Materialize `stage` on `node`. Returns the typed receipt the
76    /// `PlantioController` feeds into the ledger.
77    ///
78    /// # Errors
79    /// [`RoceiroError::Backend`] for build / cache failures;
80    /// [`RoceiroError::UnsupportedStage`] for shape mismatches;
81    /// [`RoceiroError::VerificationDenied`] if a verifier denied.
82    async fn materialize(
83        &self,
84        stage: &Stage,
85        node: NodeId,
86    ) -> Result<MaterializationReceipt, RoceiroError>;
87}
88
89// =================================================================
90// FakeRoceiro — deterministic in-memory materializer for tests
91// =================================================================
92
93/// In-memory materializer. Records every materialize call;
94/// produces synthetic receipts whose evidence is keyed by
95/// (`stage_id`, shape) — all nodes agree on the same bytes for a
96/// given stage. Use `dissent_on()` to inject byzantine-emitter
97/// behavior where each node reports a different evidence hash.
98#[derive(Default, Clone)]
99pub struct FakeRoceiro {
100    inner: Arc<Mutex<FakeRoceiroState>>,
101}
102
103#[derive(Default)]
104struct FakeRoceiroState {
105    /// Stage IDs whose `materialize()` should fail with Backend.
106    backend_fail: std::collections::BTreeSet<StageId>,
107    /// Stage IDs whose `materialize()` should deny verification.
108    deny_verify: std::collections::BTreeSet<StageId>,
109    /// Stage IDs whose evidence should diverge per node (byzantine).
110    dissent: std::collections::BTreeSet<StageId>,
111    /// Call log for test assertion.
112    calls: Vec<(StageId, NodeId)>,
113}
114
115impl FakeRoceiro {
116    /// Fresh roceiro — every materialize succeeds.
117    #[must_use]
118    pub fn new() -> Self {
119        Self::default()
120    }
121
122    /// Mark `stage_id` to fail with Backend on next + subsequent calls.
123    pub async fn fail_backend(&self, stage_id: StageId) {
124        self.inner.lock().await.backend_fail.insert(stage_id);
125    }
126
127    /// Mark `stage_id` to deny verification on next + subsequent calls.
128    pub async fn deny_verification(&self, stage_id: StageId) {
129        self.inner.lock().await.deny_verify.insert(stage_id);
130    }
131
132    /// Make `stage_id` produce divergent evidence per node — the
133    /// `QuorumTracker` will report Dissent. Simulates byzantine
134    /// emitter behavior for testing the dissent path.
135    pub async fn dissent_on(&self, stage_id: StageId) {
136        self.inner.lock().await.dissent.insert(stage_id);
137    }
138
139    /// Snapshot of materialize calls.
140    pub async fn calls(&self) -> Vec<(StageId, NodeId)> {
141        self.inner.lock().await.calls.clone()
142    }
143
144    /// Count of materialize calls.
145    pub async fn call_count(&self) -> usize {
146        self.inner.lock().await.calls.len()
147    }
148}
149
150#[async_trait]
151impl Roceiro for FakeRoceiro {
152    fn name(&self) -> &'static str {
153        "fake"
154    }
155
156    async fn materialize(
157        &self,
158        stage: &Stage,
159        node: NodeId,
160    ) -> Result<MaterializationReceipt, RoceiroError> {
161        let mut state = self.inner.lock().await;
162        state.calls.push((stage.id.clone(), node));
163        if state.backend_fail.contains(&stage.id) {
164            return Err(RoceiroError::Backend(format!(
165                "fake backend failure for {}",
166                stage.id
167            )));
168        }
169        if state.deny_verify.contains(&stage.id) {
170            return Err(RoceiroError::VerificationDenied {
171                stage: stage.id.clone(),
172                detail: "fake denial".into(),
173            });
174        }
175        let dissent = state.dissent.contains(&stage.id);
176        drop(state);
177        // Synthetic subject = BLAKE3(stage_id). Evidence is
178        // BLAKE3(stage_id + shape_tag) so faithful nodes agree.
179        // For dissent simulation, include the node id so each
180        // node reports a different evidence hash.
181        let subject = *blake3::hash(stage.id.as_str().as_bytes()).as_bytes();
182        let mut composed = stage.id.as_str().as_bytes().to_vec();
183        composed.extend_from_slice(stage.shape.tag().as_bytes());
184        if dissent {
185            composed.extend_from_slice(&node.0);
186        }
187        let evidence = *blake3::hash(&composed).as_bytes();
188        Ok(MaterializationReceipt::new(
189            ReceiptKind::Shape(stage.shape.tag()),
190            subject,
191            node,
192            42, // synthetic deterministic timestamp
193            evidence,
194        ))
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use engenho_substrate::{Placement, WorkloadShape};
202
203    fn n(b: u8) -> NodeId {
204        NodeId::new([b; 32])
205    }
206
207    fn stage(id: &str) -> Stage {
208        Stage::pinned(id, WorkloadShape::OciImage, n(1))
209    }
210
211    #[tokio::test]
212    async fn materialize_default_succeeds_and_records_call() {
213        let r = FakeRoceiro::new();
214        let receipt = r.materialize(&stage("build"), n(7)).await.unwrap();
215        assert_eq!(r.call_count().await, 1);
216        match receipt.kind {
217            ReceiptKind::Shape(tag) => assert_eq!(tag, "oci_image"),
218            _ => panic!("expected Shape kind"),
219        }
220        assert_eq!(receipt.emitter, n(7));
221    }
222
223    #[tokio::test]
224    async fn receipt_subject_is_deterministic_per_stage_id() {
225        let r = FakeRoceiro::new();
226        let r1 = r.materialize(&stage("x"), n(1)).await.unwrap();
227        let r2 = r.materialize(&stage("x"), n(2)).await.unwrap();
228        // Same subject (stage), different emitter.
229        assert_eq!(r1.subject, r2.subject);
230        assert_ne!(r1.emitter, r2.emitter);
231    }
232
233    #[tokio::test]
234    async fn faithful_nodes_agree_on_evidence_for_same_stage() {
235        let r = FakeRoceiro::new();
236        let r1 = r.materialize(&stage("x"), n(1)).await.unwrap();
237        let r2 = r.materialize(&stage("x"), n(2)).await.unwrap();
238        // Default: nodes produce the SAME evidence (faithful
239        // materialization). Quorum reaches Reached, not Dissent.
240        assert_eq!(r1.evidence_hash, r2.evidence_hash);
241        assert_ne!(r1.emitter, r2.emitter);
242    }
243
244    #[tokio::test]
245    async fn dissent_on_makes_nodes_disagree() {
246        let r = FakeRoceiro::new();
247        r.dissent_on(StageId::new("byz")).await;
248        let r1 = r.materialize(&stage("byz"), n(1)).await.unwrap();
249        let r2 = r.materialize(&stage("byz"), n(2)).await.unwrap();
250        // With dissent_on, nodes report divergent evidence.
251        assert_ne!(r1.evidence_hash, r2.evidence_hash);
252    }
253
254    #[tokio::test]
255    async fn fail_backend_marks_stage_to_fail() {
256        let r = FakeRoceiro::new();
257        r.fail_backend(StageId::new("bad")).await;
258        let err = r.materialize(&stage("bad"), n(1)).await.unwrap_err();
259        assert_eq!(err.kind(), "backend");
260    }
261
262    #[tokio::test]
263    async fn deny_verification_marks_stage_to_deny() {
264        let r = FakeRoceiro::new();
265        r.deny_verification(StageId::new("nope")).await;
266        let err = r.materialize(&stage("nope"), n(1)).await.unwrap_err();
267        assert_eq!(err.kind(), "verification_denied");
268    }
269
270    #[tokio::test]
271    async fn unmarked_stages_succeed_even_when_others_marked() {
272        let r = FakeRoceiro::new();
273        r.fail_backend(StageId::new("bad")).await;
274        let ok = r.materialize(&stage("good"), n(1)).await;
275        assert!(ok.is_ok());
276    }
277
278    #[tokio::test]
279    async fn calls_log_records_each_invocation() {
280        let r = FakeRoceiro::new();
281        r.materialize(&stage("a"), n(1)).await.unwrap();
282        r.materialize(&stage("b"), n(2)).await.unwrap();
283        let calls = r.calls().await;
284        assert_eq!(
285            calls,
286            vec![(StageId::new("a"), n(1)), (StageId::new("b"), n(2)),]
287        );
288    }
289
290    #[tokio::test]
291    async fn shape_tag_passes_through_to_receipt() {
292        let r = FakeRoceiro::new();
293        let mut st = stage("static");
294        st.shape = WorkloadShape::StaticBinary {
295            triple: "x86_64-unknown-linux-musl".into(),
296        };
297        // Make sure pinned-defaults aren't surprising.
298        st.placement = Placement::Pinned { node: n(1) };
299        let receipt = r.materialize(&st, n(1)).await.unwrap();
300        match receipt.kind {
301            ReceiptKind::Shape(tag) => {
302                assert_eq!(tag, "static_binary:x86_64-unknown-linux-musl");
303            }
304            _ => panic!("expected Shape kind"),
305        }
306    }
307
308    #[test]
309    fn error_kinds_are_stable() {
310        assert_eq!(RoceiroError::Backend("x".into()).kind(), "backend");
311        assert_eq!(
312            RoceiroError::UnsupportedStage {
313                stage: StageId::new("a"),
314                detail: "x".into(),
315            }
316            .kind(),
317            "unsupported_stage"
318        );
319        assert_eq!(
320            RoceiroError::VerificationDenied {
321                stage: StageId::new("a"),
322                detail: "x".into(),
323            }
324            .kind(),
325            "verification_denied"
326        );
327    }
328
329    #[tokio::test]
330    async fn backend_name_is_stable() {
331        assert_eq!(FakeRoceiro::new().name(), "fake");
332    }
333}