Skip to main content

engenho_controllers/
plantio.rs

1//! `PlantioController` — reconciles `PlantioCR` resources by
2//! driving a `Roceiro` materializer + watching a
3//! `MaterializationLedger` for confirmation.
4//!
5//! ## Reconcile rule
6//!
7//! For each `PlantioCR` (engenho.io/v1.Plantio):
8//!   1. Read + validate the embedded Plantio.
9//!   2. Compile to `MaterializationJobs`.
10//!   3. For each job whose stage is Ready (deps Confirmed):
11//!        a. Dispatch via Roceiro.materialize(stage, `target_node`)
12//!        b. Ingest receipt into the ledger
13//!        c. Mark per-job status (Materialized / Failed)
14//!   4. Walk the stages:
15//!        a. If ledger reports Reached → `status.stages[id].phase = "Confirmed"`
16//!        b. If ledger reports Dissent → `status.stages[id].phase = "Dissent"`
17//!        c. Else: keep Pending / Materializing
18//!   5. If every stage Confirmed → status.phase = "Complete"
19//!   6. If any stage in Dissent or Failed too many times →
20//!        status.phase = "Failed"
21//!
22//! ## Idempotency
23//!
24//! The controller only re-dispatches stages whose receipts are
25//! missing from the ledger. Re-tick with no state change is a no-op.
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::num::NonZeroUsize;
29use std::sync::Arc;
30
31use async_trait::async_trait;
32use engenho_store::{
33    StoreMesh,
34    command::{Reason, ResourceCommand},
35};
36use engenho_substrate::{
37    JobTarget, MaterializationLedger, NodeId, Plantio, QuorumState, QuorumVerdict, StageId,
38};
39use serde_json::{Value, json};
40use tracing::debug;
41
42use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
43use crate::effect::Effect;
44use crate::error::ControllerError;
45use crate::roceiro::Roceiro;
46
47/// Resolves abstract `JobTargets` (AnyOne/AnyK/AllNodes) into
48/// concrete `NodeIds`. The substrate doesn't have a live cluster
49/// directory baked in; consumers supply the resolver.
50#[async_trait]
51pub trait NodeResolver: Send + Sync {
52    /// Backend identifier for telemetry.
53    fn name(&self) -> &'static str;
54
55    /// Resolve a target into a concrete set of `NodeIds`.
56    ///
57    /// # Errors
58    /// Implementations may surface backend errors via `ControllerError`.
59    async fn resolve(&self, target: &JobTarget) -> Result<Vec<NodeId>, ControllerError>;
60}
61
62/// Static resolver — fixed list of known nodes. Useful for tests
63/// + small bootstrap clusters where the operator pins the node
64/// directory.
65pub struct StaticNodeResolver {
66    nodes: Vec<NodeId>,
67}
68
69impl StaticNodeResolver {
70    /// New resolver over a fixed node list.
71    #[must_use]
72    pub fn new(nodes: Vec<NodeId>) -> Self {
73        Self { nodes }
74    }
75}
76
77#[async_trait]
78impl NodeResolver for StaticNodeResolver {
79    fn name(&self) -> &'static str {
80        "static"
81    }
82
83    async fn resolve(&self, target: &JobTarget) -> Result<Vec<NodeId>, ControllerError> {
84        let resolved = match target {
85            JobTarget::Node(n) => vec![*n],
86            JobTarget::AnyOne => self.nodes.iter().take(1).copied().collect(),
87            JobTarget::AnyK { k } => self.nodes.iter().take(*k).copied().collect(),
88            JobTarget::Quorum { k } => self.nodes.iter().take(*k).copied().collect(),
89            JobTarget::AllNodes => self.nodes.clone(),
90        };
91        Ok(resolved)
92    }
93}
94
95/// The controller.
96pub struct PlantioController {
97    store: Arc<StoreMesh>,
98    roceiro: Arc<dyn Roceiro>,
99    ledger: Arc<dyn MaterializationLedger>,
100    resolver: Arc<dyn NodeResolver>,
101    namespace: Option<String>,
102}
103
104impl PlantioController {
105    /// New controller.
106    #[must_use]
107    pub fn new(
108        store: Arc<StoreMesh>,
109        roceiro: Arc<dyn Roceiro>,
110        ledger: Arc<dyn MaterializationLedger>,
111        resolver: Arc<dyn NodeResolver>,
112        namespace: Option<String>,
113    ) -> Self {
114        Self {
115            store,
116            roceiro,
117            ledger,
118            resolver,
119            namespace,
120        }
121    }
122
123    /// Extract the typed Plantio from a CR manifest. Pure helper.
124    #[must_use]
125    pub fn extract_plantio(cr: &Value) -> Option<Plantio> {
126        let plantio_v = cr.get("spec")?.get("plantio")?.clone();
127        serde_json::from_value(plantio_v).ok()
128    }
129
130    /// Confirmation threshold for a stage. Maps the typed
131    /// `ConfirmacaoPolicy` + Placement into the non-zero threshold the
132    /// ledger counts against. A `k` of 0 still parses (the policy
133    /// carries a `usize`) and means one.
134    #[must_use]
135    pub fn threshold_for(stage: &engenho_substrate::Stage) -> NonZeroUsize {
136        use engenho_substrate::ConfirmacaoPolicy as C;
137        use engenho_substrate::Placement as P;
138        let k = match (&stage.confirm, &stage.placement) {
139            (C::Quorum { k }, _) | (C::All, P::AnyK { k } | P::Quorum { k }) => *k,
140            // AllNodes is resolved at runtime by the resolver count.
141            (C::Local | C::RaftCommitted, _)
142            | (C::All, P::Pinned { .. } | P::AnyOne | P::AllNodes) => 1,
143        };
144        NonZeroUsize::new(k).unwrap_or(NonZeroUsize::MIN)
145    }
146
147    /// Compute the set of `StageIds` whose deps are all Confirmed.
148    /// Pure helper.
149    #[must_use]
150    pub fn ready_stages(plantio: &Plantio, confirmed: &BTreeSet<StageId>) -> Vec<StageId> {
151        let mut ready = Vec::new();
152        for (id, stage) in &plantio.stages {
153            if confirmed.contains(id) {
154                continue;
155            }
156            if stage.depends_on.iter().all(|d| confirmed.contains(d)) {
157                ready.push(id.clone());
158            }
159        }
160        ready.sort();
161        ready
162    }
163}
164
165#[async_trait]
166impl Controller for PlantioController {
167    fn name(&self) -> &'static str {
168        "plantio"
169    }
170
171    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
172        let crs = self
173            .store
174            .list("engenho.io", "v1", "Plantio", self.namespace.as_deref())
175            .await;
176        let mut report = ReconcileReport::default();
177        report.objects_examined = crs.len();
178
179        for (cr_key, cr_value) in &crs {
180            let Some(plantio) = Self::extract_plantio(cr_value) else {
181                report.objects_skipped += 1;
182                continue;
183            };
184            if plantio.validate().is_err() {
185                report.objects_skipped += 1;
186                continue;
187            }
188
189            // Determine current confirmation state from CR status.
190            let mut confirmed: BTreeSet<StageId> = cr_value
191                .get("status")
192                .and_then(|s| s.get("stages"))
193                .and_then(|s| s.as_object())
194                .map(|m| {
195                    m.iter()
196                        .filter_map(|(k, v)| {
197                            let phase = v.get("phase").and_then(|p| p.as_str())?;
198                            if phase == "Confirmed" {
199                                Some(StageId::new(k.clone()))
200                            } else {
201                                None
202                            }
203                        })
204                        .collect()
205                })
206                .unwrap_or_default();
207
208            let mut stage_phases: BTreeMap<StageId, String> = confirmed
209                .iter()
210                .map(|id| (id.clone(), "Confirmed".to_string()))
211                .collect();
212
213            // Iterate: dispatch + check ledger until no progress this tick.
214            loop {
215                let ready = Self::ready_stages(&plantio, &confirmed);
216                if ready.is_empty() {
217                    break;
218                }
219                let mut made_progress = false;
220                for stage_id in ready {
221                    let stage = &plantio.stages[&stage_id];
222                    let target = match stage.placement {
223                        engenho_substrate::Placement::Pinned { node } => JobTarget::Node(node),
224                        engenho_substrate::Placement::AnyOne => JobTarget::AnyOne,
225                        engenho_substrate::Placement::AnyK { k } => JobTarget::AnyK { k },
226                        engenho_substrate::Placement::Quorum { k } => JobTarget::Quorum { k },
227                        engenho_substrate::Placement::AllNodes => JobTarget::AllNodes,
228                    };
229                    let nodes = self.resolver.resolve(&target).await?;
230                    let threshold = Self::threshold_for(stage);
231                    let mut quorum_outcome: Option<QuorumVerdict> = None;
232                    for node in nodes {
233                        match self.roceiro.materialize(stage, node).await {
234                            Ok(receipt) => {
235                                let outcome = self
236                                    .ledger
237                                    .ingest(&stage_id, threshold, &receipt)
238                                    .await
239                                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
240                                quorum_outcome = Some(outcome);
241                            }
242                            Err(e) => {
243                                debug!(stage = %stage_id, error = %e, "materialize failed");
244                                stage_phases.insert(stage_id.clone(), "Failed".into());
245                            }
246                        }
247                    }
248                    match quorum_outcome.map(|v| v.state()) {
249                        Some(QuorumState::Reached) => {
250                            confirmed.insert(stage_id.clone());
251                            stage_phases.insert(stage_id, "Confirmed".into());
252                            made_progress = true;
253                        }
254                        Some(QuorumState::Dissent) => {
255                            stage_phases.insert(stage_id, "Dissent".into());
256                        }
257                        Some(QuorumState::Pending) => {
258                            stage_phases
259                                .entry(stage_id)
260                                .or_insert("Materializing".into());
261                        }
262                        None => {
263                            // Never even dispatched (no nodes resolved).
264                            stage_phases.entry(stage_id).or_insert("Pending".into());
265                        }
266                    }
267                }
268                if !made_progress {
269                    break;
270                }
271            }
272
273            // Aggregate status.phase.
274            let all_confirmed = plantio.stages.keys().all(|id| confirmed.contains(id));
275            let any_dissent = stage_phases.values().any(|p| p == "Dissent");
276            let any_failed = stage_phases.values().any(|p| p == "Failed");
277            let overall = if any_dissent || any_failed {
278                "Failed"
279            } else if all_confirmed {
280                "Complete"
281            } else {
282                "Materializing"
283            };
284
285            // Build the status patch.
286            let stages_status: serde_json::Map<String, Value> = stage_phases
287                .iter()
288                .map(|(k, v)| (k.to_string(), json!({"phase": v})))
289                .collect();
290            let new_status = json!({
291                "status": {
292                    "phase": overall,
293                    "stages": stages_status,
294                }
295            });
296
297            // Patch CR.
298            let applied = self
299                .store
300                .propose(ResourceCommand::patch(
301                    cr_key.clone(),
302                    new_status,
303                    Reason::Controller,
304                ))
305                .await?;
306            report.record(Effect::of(applied.op));
307        }
308        Ok(report.into())
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use engenho_substrate::{ConfirmacaoPolicy, MemoryLedger, Placement, Stage, WorkloadShape};
316
317    fn n(b: u8) -> NodeId {
318        NodeId::new([b; 32])
319    }
320
321    fn pinned_stage(id: &str, node: NodeId) -> Stage {
322        Stage::pinned(id, WorkloadShape::OciImage, node)
323    }
324
325    // ── NodeResolver ──────────────────────────────────────────
326
327    #[tokio::test]
328    async fn static_resolver_node_target_returns_one() {
329        let r = StaticNodeResolver::new(vec![n(1), n(2), n(3)]);
330        let nodes = r.resolve(&JobTarget::Node(n(2))).await.unwrap();
331        assert_eq!(nodes, vec![n(2)]);
332    }
333
334    #[tokio::test]
335    async fn static_resolver_any_one_returns_first() {
336        let r = StaticNodeResolver::new(vec![n(1), n(2), n(3)]);
337        let nodes = r.resolve(&JobTarget::AnyOne).await.unwrap();
338        assert_eq!(nodes, vec![n(1)]);
339    }
340
341    #[tokio::test]
342    async fn static_resolver_any_k_returns_first_k() {
343        let r = StaticNodeResolver::new(vec![n(1), n(2), n(3), n(4)]);
344        let nodes = r.resolve(&JobTarget::AnyK { k: 2 }).await.unwrap();
345        assert_eq!(nodes, vec![n(1), n(2)]);
346    }
347
348    #[tokio::test]
349    async fn static_resolver_quorum_returns_first_k() {
350        let r = StaticNodeResolver::new(vec![n(1), n(2), n(3)]);
351        let nodes = r.resolve(&JobTarget::Quorum { k: 2 }).await.unwrap();
352        assert_eq!(nodes.len(), 2);
353    }
354
355    #[tokio::test]
356    async fn static_resolver_all_nodes_returns_full_list() {
357        let r = StaticNodeResolver::new(vec![n(1), n(2)]);
358        let nodes = r.resolve(&JobTarget::AllNodes).await.unwrap();
359        assert_eq!(nodes, vec![n(1), n(2)]);
360    }
361
362    #[tokio::test]
363    async fn static_resolver_name_is_stable() {
364        let r = StaticNodeResolver::new(vec![]);
365        assert_eq!(r.name(), "static");
366    }
367
368    // ── PlantioController extract_plantio ─────────────────────
369
370    #[test]
371    fn extract_plantio_parses_spec_plantio() {
372        let plantio = Plantio::new();
373        let cr = json!({
374            "spec": {"plantio": &plantio}
375        });
376        let back = PlantioController::extract_plantio(&cr).unwrap();
377        assert_eq!(back, plantio);
378    }
379
380    #[test]
381    fn extract_plantio_none_for_missing_spec() {
382        let cr = json!({"metadata": {"name": "x"}});
383        assert!(PlantioController::extract_plantio(&cr).is_none());
384    }
385
386    // ── threshold_for ─────────────────────────────────────────
387
388    #[test]
389    fn threshold_for_local_is_one() {
390        let stage = pinned_stage("x", n(1));
391        // confirm defaults to Local
392        assert_eq!(PlantioController::threshold_for(&stage).get(), 1);
393    }
394
395    #[test]
396    fn threshold_for_quorum_uses_k() {
397        let mut stage = pinned_stage("x", n(1));
398        stage.confirm = ConfirmacaoPolicy::Quorum { k: 5 };
399        assert_eq!(PlantioController::threshold_for(&stage).get(), 5);
400    }
401
402    #[test]
403    fn threshold_for_quorum_clamps_zero_to_one() {
404        let mut stage = pinned_stage("x", n(1));
405        stage.confirm = ConfirmacaoPolicy::Quorum { k: 0 };
406        assert_eq!(PlantioController::threshold_for(&stage).get(), 1);
407    }
408
409    #[test]
410    fn threshold_for_all_with_anyk_uses_k() {
411        let mut stage = pinned_stage("x", n(1));
412        stage.confirm = ConfirmacaoPolicy::All;
413        stage.placement = Placement::AnyK { k: 3 };
414        assert_eq!(PlantioController::threshold_for(&stage).get(), 3);
415    }
416
417    #[test]
418    fn threshold_for_raft_committed_is_one() {
419        let mut stage = pinned_stage("x", n(1));
420        stage.confirm = ConfirmacaoPolicy::RaftCommitted;
421        assert_eq!(PlantioController::threshold_for(&stage).get(), 1);
422    }
423
424    // ── ready_stages ──────────────────────────────────────────
425
426    #[test]
427    fn ready_stages_includes_stages_with_no_deps_when_nothing_confirmed() {
428        let mut plantio = Plantio::new();
429        plantio.add_stage(pinned_stage("a", n(1))).unwrap();
430        plantio.add_stage(pinned_stage("b", n(1))).unwrap();
431        let confirmed = BTreeSet::new();
432        let ready = PlantioController::ready_stages(&plantio, &confirmed);
433        assert_eq!(ready, vec![StageId::new("a"), StageId::new("b")]);
434    }
435
436    #[test]
437    fn ready_stages_excludes_stages_with_unconfirmed_deps() {
438        let mut plantio = Plantio::new();
439        plantio.add_stage(pinned_stage("a", n(1))).unwrap();
440        let mut b = pinned_stage("b", n(1));
441        b.depends_on.insert(StageId::new("a"));
442        plantio.add_stage(b).unwrap();
443        let confirmed = BTreeSet::new();
444        let ready = PlantioController::ready_stages(&plantio, &confirmed);
445        // Only "a" is ready; "b" is blocked.
446        assert_eq!(ready, vec![StageId::new("a")]);
447    }
448
449    #[test]
450    fn ready_stages_unblocks_dependent_once_dep_is_confirmed() {
451        let mut plantio = Plantio::new();
452        plantio.add_stage(pinned_stage("a", n(1))).unwrap();
453        let mut b = pinned_stage("b", n(1));
454        b.depends_on.insert(StageId::new("a"));
455        plantio.add_stage(b).unwrap();
456        let confirmed: BTreeSet<_> = [StageId::new("a")].into_iter().collect();
457        let ready = PlantioController::ready_stages(&plantio, &confirmed);
458        assert_eq!(ready, vec![StageId::new("b")]);
459    }
460
461    #[test]
462    fn ready_stages_excludes_already_confirmed_stages() {
463        let mut plantio = Plantio::new();
464        plantio.add_stage(pinned_stage("a", n(1))).unwrap();
465        let confirmed: BTreeSet<_> = [StageId::new("a")].into_iter().collect();
466        let ready = PlantioController::ready_stages(&plantio, &confirmed);
467        assert!(ready.is_empty());
468    }
469
470    // ── full controller behavior verified at higher level later
471    // (integration tests against a live StoreMesh land when the
472    // CR storage type ships in engenho-store::types).
473
474    #[test]
475    fn controller_name_is_stable() {
476        struct F;
477        #[async_trait]
478        impl Controller for F {
479            fn name(&self) -> &'static str {
480                "plantio"
481            }
482            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
483                Ok(ReconcileReport::default().into())
484            }
485        }
486        assert_eq!(F.name(), "plantio");
487    }
488
489    // Sanity: composition of FakeRoceiro + MemoryLedger + StaticResolver
490    // produces sensible outcomes in isolation.
491
492    #[tokio::test]
493    async fn fake_roceiro_plus_memory_ledger_reaches_quorum_for_three_node_placement() {
494        use crate::roceiro::FakeRoceiro;
495        let roceiro = FakeRoceiro::new();
496        let ledger = MemoryLedger::new();
497        let mut stage = pinned_stage("x", n(1));
498        stage.confirm = ConfirmacaoPolicy::Quorum { k: 3 };
499        stage.placement = Placement::AnyK { k: 3 };
500        let threshold = PlantioController::threshold_for(&stage);
501        let resolver = StaticNodeResolver::new(vec![n(1), n(2), n(3)]);
502        let nodes = resolver.resolve(&JobTarget::AnyK { k: 3 }).await.unwrap();
503        let mut outcomes = Vec::new();
504        for node in nodes {
505            let r = roceiro.materialize(&stage, node).await.unwrap();
506            outcomes.push(ledger.ingest(&stage.id, threshold, &r).await.unwrap());
507        }
508        // Third receipt should be Reached.
509        assert!(outcomes.last().is_some_and(QuorumVerdict::is_reached));
510    }
511}