Skip to main content

agentmux_srv/drone/
checkpoint.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A checkpoint: what the engine writes after every node so a run can resume
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md §3.3).
6//!
7//! **Module B of the engine**, with `state.rs`. The types and the limits are
8//! fixed here; [`encode`], [`decode`], [`diff`] and [`apply`] are the module's
9//! job. Its acceptance tests are `state_acceptance_tests.rs`.
10//!
11//! A checkpoint is stored as a **diff from the one before it** (§3.3, the
12//! retention paragraph); step 0 has nothing before it and is stored whole. The
13//! ceiling is [`MAX_STEPS`] checkpoints per run.
14//!
15//! **The taint bits are part of the state, and a restore never clears one**:
16//! decoding then re-encoding gives back the same bits, and a value whose bits
17//! are missing in the bytes is an error (see `value::Tv`).
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use super::state::StateSnapshot;
24
25/// The format of an encoded checkpoint. A reader refuses a version it does not
26/// know (`CheckpointError::UnsupportedVersion`), so an upgrade never resumes a
27/// run from bytes it would misread.
28pub const SCHEMA_VERSION: u32 = 1;
29
30/// A run has at most this many checkpoints (§3.3).
31pub const MAX_STEPS: u32 = 1_000;
32
33/// The nodes of the graph by where they stand.
34#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Frontier {
36    pub ready: Vec<String>,
37    /// The ready blocks a loop sent round again: they run whatever their edges
38    /// say, so a restored run must still know which they were.
39    #[serde(default)]
40    pub forced: Vec<String>,
41    pub running: Vec<String>,
42    /// A waiting node and what it waits for is in `Checkpoint::deadlines` and `resume_on`.
43    pub waiting: Vec<String>,
44}
45
46/// The graph version a run started on: its number and the hash of its
47/// graph (`versions::graph_hash`). A run keeps this however the drone is edited.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct GraphRef {
50    pub version: i64,
51    pub hash: String,
52}
53
54/// Where the scheduler stands inside the graph, besides the frontier: which
55/// edges are decided, which blocks are done this pass of their loop, what each
56/// block has spent. Small, so a diff carries it whole when it changed.
57#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58pub struct Position {
59    /// Edges decided this pass of their loop, by id: `true` when they carry the run on.
60    pub decided: BTreeMap<String, bool>,
61    /// Blocks that ran or were skipped this pass of their loop.
62    pub finished: Vec<String>,
63    /// Edges out of a loop that were not taken, decided when nothing else can run, in order.
64    pub held: Vec<String>,
65    /// Blocks that failed this pass of their loop, and the graph handled it. A block skipped or run
66    /// again in a later pass keeps what it said before, so this is what says whether it failed now.
67    /// Absent in a checkpoint written before this was kept (an empty list is a run with no failure
68    /// now), and then a restore works it out from what the blocks said.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub failed: Option<Vec<String>>,
71    /// What each block has spent, in dollars.
72    pub spent_by: BTreeMap<String, f64>,
73    /// How long each loop guard's loop has been running, in ms. A restart does
74    /// not count: the time the app was off is not the loop's.
75    pub loop_elapsed_ms: BTreeMap<String, u64>,
76    /// What the run's Response block said, once it has run.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub response: Option<serde_json::Value>,
79}
80
81/// Where a replaying run came from: the run and the step it started at, and whether its
82/// blocks that have effects run for real. Never changes inside a run.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct Fork {
85    pub run_id: String,
86    pub step: u32,
87    #[serde(default)]
88    pub real: bool,
89}
90
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92pub struct Checkpoint {
93    pub schema_version: u32,
94    pub run_id: String,
95    /// 0 for the first checkpoint, then one more each time.
96    pub step: u32,
97    pub state: StateSnapshot,
98    pub frontier: Frontier,
99    /// Iterations used per loop guard, by node id.
100    pub loop_counters: BTreeMap<String, u32>,
101    pub cost_usd: f64,
102    pub elapsed_ms: u64,
103    /// Wake-up times (ms epoch) of waiting nodes, by node id.
104    pub deadlines: BTreeMap<String, i64>,
105    /// The event key each waiting node resumes on, by node id.
106    pub resume_on: BTreeMap<String, String>,
107    /// When a waiting node runs out of its own `timeout_seconds` (ms epoch), by node
108    /// id: kept so a restart does not give the wait its whole time again.
109    #[serde(default)]
110    pub wait_timeouts: BTreeMap<String, i64>,
111    pub graph: GraphRef,
112    /// The drone the run belongs to.
113    #[serde(default)]
114    pub drone_id: String,
115    /// What started the run (`{{trigger.*}}`); `Null` when nothing did. Never changes inside a run.
116    #[serde(default)]
117    pub trigger: serde_json::Value,
118    /// The run's dollar cap, from the job that started it. Never changes inside a run.
119    #[serde(default)]
120    pub run_cap_usd: Option<f64>,
121    /// The latest output of each block that ran (`{{block.path}}`), with its
122    /// `history` when a loop ran it again.
123    #[serde(default)]
124    pub outputs: BTreeMap<String, serde_json::Value>,
125    /// Each block's output bits `(tainted, derived)`. A restore never clears one.
126    #[serde(default)]
127    pub bits: BTreeMap<String, (bool, bool)>,
128    /// What each block that a loop ran again has said before, newest last (at
129    /// most 50): what `{{block.history}}` reads. Saved as it is, because it
130    /// cannot be told apart from the outputs.
131    #[serde(default)]
132    pub history: BTreeMap<String, Vec<serde_json::Value>>,
133    #[serde(default)]
134    pub position: Position,
135    /// Set on a run that replays an earlier one (`replay`); absent on any other.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub fork: Option<Fork>,
138}
139
140/// What changed from one checkpoint to the next. Fields that did not change
141/// are absent. Variables removed are listed in `removed_vars`.
142#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
143pub struct CheckpointDiff {
144    pub schema_version: u32,
145    pub run_id: String,
146    pub from_step: u32,
147    pub to_step: u32,
148    #[serde(default, skip_serializing_if = "StateSnapshot::is_empty")]
149    pub changed_state: StateSnapshot,
150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
151    pub removed_vars: Vec<String>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub frontier: Option<Frontier>,
154    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
155    pub loop_counters: BTreeMap<String, u32>,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub cost_usd: Option<f64>,
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub elapsed_ms: Option<u64>,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub deadlines: Option<BTreeMap<String, i64>>,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub resume_on: Option<BTreeMap<String, String>>,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub wait_timeouts: Option<BTreeMap<String, i64>>,
166    /// Outputs that are new or different. A block's output is never taken back.
167    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
168    pub changed_outputs: BTreeMap<String, serde_json::Value>,
169    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
170    pub changed_bits: BTreeMap<String, (bool, bool)>,
171    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
172    pub changed_history: BTreeMap<String, Vec<serde_json::Value>>,
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub position: Option<Position>,
175}
176
177impl StateSnapshot {
178    pub fn is_empty(&self) -> bool {
179        self.vars.is_empty() && self.reducers.is_empty()
180    }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
184pub enum CheckpointError {
185    /// The bytes were written by a build that knows a newer format. `supported` is [`SCHEMA_VERSION`].
186    #[error("checkpoint: format {found} is newer than this build reads ({supported})")]
187    UnsupportedVersion { found: u32, supported: u32 },
188    /// The bytes are not a checkpoint (not JSON, a field missing, a taint bit missing).
189    #[error("checkpoint: unreadable: {0}")]
190    Unreadable(String),
191    /// A run has at most [`MAX_STEPS`] checkpoints: step `step` was refused.
192    #[error("checkpoint: step {step} is over the limit of {max} steps")]
193    TooManySteps { step: u32, max: u32 },
194    /// A diff applied to a checkpoint it does not follow (another run, or `from_step` is not its step).
195    #[error("checkpoint: the diff does not follow this checkpoint ({0})")]
196    DoesNotFollow(String),
197}
198
199/// A checkpoint as bytes (UTF-8 JSON, so a person can read one in a bug report).
200/// Refuses `step >= MAX_STEPS` with [`CheckpointError::TooManySteps`].
201pub fn encode(c: &Checkpoint) -> Result<Vec<u8>, CheckpointError> {
202    if c.step >= MAX_STEPS {
203        return Err(CheckpointError::TooManySteps { step: c.step, max: MAX_STEPS });
204    }
205    serde_json::to_vec(c).map_err(|error| CheckpointError::Unreadable(error.to_string()))
206}
207
208/// The checkpoint in `bytes`. A newer `schema_version` is
209/// [`CheckpointError::UnsupportedVersion`] (checked before the rest is read);
210/// anything else wrong is [`CheckpointError::Unreadable`]. A restored value
211/// has exactly the bits it was saved with.
212pub fn decode(bytes: &[u8]) -> Result<Checkpoint, CheckpointError> {
213    let value: serde_json::Value =
214        serde_json::from_slice(bytes).map_err(|error| CheckpointError::Unreadable(error.to_string()))?;
215    // The version decides before any other field is looked at: bytes from a
216    // newer build may be missing fields this build requires or hold ones it
217    // does not know, and must not be misread as this format.
218    let found = value
219        .get("schema_version")
220        .and_then(serde_json::Value::as_u64)
221        .ok_or_else(|| CheckpointError::Unreadable("no numeric schema_version".to_string()))?;
222    if found > u64::from(SCHEMA_VERSION) {
223        return Err(CheckpointError::UnsupportedVersion {
224            found: u32::try_from(found).unwrap_or(u32::MAX),
225            supported: SCHEMA_VERSION,
226        });
227    }
228    if found < u64::from(SCHEMA_VERSION) {
229        return Err(CheckpointError::Unreadable(format!(
230            "format {found} is older than this build reads ({SCHEMA_VERSION})"
231        )));
232    }
233    // `Tv` requires both bits, so a value saved without one fails here instead
234    // of coming back clean.
235    serde_json::from_value(value).map_err(|error| CheckpointError::Unreadable(error.to_string()))
236}
237
238/// What changed from `prev` to `next` (`next.step == prev.step + 1`, same run).
239pub fn diff(prev: &Checkpoint, next: &Checkpoint) -> Result<CheckpointDiff, CheckpointError> {
240    if prev.run_id != next.run_id {
241        return Err(CheckpointError::DoesNotFollow(format!(
242            "run {:?} is not run {:?}",
243            next.run_id, prev.run_id
244        )));
245    }
246    if next.step != prev.step.checked_add(1).unwrap_or(u32::MAX) {
247        return Err(CheckpointError::DoesNotFollow(format!(
248            "step {} does not follow step {}",
249            next.step, prev.step
250        )));
251    }
252    if prev.graph != next.graph {
253        // The graph is pinned when the run starts; a run never moves to another
254        // graph, so a pair that does is not one step of one run.
255        return Err(CheckpointError::DoesNotFollow("the graph ref changed inside the run".to_string()));
256    }
257    if next.step >= MAX_STEPS {
258        // The incremental store must honour the ceiling `encode` enforces;
259        // otherwise a run could be resumed from a step no reader would accept.
260        return Err(CheckpointError::TooManySteps { step: next.step, max: MAX_STEPS });
261    }
262    let mut d = CheckpointDiff {
263        schema_version: next.schema_version,
264        run_id: next.run_id.clone(),
265        from_step: prev.step,
266        to_step: next.step,
267        ..CheckpointDiff::default()
268    };
269    d.changed_state = changed_state(&prev.state, &next.state);
270    d.removed_vars = prev
271        .state
272        .vars
273        .keys()
274        .filter(|name| !next.state.vars.contains_key(*name))
275        .cloned()
276        .collect();
277    if prev.frontier != next.frontier {
278        d.frontier = Some(next.frontier.clone());
279    }
280    d.loop_counters = changed_counters(&prev.loop_counters, &next.loop_counters);
281    if prev.cost_usd != next.cost_usd {
282        d.cost_usd = Some(next.cost_usd);
283    }
284    if prev.elapsed_ms != next.elapsed_ms {
285        d.elapsed_ms = Some(next.elapsed_ms);
286    }
287    if prev.deadlines != next.deadlines {
288        d.deadlines = Some(next.deadlines.clone());
289    }
290    if prev.resume_on != next.resume_on {
291        d.resume_on = Some(next.resume_on.clone());
292    }
293    if prev.wait_timeouts != next.wait_timeouts {
294        d.wait_timeouts = Some(next.wait_timeouts.clone());
295    }
296    d.changed_outputs = changed_map(&prev.outputs, &next.outputs);
297    d.changed_bits = changed_map(&prev.bits, &next.bits);
298    d.changed_history = changed_map(&prev.history, &next.history);
299    if prev.position != next.position {
300        d.position = Some(next.position.clone());
301    }
302    // A diff that cannot rebuild `next` would let a restored run differ from
303    // the one that was saved, with no error anywhere. The format cannot express
304    // a loop counter that vanished, a reducer declaration that was dropped, or
305    // a removed variable whose declaration stays, so refuse those shapes
306    // (rather than store a lossy diff) when the round trip does not match.
307    if apply(prev, &d)? != *next {
308        return Err(CheckpointError::DoesNotFollow("the diff cannot rebuild this checkpoint".to_string()));
309    }
310    Ok(d)
311}
312
313/// `prev` with `d` applied: equal to the `next` the diff was made from.
314pub fn apply(prev: &Checkpoint, d: &CheckpointDiff) -> Result<Checkpoint, CheckpointError> {
315    if d.run_id != prev.run_id {
316        return Err(CheckpointError::DoesNotFollow(format!(
317            "diff for run {:?} is not run {:?}",
318            d.run_id, prev.run_id
319        )));
320    }
321    if d.from_step != prev.step {
322        return Err(CheckpointError::DoesNotFollow(format!(
323            "diff from step {} is not step {}",
324            d.from_step, prev.step
325        )));
326    }
327    if d.to_step != d.from_step.checked_add(1).unwrap_or(u32::MAX) {
328        return Err(CheckpointError::DoesNotFollow(format!(
329            "diff goes from step {} to step {}",
330            d.from_step, d.to_step
331        )));
332    }
333    if d.to_step >= MAX_STEPS {
334        // A restored checkpoint at or past the ceiling could never be encoded
335        // again, so the diff that would build it is refused here too.
336        return Err(CheckpointError::TooManySteps { step: d.to_step, max: MAX_STEPS });
337    }
338    let mut out = prev.clone();
339    out.schema_version = d.schema_version;
340    out.step = d.to_step;
341    for (name, value) in &d.changed_state.vars {
342        out.state.vars.insert(name.clone(), value.clone());
343    }
344    for (name, reducer) in &d.changed_state.reducers {
345        out.state.reducers.insert(name.clone(), *reducer);
346    }
347    // A variable's declaration goes with the variable: `removed_vars` names the
348    // variable only, and a restore drops its declaration too. A declaration
349    // made before the first write (a name with no value yet) is left alone.
350    for name in &d.removed_vars {
351        out.state.vars.remove(name);
352        out.state.reducers.remove(name);
353    }
354    if let Some(frontier) = &d.frontier {
355        out.frontier = frontier.clone();
356    }
357    out.loop_counters.extend(d.loop_counters.iter().map(|(node, count)| (node.clone(), *count)));
358    if let Some(cost_usd) = d.cost_usd {
359        out.cost_usd = cost_usd;
360    }
361    if let Some(elapsed_ms) = d.elapsed_ms {
362        out.elapsed_ms = elapsed_ms;
363    }
364    if let Some(deadlines) = &d.deadlines {
365        out.deadlines = deadlines.clone();
366    }
367    if let Some(resume_on) = &d.resume_on {
368        out.resume_on = resume_on.clone();
369    }
370    if let Some(wait_timeouts) = &d.wait_timeouts {
371        out.wait_timeouts = wait_timeouts.clone();
372    }
373    out.outputs.extend(d.changed_outputs.iter().map(|(id, v)| (id.clone(), v.clone())));
374    out.bits.extend(d.changed_bits.iter().map(|(id, b)| (id.clone(), *b)));
375    out.history.extend(d.changed_history.iter().map(|(id, h)| (id.clone(), h.clone())));
376    if let Some(position) = &d.position {
377        out.position = position.clone();
378    }
379    Ok(out)
380}
381
382/// The variables and reducers that are new or different in `next`.
383fn changed_state(prev: &StateSnapshot, next: &StateSnapshot) -> StateSnapshot {
384    let mut changed = StateSnapshot::default();
385    for (name, value) in &next.vars {
386        if prev.vars.get(name) != Some(value) {
387            changed.vars.insert(name.clone(), value.clone());
388        }
389    }
390    for (name, reducer) in &next.reducers {
391        if prev.reducers.get(name) != Some(reducer) {
392            changed.reducers.insert(name.clone(), *reducer);
393        }
394    }
395    changed
396}
397
398/// The entries of `next` that are new or different from `prev`'s.
399fn changed_map<V: Clone + PartialEq>(prev: &BTreeMap<String, V>, next: &BTreeMap<String, V>) -> BTreeMap<String, V> {
400    next.iter().filter(|(id, v)| prev.get(*id) != Some(*v)).map(|(id, v)| (id.clone(), v.clone())).collect()
401}
402
403/// The loop counters that changed. A counter for a loop guard never disappears
404/// while the run lasts (its graph is pinned), so an entry can only be added or
405/// raised, and the changed entries alone are enough to restore the map.
406fn changed_counters(prev: &BTreeMap<String, u32>, next: &BTreeMap<String, u32>) -> BTreeMap<String, u32> {
407    next.iter()
408        .filter(|(node, count)| prev.get(*node) != Some(*count))
409        .map(|(node, count)| (node.clone(), *count))
410        .collect()
411}
412
413/// A small valid checkpoint, for tests and docs.
414#[cfg(test)]
415pub(crate) fn sample(step: u32) -> Checkpoint {
416    use crate::drone::state::Reducer;
417    use crate::drone::value::Tv;
418    use serde_json::json;
419    let mut state = StateSnapshot::default();
420    state.vars.insert("title".into(), Tv::tainted(json!("fix the build")));
421    state.vars.insert("attempts".into(), Tv::derived(json!(2)));
422    state.vars.insert("owner".into(), Tv::clean(json!("agenty")));
423    state.reducers.insert("attempts".into(), Reducer::Add);
424    Checkpoint {
425        schema_version: SCHEMA_VERSION,
426        run_id: "run-1".into(),
427        step,
428        state,
429        frontier: Frontier { ready: vec!["n3".into()], forced: vec![], running: vec![], waiting: vec!["w1".into()] },
430        loop_counters: BTreeMap::from([("guard".to_string(), 2)]),
431        cost_usd: 0.25,
432        elapsed_ms: 1_500,
433        deadlines: BTreeMap::from([("w1".to_string(), 1_800_000_000_000)]),
434        resume_on: BTreeMap::new(),
435        wait_timeouts: BTreeMap::from([("w1".to_string(), 1_800_000_060_000)]),
436        graph: GraphRef { version: 3, hash: "abc".into() },
437        drone_id: "drone-1".into(),
438        trigger: serde_json::json!({ "pr": 12 }),
439        run_cap_usd: Some(5.0),
440        outputs: BTreeMap::from([("n1".to_string(), serde_json::json!({ "value": "x" }))]),
441        bits: BTreeMap::from([("n1".to_string(), (true, false))]),
442        history: BTreeMap::new(),
443        position: Position {
444            decided: BTreeMap::from([("e1".to_string(), true)]),
445            finished: vec!["n1".into()],
446            ..Position::default()
447        },
448        fork: None,
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455    use crate::drone::state::Reducer;
456    use crate::drone::value::Tv;
457    use serde_json::json;
458
459    /// A checkpoint varied in the fields a diff carries, seeded so each seed
460    /// differs in values, bits, reducers and the maps that can grow and shrink.
461    fn varied(step: u32, seed: u32) -> Checkpoint {
462        let mut c = sample(step);
463        c.run_id = format!("run-{seed}");
464        c.graph = GraphRef { version: i64::from(seed) + 1, hash: format!("hash-{seed}") };
465        c.cost_usd = 0.25 + f64::from(seed) * 0.5;
466        c.elapsed_ms = 1_500 + u64::from(seed) * 7;
467        c.frontier.ready = (0..seed % 4).map(|i| format!("n{i}")).collect();
468        c.frontier.waiting = if seed % 2 == 0 { vec![] } else { vec!["w1".into()] };
469        c.loop_counters = (0..seed % 3).map(|i| (format!("g{i}"), i + seed)).collect();
470        c.deadlines = (0..seed % 2).map(|i| (format!("d{i}"), i64::from(i))).collect();
471        c.resume_on = (0..seed % 2).map(|i| (format!("r{i}"), format!("key{i}"))).collect();
472        c.wait_timeouts = (0..seed % 3).map(|i| (format!("t{i}"), i64::from(i) + 9)).collect();
473        c.state.vars.clear();
474        c.state.reducers.clear();
475        for i in 0..=seed % 5 {
476            let value = match i % 3 {
477                0 => Tv::clean(json!({ "i": i })),
478                1 => Tv::tainted(json!(["x", i])),
479                _ => Tv::derived(json!(i)),
480            };
481            c.state.vars.insert(format!("v{i}"), value);
482            if i % 2 == 0 {
483                c.state.reducers.insert(format!("v{i}"), Reducer::Add);
484            }
485        }
486        c
487    }
488
489    /// `prev` one step later: a value removed, one added, one changed and
490    /// tainted, and each map grown.
491    fn grown(prev: &Checkpoint, step: u32, seed: u32) -> Checkpoint {
492        let mut next = prev.clone();
493        next.step = step;
494        next.cost_usd += 0.01;
495        next.elapsed_ms += 5;
496        next.frontier.ready.push(format!("n{step}"));
497        if let Some(name) = prev.state.vars.keys().next().cloned() {
498            next.state.vars.remove(&name);
499            next.state.reducers.remove(&name);
500        }
501        next.state.vars.insert(format!("new{seed}"), Tv::derived(json!(seed)));
502        if let Some(value) = next.state.vars.values_mut().next() {
503            value.v = json!("changed");
504            value.tainted = true;
505            value.derived = false;
506        }
507        next.loop_counters.insert("g0".into(), step + seed);
508        next.deadlines.insert(format!("d{step}"), i64::from(step));
509        next.resume_on.insert(format!("r{seed}"), format!("k{step}"));
510        next.wait_timeouts.insert(format!("t{step}"), i64::from(step));
511        next
512    }
513
514    #[test]
515    fn a_round_trip_and_a_diff_keep_every_bit_and_reducer() {
516        for seed in 0..12 {
517            let prev = varied(1, seed);
518            let next = grown(&prev, 2, seed);
519            let bytes = encode(&prev).unwrap();
520            let back = decode(&bytes).unwrap();
521            assert_eq!(back, prev, "seed {seed}");
522            for (name, value) in &prev.state.vars {
523                assert_eq!((back.state.vars[name].tainted, back.state.vars[name].derived), (value.tainted, value.derived));
524            }
525            let d = diff(&prev, &next).unwrap();
526            let restored = apply(&prev, &d).unwrap();
527            assert_eq!(restored, next, "seed {seed}");
528            for (name, value) in &next.state.vars {
529                assert_eq!(restored.state.vars[name], *value, "the bits of {name} survive a diff");
530            }
531            // A decoded diff is the same diff: both ends survive a store.
532            let bytes = serde_json::to_vec(&d).unwrap();
533            let read: CheckpointDiff = serde_json::from_slice(&bytes).unwrap();
534            assert_eq!(apply(&prev, &read).unwrap(), next, "seed {seed}");
535        }
536    }
537
538    #[test]
539    fn a_removed_variable_takes_its_reducer_with_it() {
540        let prev = varied(1, 3);
541        let name = prev.state.vars.keys().next().unwrap().clone();
542        let mut next = prev.clone();
543        next.step = 2;
544        next.state.vars.remove(&name);
545        next.state.reducers.remove(&name);
546        let d = diff(&prev, &next).unwrap();
547        assert_eq!(d.removed_vars, vec![name.clone()]);
548        assert!(!d.changed_state.reducers.contains_key(&name));
549        let restored = apply(&prev, &d).unwrap();
550        assert_eq!(restored.state.reducers.get(&name), None);
551        assert_eq!(restored, next);
552    }
553
554    #[test]
555    fn a_pair_a_diff_cannot_rebuild_is_refused() {
556        // A loop counter that disappeared: the format carries changed counters only.
557        let mut prev = sample(1);
558        prev.loop_counters = BTreeMap::from([("guard".to_string(), 2)]);
559        let mut next = prev.clone();
560        next.step = 2;
561        next.loop_counters.clear();
562        assert!(matches!(diff(&prev, &next), Err(CheckpointError::DoesNotFollow(_))));
563
564        // A reducer declaration dropped while its variable stays.
565        let mut prev = sample(1);
566        prev.state.vars.insert("n".into(), Tv::clean(json!(1)));
567        prev.state.reducers.insert("n".into(), Reducer::Add);
568        let mut next = prev.clone();
569        next.step = 2;
570        next.state.reducers.remove("n");
571        assert!(matches!(diff(&prev, &next), Err(CheckpointError::DoesNotFollow(_))));
572
573        // A removed variable whose declaration stays.
574        let mut prev = sample(1);
575        prev.state.vars.insert("n".into(), Tv::clean(json!(1)));
576        prev.state.reducers.insert("n".into(), Reducer::Add);
577        let mut next = prev.clone();
578        next.step = 2;
579        next.state.vars.remove("n");
580        assert!(matches!(diff(&prev, &next), Err(CheckpointError::DoesNotFollow(_))));
581    }
582
583    #[test]
584    fn a_checkpoint_past_the_step_ceiling_is_refused_by_diff_and_apply() {
585        let prev = sample(MAX_STEPS - 1);
586        let mut next = prev.clone();
587        next.step = MAX_STEPS;
588        assert_eq!(
589            diff(&prev, &next).unwrap_err(),
590            CheckpointError::TooManySteps { step: MAX_STEPS, max: MAX_STEPS }
591        );
592        let d = CheckpointDiff {
593            schema_version: SCHEMA_VERSION,
594            run_id: prev.run_id.clone(),
595            from_step: prev.step,
596            to_step: MAX_STEPS,
597            ..CheckpointDiff::default()
598        };
599        assert_eq!(
600            apply(&prev, &d).unwrap_err(),
601            CheckpointError::TooManySteps { step: MAX_STEPS, max: MAX_STEPS }
602        );
603    }
604}