Skip to main content

nmbrs_runtime/checkpoint/
mod.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Workload checkpointing — see SRD-44.
5//!
6//! Submodules:
7//!
8//! - [`identity`] — `PathSegment`, `PhaseIdentity`, and the
9//!   per-phase canonical-program hash. Identity is per-phase
10//!   (no workload-level identity tuple) and `(yaml_path,
11//!   coords)` is necessary; the program hash is sufficiency.
12//! - [`storage`] — JSON file format + atomic-rename writer.
13//! - [`writer`] — `CheckpointWriter` actor: subscribes to
14//!   phase-lifecycle events, flushes on the metrics-tick
15//!   cadence with sqlite-fsync-then-checkpoint-fsync ordering.
16//! - [`resume`] — resume planner: loads checkpoint, classifies
17//!   each freshly-pre-mapped phase per the resume protocol,
18//!   produces a `ResumePlan` the executor consults before
19//!   dispatch.
20
21pub mod events;
22pub mod identity;
23pub mod params_scope;
24pub mod resume;
25pub mod storage;
26pub mod writer;
27
28pub use events::CheckpointData;
29pub use identity::{PathSegment, PhaseIdentity};
30pub use resume::{ResumeAction, ResumePlan};
31pub use storage::{Checkpoint, OpCounts, PhaseEntry, PhaseStatus};
32pub use writer::CheckpointWriter;
33
34/// Declare every phase node in a freshly-pre-mapped scene tree
35/// to the writer. Called once at session bootstrap, immediately
36/// after the pre-map pass of `crate::executor::execute_tree`
37/// (run with `pre_map_only` set) returns. Each phase
38/// gets a `Pending` entry with no hash; the runtime updates the
39/// hash via [`CheckpointWriter::update_phase_hash`] when the
40/// phase compiles.
41///
42/// The `phases` map carries each phase's `checkpoint:`
43/// declaration (parsed by `nmbrs-workload`); entries with
44/// `checkpoint: idempotent` set `skip_eligible = true`, all
45/// others set `false`.
46pub fn declare_scene_tree_phases(
47    writer: &CheckpointWriter,
48    tree: &crate::scene_tree::SceneTree,
49    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
50) {
51    for node in tree.dfs_phases() {
52        let identity = PhaseIdentity {
53            yaml_path: node.yaml_path.clone(),
54            coords: node.labels.clone(),
55            phase_hash: None,
56        };
57        let skip_eligible = phases
58            .get(&node.name)
59            .and_then(|p| p.checkpoint.as_ref())
60            .map(|c| c.idempotent)
61            .unwrap_or(false);
62        writer.declare_phase(identity, skip_eligible);
63    }
64}
65
66/// Build a list of `(identity, declared_idempotent)` pairs for
67/// every phase the scene tree will execute. The runner feeds
68/// this to [`ResumePlan::from_checkpoint`] when resuming, so the
69/// planner can classify each freshly-pre-mapped phase against
70/// the saved document.
71///
72/// Each candidate's `phase_hash` is `compose_phase_hash` over
73/// two pre-map-computable digests (SRD-106 D2 — this is THE
74/// skip-validity anchor, shared verbatim with the executor's
75/// stamped value so saved and fresh compare directly):
76///
77/// - the **ancestor-chain instance hash** — SHA-256 over the
78///   canonical_hash of every installed ancestor kernel, from
79///   the immediate parent scope up through the workload root
80///   AND the session-level workload-params module. Catches
81///   upstream binding edits and any param-value change (params
82///   live as const slots on the params module).
83/// - the **phase-config digest** (`phase_config_hash`) — a
84///   canonical serialization of the phase's full declared
85///   configuration: ops (statement templates included),
86///   bindings, cycles, concurrency, rate, stop conditions —
87///   every `WorkloadPhase` field. Catches edits the compiled
88///   program chain cannot see (an op's statement text, a
89///   cycle-count change).
90pub fn scene_tree_resume_candidates(
91    tree: &crate::scene_tree::SceneTree,
92    scope_tree: &crate::scope_tree::ScopeTree,
93    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
94) -> Vec<(PhaseIdentity, bool)> {
95    tree.dfs_phases()
96        .map(|node| {
97            let phase = phases.get(&node.name);
98            let chain = ancestor_chain_hash(scope_tree, &node.name);
99            let config = phase.map(phase_config_hash).unwrap_or([0u8; 32]);
100            let identity = PhaseIdentity {
101                yaml_path: node.yaml_path.clone(),
102                coords: node.labels.clone(),
103                phase_hash: Some(compose_phase_hash(chain, config)),
104            };
105            let idempotent = phase
106                .and_then(|p| p.checkpoint.as_ref())
107                .map(|c| c.idempotent)
108                .unwrap_or(false);
109            (identity, idempotent)
110        })
111        .collect()
112}
113
114/// Compose the two provenance digests into the one phase hash
115/// that every store and gate carries: the checkpoint document
116/// (SRD-44 resume classification), the persisted phase-outcome
117/// row (SRD-77 refine hash gate), and the resume planner's
118/// candidates all use this same formula, so a saved hash and a
119/// freshly computed one compare directly.
120pub(crate) fn compose_phase_hash(chain: Option<[u8; 32]>, config: [u8; 32]) -> [u8; 32] {
121    use sha2::{Digest, Sha256};
122    let mut h = Sha256::new();
123    h.update(b"nmbrs-phase-identity-v2\n");
124    match chain {
125        Some(c) => {
126            h.update(b"chain:");
127            h.update(c);
128        }
129        None => h.update(b"chain:none"),
130    }
131    h.update(b"config:");
132    h.update(config);
133    h.finalize().into()
134}
135
136/// Canonical serialization of a phase's full declared
137/// configuration — every `WorkloadPhase` field, ops and bindings
138/// included — through `serde_json::Value` with recursively sorted
139/// object keys so HashMap-backed fields serialize stably across
140/// processes (the workspace enables serde_json's `preserve_order`,
141/// so insertion order alone is NOT stable). One surface, two
142/// consumers: the config digest below and SRD-107's textual
143/// `{name}` interpolation scan.
144pub(crate) fn phase_config_canonical_text(phase: &nmbrs_workload::model::WorkloadPhase) -> String {
145    let mut value = serde_json::to_value(phase).unwrap_or(serde_json::Value::Null);
146    sort_json_keys(&mut value);
147    serde_json::to_string(&value).unwrap_or_default()
148}
149
150/// Canonical SHA-256 over [`phase_config_canonical_text`].
151pub(crate) fn phase_config_hash(phase: &nmbrs_workload::model::WorkloadPhase) -> [u8; 32] {
152    config_text_hash(&phase_config_canonical_text(phase))
153}
154
155/// Hash an already-canonicalized config text (callers that also
156/// feed the text to the SRD-107 scan avoid serializing twice).
157pub(crate) fn config_text_hash(text: &str) -> [u8; 32] {
158    use sha2::{Digest, Sha256};
159    let mut h = Sha256::new();
160    h.update(b"nmbrs-phase-config-v1\n");
161    h.update(text.as_bytes());
162    h.finalize().into()
163}
164
165fn sort_json_keys(v: &mut serde_json::Value) {
166    match v {
167        serde_json::Value::Object(map) => {
168            let mut entries: Vec<(String, serde_json::Value)> =
169                std::mem::take(map).into_iter().collect();
170            entries.sort_by(|a, b| a.0.cmp(&b.0));
171            for (_, val) in entries.iter_mut() {
172                sort_json_keys(val);
173            }
174            map.extend(entries);
175        }
176        serde_json::Value::Array(items) => {
177            for item in items {
178                sort_json_keys(item);
179            }
180        }
181        _ => {}
182    }
183}
184
185/// Compute a phase's ancestor-chain instance hash by looking up
186/// the scope-tree node and walking its installed ancestor
187/// kernels — immediate parent first, up through the workload
188/// root. The session node's kernel (the workload-params module)
189/// is EXCLUDED (SRD-107): param values participate per-phase via
190/// the consumed-params digest, not the chain, so an unrelated
191/// param change cannot flip this hash. Returns `None` if the
192/// scope tree has no installed kernels below the session
193/// (defensive — the workload root always has one in production).
194///
195/// Shared by the resume planner's candidates and the executor's
196/// stamped hash ([`compose_phase_hash`] composes it with the
197/// phase-config digest at both sites) — one formula, one walk.
198pub(crate) fn ancestor_chain_hash(
199    scope_tree: &crate::scope_tree::ScopeTree,
200    phase_name: &str,
201) -> Option<[u8; 32]> {
202    let idx = scope_tree.phase_node_by_name(phase_name)?;
203    let (ancestors, _params_module) = scope_tree.ancestor_kernels_split(idx);
204    if ancestors.is_empty() {
205        return None;
206    }
207    // The chain hash uses PolydatProgram::instance_hash with the
208    // first ancestor as the "self" anchor and the rest as
209    // ancestors-of-ancestor. The phase's OWN program is
210    // deliberately absent (it compiles lazily; its declared
211    // matter is covered by the phase-config digest instead), so
212    // this value is computable at pre-map time and identical at
213    // both compute sites.
214    let head = ancestors[0].program();
215    let tail: Vec<&polydat::kernel::PolydatProgram> = ancestors[1..]
216        .iter()
217        .map(|k| k.program().as_ref())
218        .collect();
219    Some(head.instance_hash(&tail))
220}
221
222/// The session's checkpoint log as an adapter sees it
223/// ([`crate::adapter::AdapterPositions`], SRD-117 §9.6).
224pub struct SessionPositions {
225    writer: std::sync::Arc<CheckpointWriter>,
226    /// Whether this invocation resumes an earlier one. Only then does
227    /// the log hold positions worth handing back.
228    resumed: bool,
229}
230
231impl SessionPositions {
232    pub fn new(writer: std::sync::Arc<CheckpointWriter>, resumed: bool) -> Self {
233        Self { writer, resumed }
234    }
235}
236
237impl crate::adapter::AdapterPositions for SessionPositions {
238    fn record(&self, adapter: &str, key: &str, position: serde_json::Value) {
239        self.writer.adapter_position(adapter, key, position);
240    }
241
242    fn resumed(&self, adapter: &str, key: &str) -> Option<serde_json::Value> {
243        if !self.resumed {
244            return None;
245        }
246        storage::latest_adapter_position(self.writer.path(), adapter, key)
247            .ok()
248            .flatten()
249    }
250}