use std::collections::{BTreeMap, BTreeSet, VecDeque};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::receipt::NodeId;
use crate::shape::WorkloadShape;
use crate::verifier::Verificacao;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct StageId(pub String);
impl StageId {
#[must_use]
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for StageId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
fn de_threshold_k<'de, D>(de: D) -> Result<usize, D::Error>
where
D: serde::Deserializer<'de>,
{
let k = usize::deserialize(de)?;
if k == 0 {
return Err(serde::de::Error::invalid_value(
serde::de::Unexpected::Unsigned(0),
&"k: a threshold of at least 1",
));
}
Ok(k)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Placement {
Pinned {
node: NodeId,
},
AnyOne,
AnyK {
#[serde(deserialize_with = "de_threshold_k")]
k: usize,
},
Quorum {
#[serde(deserialize_with = "de_threshold_k")]
k: usize,
},
AllNodes,
}
impl Placement {
#[must_use]
pub fn min_nodes(&self) -> Option<usize> {
match self {
Self::Pinned { .. } | Self::AnyOne => Some(1),
Self::AnyK { k } | Self::Quorum { k } => Some((*k).max(1)),
Self::AllNodes => None,
}
}
#[must_use]
pub fn requires_agreement(&self) -> bool {
matches!(self, Self::Quorum { .. } | Self::AllNodes)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConfirmacaoPolicy {
Local,
Quorum {
#[serde(deserialize_with = "de_threshold_k")]
k: usize,
},
All,
RaftCommitted,
}
impl Default for ConfirmacaoPolicy {
fn default() -> Self {
Self::Local
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stage {
pub id: StageId,
pub shape: WorkloadShape,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub depends_on: BTreeSet<StageId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub verify: Vec<Verificacao>,
#[serde(default)]
pub confirm: ConfirmacaoPolicy,
pub placement: Placement,
}
impl Stage {
#[must_use]
pub fn pinned(id: impl Into<String>, shape: WorkloadShape, node: NodeId) -> Self {
Self {
id: StageId::new(id),
shape,
depends_on: BTreeSet::new(),
verify: Vec::new(),
confirm: ConfirmacaoPolicy::Local,
placement: Placement::Pinned { node },
}
}
}
#[derive(Debug, Clone, Error)]
pub enum PlantioError {
#[error("unknown dependency: stage {stage} depends on {dependency}")]
UnknownDependency {
stage: StageId,
dependency: StageId,
},
#[error("cycle detected (remaining stages: {remaining:?})")]
Cycle {
remaining: Vec<StageId>,
},
#[error("duplicate stage id: {0}")]
DuplicateId(StageId),
}
crate::impl_error_kind! {
PlantioError {
{ UnknownDependency { .. } } => "unknown_dependency",
{ Cycle { .. } } => "cycle",
(DuplicateId(_)) => "duplicate_id",
}
}
crate::impl_fingerprint!(Plantio);
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Plantio {
pub stages: BTreeMap<StageId, Stage>,
}
impl Plantio {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add_stage(&mut self, stage: Stage) -> Result<&mut Self, PlantioError> {
if self.stages.contains_key(&stage.id) {
return Err(PlantioError::DuplicateId(stage.id));
}
self.stages.insert(stage.id.clone(), stage);
Ok(self)
}
#[must_use]
pub fn len(&self) -> usize {
self.stages.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.stages.is_empty()
}
#[must_use]
pub fn fingerprint(&self) -> [u8; 32] {
<Self as crate::Fingerprint>::fingerprint(self)
}
#[must_use]
pub fn snapshot(&self) -> crate::mirante::ChildCountSnapshot {
crate::mirante::ChildCountSnapshot {
name: "plantio",
child_count: self.len(),
}
}
pub fn validate(&self) -> Result<(), PlantioError> {
for stage in self.stages.values() {
for dep in &stage.depends_on {
if !self.stages.contains_key(dep) {
return Err(PlantioError::UnknownDependency {
stage: stage.id.clone(),
dependency: dep.clone(),
});
}
}
}
let _ = self.topo_sort()?;
Ok(())
}
pub fn topo_sort(&self) -> Result<Vec<StageId>, PlantioError> {
for stage in self.stages.values() {
for dep in &stage.depends_on {
if !self.stages.contains_key(dep) {
return Err(PlantioError::UnknownDependency {
stage: stage.id.clone(),
dependency: dep.clone(),
});
}
}
}
let mut in_degree: BTreeMap<StageId, usize> =
self.stages.keys().map(|k| (k.clone(), 0usize)).collect();
for stage in self.stages.values() {
for dep in &stage.depends_on {
*in_degree.entry(stage.id.clone()).or_insert(0) += 1;
let _ = dep;
}
}
let mut queue: VecDeque<StageId> = in_degree
.iter()
.filter(|(_, d)| **d == 0)
.map(|(k, _)| k.clone())
.collect();
let mut sorted = Vec::with_capacity(self.stages.len());
while let Some(next) = queue.pop_front() {
sorted.push(next.clone());
for stage in self.stages.values() {
if stage.depends_on.contains(&next) {
if let Some(d) = in_degree.get_mut(&stage.id) {
*d = d.saturating_sub(1);
if *d == 0 {
queue.push_back(stage.id.clone());
}
}
}
}
}
if sorted.len() != self.stages.len() {
let remaining: Vec<StageId> = in_degree
.into_iter()
.filter(|(_, d)| *d > 0)
.map(|(k, _)| k)
.collect();
return Err(PlantioError::Cycle { remaining });
}
Ok(sorted)
}
pub fn compile_jobs(&self) -> Result<Vec<MaterializationJob>, PlantioError> {
let sorted = self.topo_sort()?;
let mut jobs = Vec::new();
for id in &sorted {
let stage = &self.stages[id];
match &stage.placement {
Placement::Pinned { node } => jobs.push(MaterializationJob {
stage_id: id.clone(),
target: JobTarget::Node(*node),
}),
Placement::AnyOne => jobs.push(MaterializationJob {
stage_id: id.clone(),
target: JobTarget::AnyOne,
}),
Placement::AnyK { k } => jobs.push(MaterializationJob {
stage_id: id.clone(),
target: JobTarget::AnyK { k: (*k).max(1) },
}),
Placement::Quorum { k } => jobs.push(MaterializationJob {
stage_id: id.clone(),
target: JobTarget::Quorum { k: (*k).max(1) },
}),
Placement::AllNodes => jobs.push(MaterializationJob {
stage_id: id.clone(),
target: JobTarget::AllNodes,
}),
}
}
Ok(jobs)
}
}
crate::define_named!(Plantio, "plantio");
crate::impl_observable!(Plantio, crate::mirante::ChildCountSnapshot);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MaterializationJob {
pub stage_id: StageId,
pub target: JobTarget,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JobTarget {
Node(NodeId),
AnyOne,
AnyK {
k: usize,
},
Quorum {
k: usize,
},
AllNodes,
}
#[cfg(test)]
mod tests {
use super::*;
fn n(b: u8) -> NodeId {
NodeId::new([b; 32])
}
fn s(id: &str) -> StageId {
StageId::new(id)
}
fn simple_stage(id: &str, deps: &[&str]) -> Stage {
let mut st = Stage::pinned(id, WorkloadShape::OciImage, n(1));
st.depends_on = deps.iter().map(|d| s(d)).collect();
st
}
#[test]
fn stage_id_display_matches_str() {
assert_eq!(format!("{}", s("build")), "build");
}
#[test]
fn stage_id_round_trips_via_serde() {
let id = s("x");
let bytes = serde_json::to_vec(&id).unwrap();
let back: StageId = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, id);
}
#[test]
fn placement_min_nodes_matrix() {
assert_eq!(Placement::Pinned { node: n(1) }.min_nodes(), Some(1));
assert_eq!(Placement::AnyOne.min_nodes(), Some(1));
assert_eq!(Placement::AnyK { k: 5 }.min_nodes(), Some(5));
assert_eq!(Placement::Quorum { k: 3 }.min_nodes(), Some(3));
assert_eq!(Placement::AllNodes.min_nodes(), None);
}
#[test]
fn placement_requires_agreement_only_for_quorum_and_all() {
assert!(Placement::Quorum { k: 1 }.requires_agreement());
assert!(Placement::AllNodes.requires_agreement());
assert!(!Placement::Pinned { node: n(1) }.requires_agreement());
assert!(!Placement::AnyOne.requires_agreement());
assert!(!Placement::AnyK { k: 5 }.requires_agreement());
}
#[test]
fn placement_zero_k_clamps_to_one_via_min_nodes() {
assert_eq!(Placement::AnyK { k: 0 }.min_nodes(), Some(1));
assert_eq!(Placement::Quorum { k: 0 }.min_nodes(), Some(1));
}
#[test]
fn placement_any_k_refuses_zero_at_the_parse_boundary() {
let err = serde_json::from_str::<Placement>(r#"{"kind":"any_k","k":0}"#)
.expect_err("a placement with k = 0 must not parse");
assert!(
err.to_string().contains("at least 1"),
"the refusal must say what was expected, got: {err}"
);
}
#[test]
fn placement_quorum_refuses_zero_at_the_parse_boundary() {
let err = serde_json::from_str::<Placement>(r#"{"kind":"quorum","k":0}"#)
.expect_err("a quorum placement with k = 0 must not parse");
assert!(
err.to_string().contains("at least 1"),
"the refusal must say what was expected, got: {err}"
);
}
#[test]
fn confirmacao_quorum_refuses_zero_at_the_parse_boundary() {
let err = serde_json::from_str::<ConfirmacaoPolicy>(r#"{"kind":"quorum","k":0}"#)
.expect_err("a confirmation policy with k = 0 must not parse");
assert!(
err.to_string().contains("at least 1"),
"the refusal must say what was expected, got: {err}"
);
}
#[test]
fn every_non_zero_k_still_parses_to_the_same_number() {
assert_eq!(
serde_json::from_str::<Placement>(r#"{"kind":"any_k","k":1}"#).unwrap(),
Placement::AnyK { k: 1 }
);
assert_eq!(
serde_json::from_str::<Placement>(r#"{"kind":"quorum","k":3}"#).unwrap(),
Placement::Quorum { k: 3 }
);
assert_eq!(
serde_json::from_str::<ConfirmacaoPolicy>(r#"{"kind":"quorum","k":3}"#).unwrap(),
ConfirmacaoPolicy::Quorum { k: 3 }
);
let p = Placement::Quorum { k: 3 };
let back: Placement = serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
assert_eq!(back, p);
}
#[test]
fn a_plantio_carrying_a_zero_k_does_not_parse() {
let mut st = simple_stage("q", &[]);
st.placement = Placement::Quorum { k: 3 };
st.confirm = ConfirmacaoPolicy::Quorum { k: 3 };
let mut p = Plantio::new();
p.add_stage(st).unwrap();
let good = serde_json::to_string(&p).unwrap();
assert!(serde_json::from_str::<Plantio>(&good).is_ok());
let zeroed = good.replace("\"k\":3", "\"k\":0");
assert_ne!(
zeroed, good,
"fixture must contain the k it is about to zero"
);
let err = serde_json::from_str::<Plantio>(&zeroed)
.expect_err("a plantio carrying k = 0 must not parse");
assert!(
err.to_string().contains("at least 1"),
"the refusal must say what was expected, got: {err}"
);
}
#[test]
fn confirmacao_default_is_local() {
assert_eq!(ConfirmacaoPolicy::default(), ConfirmacaoPolicy::Local);
}
#[test]
fn confirmacao_serializes_with_tag() {
let json = serde_json::to_string(&ConfirmacaoPolicy::Quorum { k: 3 }).unwrap();
assert!(json.contains("\"kind\":\"quorum\""));
}
#[test]
fn pinned_constructor_sets_defaults() {
let st = Stage::pinned("x", WorkloadShape::OciImage, n(1));
assert_eq!(st.id, s("x"));
assert_eq!(st.confirm, ConfirmacaoPolicy::Local);
assert!(st.depends_on.is_empty());
assert!(st.verify.is_empty());
assert!(matches!(st.placement, Placement::Pinned { .. }));
}
#[test]
fn stage_round_trips_via_serde() {
let st = simple_stage("x", &["a", "b"]);
let bytes = serde_json::to_vec(&st).unwrap();
let back: Stage = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, st);
}
#[test]
fn empty_plantio_is_valid() {
let p = Plantio::new();
assert!(p.is_empty());
assert_eq!(p.len(), 0);
p.validate().unwrap();
assert!(p.compile_jobs().unwrap().is_empty());
}
#[test]
fn add_stage_rejects_duplicate_id() {
let mut p = Plantio::new();
p.add_stage(simple_stage("x", &[])).unwrap();
let err = p.add_stage(simple_stage("x", &[])).unwrap_err();
assert_eq!(err.kind(), "duplicate_id");
}
#[test]
fn validate_rejects_unknown_dependency() {
let mut p = Plantio::new();
p.add_stage(simple_stage("x", &["nope"])).unwrap();
let err = p.validate().unwrap_err();
assert_eq!(err.kind(), "unknown_dependency");
}
#[test]
fn topo_sort_orders_a_then_b_when_b_depends_on_a() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &[])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
let order = p.topo_sort().unwrap();
assert_eq!(order, vec![s("a"), s("b")]);
}
#[test]
fn topo_sort_chain_of_three() {
let mut p = Plantio::new();
p.add_stage(simple_stage("c", &["b"])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
p.add_stage(simple_stage("a", &[])).unwrap();
let order = p.topo_sort().unwrap();
assert_eq!(order, vec![s("a"), s("b"), s("c")]);
}
#[test]
fn topo_sort_diamond_works() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &[])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
p.add_stage(simple_stage("c", &["a"])).unwrap();
p.add_stage(simple_stage("d", &["b", "c"])).unwrap();
let order = p.topo_sort().unwrap();
assert_eq!(order[0], s("a"));
assert_eq!(order[3], s("d"));
let middle: BTreeSet<_> = order[1..3].iter().collect();
assert!(middle.contains(&s("b")));
assert!(middle.contains(&s("c")));
}
#[test]
fn topo_sort_detects_cycle() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &["b"])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
let err = p.topo_sort().unwrap_err();
assert_eq!(err.kind(), "cycle");
if let PlantioError::Cycle { remaining } = err {
assert_eq!(remaining.len(), 2);
}
}
#[test]
fn compile_jobs_emits_one_job_per_stage_in_topo_order() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &[])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
let jobs = p.compile_jobs().unwrap();
assert_eq!(jobs.len(), 2);
assert_eq!(jobs[0].stage_id, s("a"));
assert_eq!(jobs[1].stage_id, s("b"));
}
#[test]
fn compile_jobs_projects_placement_to_job_target() {
let mut p = Plantio::new();
let mut st_pinned = Stage::pinned("p", WorkloadShape::OciImage, n(1));
st_pinned.placement = Placement::Pinned { node: n(7) };
p.add_stage(st_pinned).unwrap();
let mut st_any = Stage::pinned("any", WorkloadShape::OciImage, n(1));
st_any.placement = Placement::AnyOne;
p.add_stage(st_any).unwrap();
let mut st_quorum = Stage::pinned("q", WorkloadShape::OciImage, n(1));
st_quorum.placement = Placement::Quorum { k: 3 };
p.add_stage(st_quorum).unwrap();
let mut st_all = Stage::pinned("all", WorkloadShape::OciImage, n(1));
st_all.placement = Placement::AllNodes;
p.add_stage(st_all).unwrap();
let jobs = p.compile_jobs().unwrap();
let targets: BTreeMap<StageId, JobTarget> =
jobs.into_iter().map(|j| (j.stage_id, j.target)).collect();
assert_eq!(targets[&s("p")], JobTarget::Node(n(7)));
assert_eq!(targets[&s("any")], JobTarget::AnyOne);
assert_eq!(targets[&s("q")], JobTarget::Quorum { k: 3 });
assert_eq!(targets[&s("all")], JobTarget::AllNodes);
}
#[test]
fn compile_jobs_propagates_cycle_error() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &["b"])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
let err = p.compile_jobs().unwrap_err();
assert_eq!(err.kind(), "cycle");
}
#[test]
fn plantio_round_trips_via_serde() {
let mut p = Plantio::new();
p.add_stage(simple_stage("a", &[])).unwrap();
p.add_stage(simple_stage("b", &["a"])).unwrap();
let bytes = serde_json::to_vec(&p).unwrap();
let back: Plantio = serde_json::from_slice(&bytes).unwrap();
assert_eq!(back, p);
}
#[test]
fn error_kinds_are_stable() {
let dup = PlantioError::DuplicateId(s("x"));
assert_eq!(dup.kind(), "duplicate_id");
let unk = PlantioError::UnknownDependency {
stage: s("a"),
dependency: s("b"),
};
assert_eq!(unk.kind(), "unknown_dependency");
let cyc = PlantioError::Cycle { remaining: vec![] };
assert_eq!(cyc.kind(), "cycle");
}
}