Skip to main content

nmbrs_runtime/checkpoint/
identity.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-phase identity for checkpoint match / mismatch decisions.
5//!
6//! Per SRD-44 §"Phase identity", every checkpoint entry is
7//! keyed by an identity tuple, not by display labels. The
8//! tuple is structural (yaml_path + coords) plus an optional
9//! phase-program hash for sufficiency.
10//!
11//! This module owns the type definitions; the pre-map pass of
12//! the unified walker (`crate::executor::execute_tree` run with
13//! `pre_map_only` set) is what populates
14//! `yaml_path` per scene-tree node, and the program-canonical-
15//! emit logic lives in [`crate::checkpoint::storage`] alongside
16//! the JSON serialization.
17//!
18//! ## Why per-phase, not workload-level
19//!
20//! Workload-level identity gates ("did the YAML byte-hash
21//! match?") are coarser than per-phase: a comment-only edit
22//! invalidates the entire run's saved progress, even though
23//! every phase's compiled program is identical. Per-phase hash
24//! lets the resume planner invalidate exactly the affected
25//! phases.
26//!
27//! ## What the hash covers
28//!
29//! Per SRD-44 §"Why hash the compiled program, not the YAML
30//! body", the hash is over the canonical re-emission of the
31//! phase's *compiled `PolydatProgram`* — incorporating substituted
32//! param values, transitively-referenced binding values, and
33//! all fold-able compile-time state. So a phase whose body
34//! references `{dataset}` correctly invalidates when the
35//! dataset param changes; one that doesn't reference `{dataset}`
36//! correctly survives.
37
38use serde::{Deserialize, Serialize};
39
40/// One step in a phase's structural location within the
41/// workload YAML. The full path is built by walking the
42/// scenario tree from the workload root down to the phase
43/// declaration. Order matters; comparison is element-wise.
44#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45pub enum PathSegment {
46    /// Scenario block declaration — the named entry under the
47    /// workload's `scenarios:` map.
48    Scenario(String),
49    /// Sub-scenario inclusion via the `scenario:` directive
50    /// (a scenario referencing another by name from inside a
51    /// phase list).
52    ScenarioInclude(String),
53    /// Single-clause `for_each` iteration.
54    ForEach { var: String },
55    /// Multi-clause `for_combinations` iteration. Vars in
56    /// declaration order.
57    ForCombinations { vars: Vec<String> },
58    /// `do_while` loop. `counter` is the optional
59    /// loop-counter binding name.
60    DoWhile { counter: Option<String> },
61    /// `do_until` loop.
62    DoUntil { counter: Option<String> },
63    /// Terminal: the phase declaration itself, by name.
64    Phase(String),
65}
66
67/// Per-phase identity, used by the checkpoint writer to record
68/// "what phase is this" and by the resume planner to match a
69/// saved entry to a freshly-pre-mapped phase.
70///
71/// `(yaml_path, coords)` together are necessary for a saved
72/// entry to apply to a new pre-map; `phase_hash` (when
73/// present) is the sufficiency check. See SRD-44 §"Identity
74/// matching at resume" for the full contract.
75///
76/// `coords` is the canonical scope-coordinate-path string
77/// (the leaf-first striated form produced by
78/// [`polydat::kernel::format_scope_coordinate_path`]).
79/// Stored as a string rather than typed `Vec<ScopeCoord>`
80/// because:
81/// - the runtime already produces it for every phase via
82///   `parent_kernel.scope_coordinates()` + the formatter,
83/// - it serialises trivially to JSON,
84/// - identity comparison reduces to string equality, and
85/// - the formatting function is the canonical identity
86///   producer for both pre-map and runtime — they cannot
87///   disagree without the formatter itself drifting.
88#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
89pub struct PhaseIdentity {
90    pub yaml_path: Vec<PathSegment>,
91    pub coords: String,
92    /// SHA-256 of the canonical re-emission of the phase's
93    /// compiled `PolydatProgram`. `None` when `checkpoint.hashed
94    /// = false` was declared on the workload (operator
95    /// opt-out per SRD-44); resume falls back to
96    /// tuple-only match in that case.
97    #[serde(default, with = "hex_opt")]
98    pub phase_hash: Option<[u8; 32]>,
99}
100
101impl PhaseIdentity {
102    /// Tuple-only match — `(yaml_path, coords)` equal.
103    /// Necessary precondition for any further match check;
104    /// if this returns `false`, the saved entry simply
105    /// doesn't apply to the candidate phase.
106    pub fn matches_structural(&self, other: &PhaseIdentity) -> bool {
107        self.yaml_path == other.yaml_path && self.coords == other.coords
108    }
109
110    /// Full match — tuple-equal AND, when both sides carry a
111    /// hash, hashes equal too. The "both carry a hash" bit
112    /// covers the operator opt-out (`checkpoint.hashed =
113    /// false`): in that case the saved entry has `None` and
114    /// the candidate may also have `None`, in which case
115    /// tuple-only equivalence is what the operator asked for.
116    /// Mismatched-hash → invalidate this single phase per
117    /// SRD-44 §"Identity matching at resume" item 3.
118    pub fn matches_full(&self, other: &PhaseIdentity) -> bool {
119        if !self.matches_structural(other) {
120            return false;
121        }
122        match (&self.phase_hash, &other.phase_hash) {
123            (Some(a), Some(b)) => a == b,
124            (None, _) | (_, None) => true,
125        }
126    }
127}
128
129/// Hex-encoded `[u8; 32]` for human-readable JSON output.
130mod hex_opt {
131    use serde::{Deserialize, Deserializer, Serialize, Serializer};
132
133    pub fn serialize<S: Serializer>(v: &Option<[u8; 32]>, s: S) -> Result<S::Ok, S::Error> {
134        match v {
135            None => s.serialize_none(),
136            Some(bytes) => {
137                let mut hex = String::with_capacity(64);
138                for b in bytes {
139                    hex.push_str(&format!("{b:02x}"));
140                }
141                hex.serialize(s)
142            }
143        }
144    }
145
146    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<[u8; 32]>, D::Error> {
147        let s: Option<String> = Option::deserialize(d)?;
148        match s {
149            None => Ok(None),
150            Some(hex) => {
151                if hex.len() != 64 {
152                    return Err(serde::de::Error::custom(format!(
153                        "phase_hash: expected 64 hex chars, got {}",
154                        hex.len()
155                    )));
156                }
157                let mut out = [0u8; 32];
158                for (i, byte) in out.iter_mut().enumerate() {
159                    let pair = &hex[i * 2..i * 2 + 2];
160                    *byte = u8::from_str_radix(pair, 16).map_err(|e| {
161                        serde::de::Error::custom(format!(
162                            "phase_hash: invalid hex at byte {i}: {e}"
163                        ))
164                    })?;
165                }
166                Ok(Some(out))
167            }
168        }
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn id(path: Vec<PathSegment>, coords: &str, hash: Option<[u8; 32]>) -> PhaseIdentity {
177        PhaseIdentity {
178            yaml_path: path,
179            coords: coords.to_string(),
180            phase_hash: hash,
181        }
182    }
183
184    #[test]
185    fn structural_match_requires_path_and_coords() {
186        let a = id(vec![PathSegment::Phase("p".into())], "", None);
187        let b = id(vec![PathSegment::Phase("p".into())], "", None);
188        let c = id(vec![PathSegment::Phase("q".into())], "", None);
189        let d = id(vec![PathSegment::Phase("p".into())], "(k=1)", None);
190        assert!(a.matches_structural(&b));
191        assert!(!a.matches_structural(&c));
192        assert!(!a.matches_structural(&d));
193    }
194
195    #[test]
196    fn full_match_with_both_hashes_present() {
197        let h1 = [1u8; 32];
198        let h2 = [2u8; 32];
199        let a = id(vec![PathSegment::Phase("p".into())], "", Some(h1));
200        let b = id(vec![PathSegment::Phase("p".into())], "", Some(h1));
201        let c = id(vec![PathSegment::Phase("p".into())], "", Some(h2));
202        assert!(a.matches_full(&b));
203        assert!(!a.matches_full(&c));
204    }
205
206    #[test]
207    fn full_match_with_one_side_unhashed() {
208        // Operator opted out (`hashed: false`); structural
209        // match is sufficient.
210        let h = [1u8; 32];
211        let a = id(vec![PathSegment::Phase("p".into())], "", Some(h));
212        let b = id(vec![PathSegment::Phase("p".into())], "", None);
213        assert!(a.matches_full(&b));
214        assert!(b.matches_full(&a));
215    }
216
217    #[test]
218    fn json_round_trip_with_hash() {
219        let h = [0xab; 32];
220        let original = id(
221            vec![
222                PathSegment::Scenario("fulltest".into()),
223                PathSegment::ForEach {
224                    var: "profile".into(),
225                },
226                PathSegment::Phase("rampup".into()),
227            ],
228            "(profile=label_03)",
229            Some(h),
230        );
231        let json = serde_json::to_string(&original).expect("serialize");
232        // The hash should appear as 64 hex chars.
233        assert!(
234            json.contains(&"ab".repeat(32)),
235            "expected hex hash in JSON: {json}"
236        );
237        let parsed: PhaseIdentity = serde_json::from_str(&json).expect("deserialize");
238        assert_eq!(parsed, original);
239    }
240
241    #[test]
242    fn json_round_trip_without_hash() {
243        let original = id(vec![PathSegment::Phase("p".into())], "", None);
244        let json = serde_json::to_string(&original).expect("serialize");
245        let parsed: PhaseIdentity = serde_json::from_str(&json).expect("deserialize");
246        assert_eq!(parsed, original);
247    }
248
249    #[test]
250    fn rejects_invalid_hex_length() {
251        let bad = r#"{"yaml_path":[],"coords":"","phase_hash":"ab12"}"#;
252        let err = serde_json::from_str::<PhaseIdentity>(bad).unwrap_err();
253        assert!(err.to_string().contains("64 hex"), "got: {err}");
254    }
255}