Skip to main content

agentmux_srv/drone/
state.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Run state: the named values a graph writes, and how writes combine
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md §3.2).
6//!
7//! **Module B of the engine**, with `checkpoint.rs`. The types and the cap are
8//! fixed here; [`RunState::write`] and the rest are the module's job. Its
9//! acceptance tests are `state_acceptance_tests.rs`.
10//!
11//! # Reducers
12//!
13//! A variable declares how its writes combine. A name with no declaration is
14//! `replace`. The reducer decides the value, and [`merged_bits`] decides the
15//! taint bits of the result (the same rule for every reducer: none clears a bit).
16//!
17//! | Reducer | First write | Next write `w` onto current `c` | Type error when |
18//! |---|---|---|---|
19//! | `replace` | `w` | `w` | never |
20//! | `append` | `[w]` | `c` with `w` pushed as one element (a list `w` is one element) | `c` is not a list |
21//! | `merge` | `w` | shallow merge, `w`'s keys win | `c` or `w` is not an object |
22//! | `add` | `w` | `c + w`; integers stay integers (`1 + 2` is `3`) | `c` or `w` is not a number |
23
24use std::collections::BTreeMap;
25
26use serde::{Deserialize, Serialize};
27
28use super::value::{join, Tv};
29
30/// The state of a run is at most this many bytes of JSON (§3.2).
31pub const STATE_CAP_BYTES: usize = 256 * 1024;
32
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Reducer {
36    #[default]
37    Replace,
38    Append,
39    Merge,
40    Add,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44pub enum StateError {
45    /// The write does not fit the reducer (`append` onto a number, `add` of text, `merge` of a list).
46    #[error("state: {name}: {reducer:?} needs {needs}, got {got}")]
47    Type { name: String, reducer: Reducer, needs: &'static str, got: &'static str },
48    /// The state would pass [`STATE_CAP_BYTES`]. The write is not applied.
49    #[error("state: over the limit of {cap} bytes (would be {bytes})")]
50    TooLarge { bytes: usize, cap: usize },
51    /// A name that cannot be a variable (empty, or holding a dot or whitespace).
52    #[error("state: {0:?} is not a variable name")]
53    Name(String),
54}
55
56/// What a checkpoint stores of the state: every value with its bits, and the
57/// reducer each name declared.
58#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
59pub struct StateSnapshot {
60    pub vars: BTreeMap<String, Tv>,
61    pub reducers: BTreeMap<String, Reducer>,
62}
63
64/// The bits a write leaves on a variable: **no reducer clears a bit** (spec
65/// 4.1 "a reducer cannot clear taint", 4.2 "tainted if any contributing write
66/// is tainted"). With nothing there yet they are the write's; after that they
67/// are [`join`] of the current value and the write, `replace` included: a clean
68/// write over a tainted value leaves it tainted, because a person cannot tell
69/// from the variable which text is still in it.
70pub fn merged_bits(current: Option<&Tv>, write: &Tv) -> (bool, bool) {
71    match current {
72        None => (write.tainted, write.derived),
73        Some(c) => join(&[c, write]),
74    }
75}
76
77#[derive(Debug, Clone, Default)]
78pub struct RunState {
79    snapshot: StateSnapshot,
80}
81
82impl RunState {
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    /// A state restored from a checkpoint. The bits come back exactly as saved.
88    pub fn from_snapshot(snapshot: StateSnapshot) -> Self {
89        Self { snapshot }
90    }
91
92    pub fn snapshot(&self) -> StateSnapshot {
93        self.snapshot.clone()
94    }
95
96    pub fn reducer_of(&self, name: &str) -> Reducer {
97        self.snapshot.reducers.get(name).copied().unwrap_or_default()
98    }
99
100    pub fn get(&self, name: &str) -> Option<&Tv> {
101        self.snapshot.vars.get(name)
102    }
103
104    /// Declare how `name`'s writes combine. Declaring the same reducer again is
105    /// fine. Once the name has a value its reducer cannot change: another one is
106    /// a [`StateError::Type`] with `needs` "the reducer it was written under".
107    /// A bad name is a [`StateError::Name`]. A declaration counts toward
108    /// [`STATE_CAP_BYTES`] like a value, because [`Self::size_bytes`] measures
109    /// the declarations too; one that would pass it is a
110    /// [`StateError::TooLarge`] and changes nothing.
111    pub fn declare(&mut self, name: &str, reducer: Reducer) -> Result<(), StateError> {
112        check_name(name)?;
113        if self.snapshot.vars.contains_key(name) && self.reducer_of(name) != reducer {
114            return Err(StateError::Type {
115                name: name.to_string(),
116                reducer,
117                needs: "the reducer it was written under",
118                got: "a different reducer",
119            });
120        }
121        // Measure on a copy, as `write` does: a declaration is part of the
122        // state's JSON, so it can take the state over the cap on its own.
123        let mut candidate = self.snapshot.clone();
124        candidate.reducers.insert(name.to_string(), reducer);
125        let bytes = snapshot_len(&candidate);
126        if bytes > STATE_CAP_BYTES {
127            return Err(StateError::TooLarge { bytes, cap: STATE_CAP_BYTES });
128        }
129        self.snapshot = candidate;
130        Ok(())
131    }
132
133    /// Apply a write under the variable's reducer (see the table above). On an
134    /// error nothing changes. After a write the state is at most [`STATE_CAP_BYTES`].
135    pub fn write(&mut self, name: &str, value: Tv) -> Result<(), StateError> {
136        check_name(name)?;
137        let reducer = self.reducer_of(name);
138        let current = self.snapshot.vars.get(name);
139        let new_value = match reducer {
140            Reducer::Replace => value.v.clone(),
141            Reducer::Append => append_value(name, current, &value)?,
142            Reducer::Merge => merge_value(name, current, &value)?,
143            Reducer::Add => add_value(name, current, &value)?,
144        };
145        let (tainted, derived) = merged_bits(current, &value);
146        // Apply to a copy and measure before committing, so an over-cap write
147        // leaves the state exactly as it was.
148        let mut candidate = self.snapshot.clone();
149        candidate.vars.insert(name.to_string(), Tv { v: new_value, tainted, derived });
150        let bytes = snapshot_len(&candidate);
151        if bytes > STATE_CAP_BYTES {
152            return Err(StateError::TooLarge { bytes, cap: STATE_CAP_BYTES });
153        }
154        self.snapshot = candidate;
155        Ok(())
156    }
157
158    /// The size of the state as JSON, the number [`STATE_CAP_BYTES`] bounds:
159    /// the length of `serde_json::to_string(&snapshot())`.
160    pub fn size_bytes(&self) -> usize {
161        snapshot_len(&self.snapshot)
162    }
163}
164
165/// Refuse a name that cannot be a variable: empty, with a dot, or with whitespace.
166fn check_name(name: &str) -> Result<(), StateError> {
167    if name.is_empty() || name.contains('.') || name.chars().any(char::is_whitespace) {
168        return Err(StateError::Name(name.to_string()));
169    }
170    Ok(())
171}
172
173/// What a value is, for the `got` half of a [`StateError::Type`].
174fn kind(value: &serde_json::Value) -> &'static str {
175    match value {
176        serde_json::Value::Null => "null",
177        serde_json::Value::Bool(_) => "a boolean",
178        serde_json::Value::Number(_) => "a number",
179        serde_json::Value::String(_) => "a string",
180        serde_json::Value::Array(_) => "a list",
181        serde_json::Value::Object(_) => "an object",
182    }
183}
184
185fn type_error(name: &str, reducer: Reducer, needs: &'static str, got: &serde_json::Value) -> StateError {
186    StateError::Type { name: name.to_string(), reducer, needs, got: kind(got) }
187}
188
189/// The JSON length of a snapshot, the measure [`STATE_CAP_BYTES`] bounds.
190fn snapshot_len(snapshot: &StateSnapshot) -> usize {
191    serde_json::to_string(snapshot).map(|text| text.len()).unwrap_or(usize::MAX)
192}
193
194/// `append`: the first write makes `[w]`; after that `w` is one more element.
195fn append_value(name: &str, current: Option<&Tv>, write: &Tv) -> Result<serde_json::Value, StateError> {
196    let Some(current) = current else {
197        return Ok(serde_json::Value::Array(vec![write.v.clone()]));
198    };
199    let serde_json::Value::Array(items) = &current.v else {
200        return Err(type_error(name, Reducer::Append, "a list", &current.v));
201    };
202    let mut next = items.clone();
203    next.push(write.v.clone());
204    Ok(serde_json::Value::Array(next))
205}
206
207/// `merge`: a shallow object merge, `w`'s keys winning. A merge channel holds
208/// objects, so the first write must be one too.
209fn merge_value(name: &str, current: Option<&Tv>, write: &Tv) -> Result<serde_json::Value, StateError> {
210    let Some(write_object) = write.v.as_object() else {
211        return Err(type_error(name, Reducer::Merge, "an object", &write.v));
212    };
213    let Some(current) = current else {
214        return Ok(serde_json::Value::Object(write_object.clone()));
215    };
216    let Some(current_object) = current.v.as_object() else {
217        return Err(type_error(name, Reducer::Merge, "an object", &current.v));
218    };
219    let mut merged = current_object.clone();
220    for (key, value) in write_object {
221        merged.insert(key.clone(), value.clone());
222    }
223    Ok(serde_json::Value::Object(merged))
224}
225
226/// `add`: numbers only; two integers stay an integer, any float makes a float.
227fn add_value(name: &str, current: Option<&Tv>, write: &Tv) -> Result<serde_json::Value, StateError> {
228    let Some(write_number) = write.v.as_number() else {
229        return Err(type_error(name, Reducer::Add, "a number", &write.v));
230    };
231    let Some(current) = current else {
232        return Ok(write.v.clone());
233    };
234    let Some(current_number) = current.v.as_number() else {
235        return Err(type_error(name, Reducer::Add, "a number", &current.v));
236    };
237    let sum = add_numbers(current_number, write_number)
238        .ok_or_else(|| type_error(name, Reducer::Add, "a number", &write.v))?;
239    Ok(serde_json::Value::Number(sum))
240}
241
242/// The sum of two JSON numbers, keeping integers integers where it can.
243fn add_numbers(a: &serde_json::Number, b: &serde_json::Number) -> Option<serde_json::Number> {
244    // A JSON integer may be held as u64 or i64, and a pair can mix the two
245    // (a negative with one above `i64::MAX`). Summing those as i128 is exact
246    // for every pair of 64-bit values; going through f64 would round.
247    if let (Some(x), Some(y)) = (integer_of(a), integer_of(b)) {
248        let sum = x.checked_add(y)?;
249        if let Ok(fits) = i64::try_from(sum) {
250            return Some(serde_json::Number::from(fits));
251        }
252        if let Ok(fits) = u64::try_from(sum) {
253            return Some(serde_json::Number::from(fits));
254        }
255        // A sum outside both the i64 and the u64 range (only two same-sign
256        // extremes reach it) has no integer form in JSON, so the float is the
257        // best this type can hold.
258        return serde_json::Number::from_f64(sum as f64);
259    }
260    serde_json::Number::from_f64(a.as_f64()? + b.as_f64()?)
261}
262
263/// The integer a JSON number holds, signed or unsigned, as an `i128`.
264fn integer_of(number: &serde_json::Number) -> Option<i128> {
265    if let Some(signed) = number.as_i64() {
266        return Some(i128::from(signed));
267    }
268    number.as_u64().map(i128::from)
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use serde_json::json;
275
276    #[test]
277    fn the_bits_a_write_leaves_and_no_reducer_clears_one() {
278        let (clean, tainted, derived) = (Tv::clean(json!(1)), Tv::tainted(json!("x")), Tv::derived(json!(2)));
279        assert_eq!(merged_bits(None, &tainted), (true, false));
280        assert_eq!(merged_bits(None, &clean), (false, false));
281        assert_eq!(merged_bits(Some(&tainted), &clean), (true, false), "a clean write over a tainted value");
282        assert_eq!(merged_bits(Some(&clean), &tainted), (true, false));
283        assert_eq!(merged_bits(Some(&clean), &derived), (false, true));
284        assert_eq!(merged_bits(Some(&derived), &clean), (false, true), "a derived value stays derived");
285        assert_eq!(merged_bits(Some(&tainted), &derived), (true, false), "tainted is the stronger claim");
286        assert_eq!(merged_bits(Some(&clean), &clean), (false, false));
287    }
288
289    #[test]
290    fn a_reducer_is_written_in_snake_case() {
291        assert_eq!(serde_json::to_value(Reducer::Append).unwrap(), json!("append"));
292        assert_eq!(Reducer::default(), Reducer::Replace);
293    }
294
295    #[test]
296    fn adding_integers_is_exact_across_the_sign_boundary() {
297        let mut s = RunState::new();
298        s.declare("n", Reducer::Add).unwrap();
299        // One above i64::MAX is held as u64; the sum with -1 is the largest
300        // i64 and must not be rounded through f64.
301        s.write("n", Tv::clean(json!(9_223_372_036_854_775_808u64))).unwrap();
302        s.write("n", Tv::clean(json!(-1))).unwrap();
303        assert_eq!(s.get("n").unwrap().v, json!(9_223_372_036_854_775_807u64));
304        // A float still makes the result a float.
305        let mut f = RunState::new();
306        f.declare("f", Reducer::Add).unwrap();
307        f.write("f", Tv::clean(json!(3))).unwrap();
308        f.write("f", Tv::clean(json!(0.5))).unwrap();
309        assert_eq!(f.get("f").unwrap().v, json!(3.5));
310    }
311
312    #[test]
313    fn a_declaration_over_the_cap_is_refused_and_changes_nothing() {
314        let mut s = RunState::new();
315        s.write("ok", Tv::clean(json!(1))).unwrap();
316        let before = s.size_bytes();
317        let name = "x".repeat(STATE_CAP_BYTES + 1);
318        let err = s.declare(&name, Reducer::Add).unwrap_err();
319        assert!(matches!(err, StateError::TooLarge { cap, .. } if cap == STATE_CAP_BYTES), "{err:?}");
320        assert_eq!(s.size_bytes(), before);
321        assert_eq!(s.reducer_of(&name), Reducer::Replace, "the declaration did not land");
322    }
323}