Skip to main content

ic_backup/model/effect_graph/
mod.rs

1//! Immutable explicit operation dependencies; no universal application ordering or authority.
2
3use crate::model::evidence_digest::EvidenceDigest;
4mod node;
5pub use node::{EffectNodeRecord, EffectNodeRequest, MAX_EFFECT_DEPENDENCIES};
6
7use crate::model::{artifacts::ArtifactChecksumRecord, bounded_sequence};
8use serde::{Deserialize, Deserializer, Serialize};
9use std::collections::BTreeSet;
10use thiserror::Error;
11
12/// Maximum operation identities in a declared dependency graph.
13pub const MAX_EFFECT_OPERATIONS: usize = 8192;
14/// Maximum total explicit dependencies across one graph.
15pub const MAX_EFFECT_EDGES: usize = 65536;
16
17/// Canonical v1 dependency graph over opaque exact operation sequence identities.
18///
19/// Nodes refer to operations owned by a future complete plan. This record contains
20/// no effects, targets, request codecs, current authority or completion receipts.
21/// Parent-before-child and lifecycle order must be explicitly qualified by an integration.
22#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
23#[serde(try_from = "GraphFields")]
24pub struct EffectGraphRecord {
25    version: u16,
26    nodes: Vec<EffectNodeRecord>,
27    #[serde(skip)]
28    order: Vec<usize>,
29}
30
31#[derive(Deserialize)]
32#[serde(deny_unknown_fields)]
33struct GraphFields {
34    version: u16,
35    #[serde(deserialize_with = "bounded_nodes")]
36    nodes: Vec<EffectNodeRecord>,
37}
38impl TryFrom<GraphFields> for EffectGraphRecord {
39    type Error = EffectGraphError;
40    fn try_from(fields: GraphFields) -> Result<Self, Self::Error> {
41        if fields.version != 1 {
42            return Err(EffectGraphError::UnsupportedVersion(fields.version));
43        }
44        Self::new(fields.nodes)
45    }
46}
47
48impl EffectGraphRecord {
49    /// Validate bounded, unique, closed acyclic dependencies without IO.
50    ///
51    /// # Errors
52    /// Rejects empty/excessive graphs, repeated identities, missing edges and cycles.
53    pub fn new(mut nodes: Vec<EffectNodeRecord>) -> Result<Self, EffectGraphError> {
54        if nodes.is_empty() {
55            return Err(EffectGraphError::EmptyGraph);
56        }
57        if nodes.len() > MAX_EFFECT_OPERATIONS {
58            return Err(EffectGraphError::TooManyOperations);
59        }
60        nodes.sort_by_key(EffectNodeRecord::operation_sequence);
61        for pair in nodes.windows(2) {
62            if pair[0].operation_sequence() == pair[1].operation_sequence() {
63                return Err(EffectGraphError::DuplicateOperation(
64                    pair[0].operation_sequence(),
65                ));
66            }
67        }
68        let mut edges = 0;
69        for node in &nodes {
70            edges = add_edges(edges, node.depends_on().len())?;
71        }
72        let order = topological_order(&nodes)?;
73        Ok(Self {
74            version: 1,
75            nodes,
76            order,
77        })
78    }
79    /// Read immutable nodes in ascending operation sequence order.
80    #[must_use]
81    pub fn nodes(&self) -> &[EffectNodeRecord] {
82        &self.nodes
83    }
84    /// Resolve an exact operation identity without treating its numeric value as an order.
85    ///
86    /// # Errors
87    /// Rejects operation identities absent from the original graph.
88    pub fn node(&self, sequence: u64) -> Result<&EffectNodeRecord, EffectGraphError> {
89        self.nodes
90            .binary_search_by_key(&sequence, EffectNodeRecord::operation_sequence)
91            .map(|index| &self.nodes[index])
92            .map_err(|_| EffectGraphError::UnknownOperation(sequence))
93    }
94    /// Project deterministic topological order; smallest currently ready sequence wins ties.
95    ///
96    /// This order grants no effect authorization, target identity or fresh safety evidence.
97    pub fn ordered_nodes(
98        &self,
99    ) -> impl ExactSizeIterator<Item = &EffectNodeRecord> + DoubleEndedIterator + '_ {
100        self.order.iter().map(|index| &self.nodes[*index])
101    }
102    /// Hash canonical explicit identities/edges using the documented v1 binary encoding.
103    #[must_use]
104    pub fn digest(&self) -> ArtifactChecksumRecord {
105        let mut bytes = EvidenceDigest::new(b"ic-backup/effect-graph/v1\0");
106        bytes.count_u32(self.nodes.len());
107        for node in &self.nodes {
108            bytes.u64_be(node.operation_sequence());
109            bytes.count_u32(node.depends_on().len());
110            for dependency in node.depends_on() {
111                bytes.u64_be(*dependency);
112            }
113        }
114        bytes.finish()
115    }
116}
117
118fn topological_order(nodes: &[EffectNodeRecord]) -> Result<Vec<usize>, EffectGraphError> {
119    let mut dependents = vec![Vec::new(); nodes.len()];
120    let mut remaining: Vec<_> = nodes.iter().map(|node| node.depends_on().len()).collect();
121    for (index, node) in nodes.iter().enumerate() {
122        for dependency in node.depends_on() {
123            let parent = nodes
124                .binary_search_by_key(dependency, EffectNodeRecord::operation_sequence)
125                .map_err(|_| EffectGraphError::MissingDependency {
126                    operation_sequence: node.operation_sequence(),
127                    dependency: *dependency,
128                })?;
129            dependents[parent].push(index);
130        }
131    }
132    let mut ready: BTreeSet<_> = remaining
133        .iter()
134        .enumerate()
135        .filter_map(|(index, count)| (*count == 0).then_some(index))
136        .collect();
137    let mut order = Vec::with_capacity(nodes.len());
138    while let Some(index) = ready.pop_first() {
139        order.push(index);
140        for dependent in &dependents[index] {
141            remaining[*dependent] -= 1;
142            if remaining[*dependent] == 0 {
143                ready.insert(*dependent);
144            }
145        }
146    }
147    if order.len() != nodes.len() {
148        return Err(EffectGraphError::Cycle);
149    }
150    Ok(order)
151}
152
153fn add_edges(current: usize, additional: usize) -> Result<usize, EffectGraphError> {
154    current
155        .checked_add(additional)
156        .filter(|total| *total <= MAX_EFFECT_EDGES)
157        .ok_or(EffectGraphError::TooManyEdges)
158}
159
160fn bounded_nodes<'de, D: Deserializer<'de>>(
161    deserializer: D,
162) -> Result<Vec<EffectNodeRecord>, D::Error> {
163    let mut edges = 0;
164    bounded_sequence::deserialize_checked::<D, EffectNodeRecord, _, _, MAX_EFFECT_OPERATIONS>(
165        deserializer,
166        "bounded explicit effect nodes and total edges",
167        EffectGraphError::TooManyOperations,
168        |node| {
169            edges = add_edges(edges, node.depends_on().len())?;
170            Ok::<(), EffectGraphError>(())
171        },
172    )
173}
174
175/// Typed declared graph identity, dependency or resource-bound rejection.
176#[derive(Debug, Error)]
177pub enum EffectGraphError {
178    /// Only protocol generation v1 is maintained.
179    #[error("unsupported effect graph version {0}")]
180    UnsupportedVersion(u16),
181    /// At least one exact operation must be declared.
182    #[error("effect graph contains no operations")]
183    EmptyGraph,
184    /// Node count exceeds its maintained bound.
185    #[error("effect graph exceeds {MAX_EFFECT_OPERATIONS} operations")]
186    TooManyOperations,
187    /// One operation declares too many direct dependencies.
188    #[error("effect node exceeds {MAX_EFFECT_DEPENDENCIES} dependencies")]
189    TooManyDependencies,
190    /// Total graph dependencies exceed the maintained bound.
191    #[error("effect graph exceeds {MAX_EFFECT_EDGES} edges")]
192    TooManyEdges,
193    /// An exact operation was declared more than once.
194    #[error("duplicate effect operation {0}")]
195    DuplicateOperation(u64),
196    /// A requested exact operation is absent.
197    #[error("unknown effect operation {0}")]
198    UnknownOperation(u64),
199    /// A dependency identity appears more than once in one operation.
200    #[error("effect operation {operation_sequence} repeats dependency {dependency}")]
201    DuplicateDependency {
202        /// Exact owning operation sequence.
203        operation_sequence: u64,
204        /// Repeated exact prerequisite sequence.
205        dependency: u64,
206    },
207    /// An edge references an absent exact operation.
208    #[error("effect operation {operation_sequence} has absent dependency {dependency}")]
209    MissingDependency {
210        /// Exact owning operation sequence.
211        operation_sequence: u64,
212        /// Absent prerequisite sequence.
213        dependency: u64,
214    },
215    /// Dependencies include a self-loop or longer cycle.
216    #[error("effect graph contains a dependency cycle")]
217    Cycle,
218}
219
220#[cfg(test)]
221mod tests;