Skip to main content

agentmux_srv/server/remote_ops/fleet_sync/
status.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the fleet Global Memory sync did, per peer, for the Memory list to show: when each peer was
5//! last synced, how many entries went, why it could not be (a refused list, an unreachable machine),
6//! and which entries the peer answered but did not apply (an owner's `machine` entry, say). The
7//! writer reads this instead of finding out from the peer's stewards that an entry never arrived.
8//!
9//! It also keeps the entries this machine replaced because a newer write came from the fleet while
10//! its own `machine` row was only a default (`backend::memory::fleet`), so a steward can see what
11//! changed on its own and revert it from the entry's history. In memory only: it starts empty with
12//! the process; the history of each entry is what lasts.
13
14use std::collections::{BTreeMap, VecDeque};
15use std::sync::{Mutex, OnceLock};
16
17use serde_json::{json, Value};
18
19/// The most replaced entries kept; the oldest go first.
20const MAX_ADOPTED: usize = 50;
21
22#[derive(Default)]
23struct PeerState {
24    synced_at_ms: Option<i64>,
25    sent: u64,
26    error: Option<String>,
27    /// Entry id -> why the peer did not apply it, from the last pass.
28    not_applied: BTreeMap<String, String>,
29}
30
31struct Adopted {
32    id: String,
33    name: String,
34    from: String,
35    at_ms: i64,
36}
37
38#[derive(Default)]
39struct Inner {
40    peers: BTreeMap<String, PeerState>,
41    adopted: VecDeque<Adopted>,
42}
43
44#[derive(Default)]
45pub(crate) struct Status {
46    inner: Mutex<Inner>,
47}
48
49/// The one this process keeps.
50pub(crate) fn global() -> &'static Status {
51    static STATUS: OnceLock<Status> = OnceLock::new();
52    STATUS.get_or_init(Status::default)
53}
54
55impl Status {
56    /// A pass over `host` finished. Returns the entries newly not applied (not already so on the
57    /// last pass), for the log.
58    pub(crate) fn synced(&self, host: &str, at_ms: i64, sent: usize, not_applied: BTreeMap<String, String>) -> Vec<(String, String)> {
59        let mut inner = self.inner.lock().unwrap();
60        let peer = inner.peers.entry(host.to_string()).or_default();
61        let fresh = not_applied.iter().filter(|(id, why)| peer.not_applied.get(*id) != Some(*why)).map(|(i, w)| (i.clone(), w.clone())).collect();
62        peer.synced_at_ms = Some(at_ms);
63        peer.sent += sent as u64;
64        peer.error = None;
65        peer.not_applied = not_applied;
66        fresh
67    }
68
69    /// A pass over `host` could not be made.
70    pub(crate) fn failed(&self, host: &str, why: &str) {
71        let mut inner = self.inner.lock().unwrap();
72        inner.peers.entry(host.to_string()).or_default().error = Some(why.to_string());
73    }
74
75    /// Forget peers that are no longer on the network.
76    pub(crate) fn keep_only(&self, hosts: &[&str]) {
77        self.inner.lock().unwrap().peers.retain(|host, _| hosts.contains(&host.as_str()));
78    }
79
80    /// A newer write from `from` replaced entry `id` here, which was `machine` only by default.
81    pub(crate) fn adopted(&self, id: &str, name: &str, from: &str, at_ms: i64) {
82        let mut inner = self.inner.lock().unwrap();
83        inner.adopted.push_back(Adopted { id: id.to_string(), name: name.to_string(), from: from.to_string(), at_ms });
84        while inner.adopted.len() > MAX_ADOPTED {
85            inner.adopted.pop_front();
86        }
87    }
88
89    /// The peers the last pass did not bring up to date: host -> `{ error, not_applied }`, only for a
90    /// host that could not be reached or that did not apply some entry. What a write tells its writer.
91    pub(crate) fn not_in_step(&self) -> Value {
92        let inner = self.inner.lock().unwrap();
93        let peers: serde_json::Map<String, Value> = inner
94            .peers
95            .iter()
96            .filter(|(_, p)| p.error.is_some() || !p.not_applied.is_empty())
97            .map(|(host, p)| (host.clone(), json!({ "error": p.error, "not_applied": p.not_applied })))
98            .collect();
99        Value::Object(peers)
100    }
101
102    /// The Memory list's `sync` field.
103    pub(crate) fn snapshot(&self) -> Value {
104        let inner = self.inner.lock().unwrap();
105        let peers: serde_json::Map<String, Value> = inner
106            .peers
107            .iter()
108            .map(|(host, p)| {
109                let state = json!({
110                    "synced_at": p.synced_at_ms,
111                    "sent": p.sent,
112                    "error": p.error,
113                    "not_applied": p.not_applied,
114                });
115                (host.clone(), state)
116            })
117            .collect();
118        let adopted: Vec<Value> =
119            inner.adopted.iter().rev().map(|a| json!({ "id": a.id, "name": a.name, "from": a.from, "at": a.at_ms })).collect();
120        json!({ "peers": peers, "replaced_here": adopted })
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    fn skipped(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
129        pairs.iter().map(|(i, w)| (i.to_string(), w.to_string())).collect()
130    }
131
132    #[test]
133    fn a_pass_reports_what_the_peer_did_not_apply_and_names_only_the_new_ones_for_the_log() {
134        let status = Status::default();
135        let first = status.synced("charlie", 1_000, 2, skipped(&[("a", "machine_scope")]));
136        assert_eq!(first, [("a".to_string(), "machine_scope".to_string())]);
137        let again = status.synced("charlie", 2_000, 0, skipped(&[("a", "machine_scope"), ("b", "protected")]));
138        assert_eq!(again, [("b".to_string(), "protected".to_string())], "a is not news");
139
140        let snap = status.snapshot();
141        assert_eq!(snap["peers"]["charlie"]["sent"], 2);
142        assert_eq!(snap["peers"]["charlie"]["synced_at"], 2_000);
143        assert_eq!(snap["peers"]["charlie"]["not_applied"]["b"], "protected");
144
145        status.synced("charlie", 3_000, 1, BTreeMap::new());
146        assert_eq!(status.snapshot()["peers"]["charlie"]["not_applied"], json!({}), "it applied after all");
147    }
148
149    #[test]
150    fn a_peer_that_cannot_be_reached_shows_why_and_one_that_left_is_forgotten() {
151        let status = Status::default();
152        status.failed("old-build", "list: peer_cannot_do_remote_ops");
153        let snap = status.snapshot();
154        assert_eq!(status.not_in_step()["old-build"]["error"], "list: peer_cannot_do_remote_ops");
155        assert_eq!(snap["peers"]["old-build"]["error"], "list: peer_cannot_do_remote_ops");
156        assert_eq!(snap["peers"]["old-build"]["synced_at"], Value::Null);
157
158        status.synced("charlie", 1, 0, BTreeMap::new());
159        status.keep_only(&["charlie"]);
160        assert!(status.snapshot()["peers"].get("old-build").is_none());
161        assert!(status.snapshot()["peers"].get("charlie").is_some());
162    }
163
164    #[test]
165    fn a_write_hears_only_of_the_peers_that_are_not_in_step() {
166        let status = Status::default();
167        assert_eq!(status.not_in_step(), json!({}), "nobody known: nothing to say");
168        status.synced("charlie", 1, 3, BTreeMap::new());
169        status.synced("area54", 1, 0, skipped(&[("e1", "name_taken")]));
170        status.failed("gamer", "list: timed out");
171        let out = status.not_in_step();
172        assert!(out.get("charlie").is_none(), "charlie took everything");
173        assert_eq!(out["area54"]["not_applied"]["e1"], "name_taken");
174        assert_eq!(out["gamer"]["error"], "list: timed out");
175    }
176
177    #[test]
178    fn replaced_entries_are_listed_newest_first_and_the_oldest_drop_off() {
179        let status = Status::default();
180        for n in 0..(MAX_ADOPTED + 3) {
181            status.adopted(&format!("e{n}"), "Rules", "loap@narko", n as i64);
182        }
183        let snap = status.snapshot();
184        let list = snap["replaced_here"].as_array().unwrap();
185        assert_eq!(list.len(), MAX_ADOPTED);
186        assert_eq!(list[0]["id"], format!("e{}", MAX_ADOPTED + 2));
187        assert_eq!(list[MAX_ADOPTED - 1]["id"], "e3");
188    }
189}