Skip to main content

agentmux_srv/server/remote_ops/
fleet_sync.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Keeps the fleet's Global Memory in step (task #12439, section 4.6): the sending half of
5//! `memory.global.put`, `.remove` and `.list`.
6//!
7//! One loop, no change observer: every few seconds this machine fingerprints what it holds for the
8//! fleet (`backend::memory::fleet::fingerprint`) and, for each LAN peer whose last sync had another
9//! fingerprint (or that has not been synced since it appeared, which is how a machine that was
10//! offline catches up), lists what the peer holds and sends what it lacks or has older. Each side
11//! runs the same loop, so what the peer holds newer comes back on its own turn. A peer that is not
12//! reachable, is not proven, or does not have the ops is left alone until a retry time. Nothing is
13//! sent when nothing changed, so the audit trails only carry real work. What each peer answered
14//! (applied, or kept what it had and why) is kept in `status` for the Memory list, so the writer can
15//! see which entries did not arrive.
16
17use std::collections::HashMap;
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20
21use std::future::Future;
22
23use serde_json::{json, Value};
24
25use crate::server::remote_ops::op::{OpStatus, RemoteOpResult};
26
27use super::{enabled, send};
28use crate::backend::memory::fleet::{self, FleetMeta, Push};
29use crate::backend::storage::store::Store;
30use crate::server::AppState;
31
32/// How often this machine checks whether it has something new for its peers.
33const TICK: Duration = Duration::from_secs(15);
34/// A peer is synced again after this long even if nothing here changed, to heal a lost push.
35const RESYNC: Duration = Duration::from_secs(10 * 60);
36/// A peer that failed is left alone this long.
37const RETRY: Duration = Duration::from_secs(5 * 60);
38const REASON: &str = "fleet Global Memory sync";
39/// The signed form of params is a little longer than their JSON text.
40const SIGNING_SLACK: usize = 256;
41
42/// One machine to sync with: a key that tells it from the others, and the `host` the send takes.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub(super) struct Peer {
45    pub key: String,
46    pub host: String,
47}
48
49/// What the last sync of one peer saw.
50#[derive(Debug, Clone)]
51pub(super) struct Synced {
52    fingerprint: String,
53    at: Instant,
54    /// Set after a failure: the peer is skipped until then.
55    retry_at: Option<Instant>,
56}
57
58/// Start the loop. Does nothing while remote operations are off.
59pub(crate) fn install(state: AppState) {
60    tokio::spawn(async move {
61        let mut seen: HashMap<String, Synced> = HashMap::new();
62        let mut tick = tokio::time::interval(TICK);
63        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
64        loop {
65            tick.tick().await;
66            if enabled(&state) {
67                sync_once(&state, &mut seen).await;
68            }
69        }
70    });
71}
72
73fn peers(state: &AppState) -> Vec<Peer> {
74    state
75        .lan_discovery
76        .get_instances()
77        .into_iter()
78        .map(|p| {
79            let name = p.hostname.trim().to_string();
80            let key = peer_key(&p.install_id, &name, &p.channel, &p.address, p.port);
81            let host = if p.channel.is_empty() { name } else { format!("{name}/{}", p.channel) };
82            Peer { key, host }
83        })
84        .collect()
85}
86
87/// What tells one peer from another in the sync's bookkeeping. Not the discovery's `instance_id`: on a
88/// stable build it is the version (`v0.60.35`), the same on every machine running it, so peers that share
89/// a version shared one record, and a pass that had synced one counted the others as synced too (only one
90/// peer in ten minutes got anything). The install and the channel are the machine's own; an install that
91/// does not announce an id is told apart by its name, channel and address.
92fn peer_key(install_id: &str, hostname: &str, channel: &str, address: &str, port: u16) -> String {
93    if install_id.is_empty() {
94        format!("{hostname}/{channel}@{address}:{port}")
95    } else {
96        format!("{install_id}/{channel}")
97    }
98}
99
100/// An agent of this machine to sign with: the requests are `slug@machine` on both audit trails.
101pub(crate) fn signer(state: &AppState) -> Option<String> {
102    state.fleet_feed.snapshot().agents.iter().find(|a| !a.trim().is_empty()).cloned()
103}
104
105async fn sync_once(state: &AppState, seen: &mut HashMap<String, Synced>) {
106    let peers = peers(state);
107    if peers.is_empty() {
108        seen.clear();
109        return;
110    }
111    let Some(slug) = signer(state) else { return };
112    let call = |host: String, op: &'static str, params: Value| {
113        let slug = slug.clone();
114        async move { send::call(state, &slug, &host, op, params, REASON).await }
115    };
116    sync_peers(state.id_store.clone(), &peers, seen, &call, Instant::now()).await;
117}
118
119/// Sync every peer that is due. Separate from [`sync_once`] so a test can give it a fake machine.
120pub(super) async fn sync_peers<F, Fut>(store: Arc<Store>, peers: &[Peer], seen: &mut HashMap<String, Synced>, call: &F, now: Instant)
121where
122    F: Fn(String, &'static str, Value) -> Fut,
123    Fut: Future<Output = RemoteOpResult>,
124{
125    sync_peers_with(store, peers, seen, call, now, status::global()).await;
126}
127
128/// [`sync_peers`], with the status it reports to given, so a test reads its own.
129pub(super) async fn sync_peers_with<F, Fut>(
130    store: Arc<Store>,
131    peers: &[Peer],
132    seen: &mut HashMap<String, Synced>,
133    call: &F,
134    now: Instant,
135    report: &status::Status,
136) where
137    F: Fn(String, &'static str, Value) -> Fut,
138    Fut: Future<Output = RemoteOpResult>,
139{
140    // A peer that went away is synced as new when it comes back.
141    seen.retain(|key, _| peers.iter().any(|p| &p.key == key));
142    report.keep_only(&peers.iter().map(|p| p.host.as_str()).collect::<Vec<_>>());
143    let local = match blocking(store.clone(), fleet::list_meta).await {
144        Ok(local) => local,
145        Err(e) => {
146            tracing::warn!(error = %e, "fleet memory sync: could not read what this machine holds");
147            return;
148        }
149    };
150    let fingerprint = fleet::fingerprint(&local);
151    for peer in peers {
152        let due = match seen.get(&peer.key) {
153            None => true,
154            Some(s) => match s.retry_at {
155                Some(at) => now >= at,
156                None => s.fingerprint != fingerprint || now.duration_since(s.at) >= RESYNC,
157            },
158        };
159        if !due {
160            continue;
161        }
162        match sync_peer(&store, peer, &local, call).await {
163            Ok((sent, not_applied)) => {
164                if sent > 0 {
165                    tracing::info!(peer = %peer.host, sent, "fleet memory: sent entries to another machine");
166                }
167                for (id, why) in report.synced(&peer.host, agentmux_common::time::now_ms(), sent, not_applied) {
168                    tracing::warn!(peer = %peer.host, entry = %id, why, "fleet memory: the other machine did not apply an entry");
169                }
170                seen.insert(peer.key.clone(), Synced { fingerprint: fingerprint.clone(), at: now, retry_at: None });
171            }
172            Err(why) => {
173                tracing::debug!(peer = %peer.host, why, "fleet memory sync: left for later");
174                report.failed(&peer.host, &why);
175                seen.insert(peer.key.clone(), Synced { fingerprint: String::new(), at: now, retry_at: Some(now + RETRY) });
176            }
177        }
178    }
179}
180
181async fn blocking<T: Send + 'static>(
182    store: Arc<Store>,
183    f: impl FnOnce(&Store) -> Result<T, crate::backend::storage::error::StoreError> + Send + 'static,
184) -> Result<T, String> {
185    tokio::task::spawn_blocking(move || f(&store))
186        .await
187        .map_err(|e| e.to_string())?
188        .map_err(|e| e.to_string())
189}
190
191fn why_not(answer: &RemoteOpResult) -> String {
192    answer
193        .refused_reason
194        .clone()
195        .or_else(|| answer.result.get("error").and_then(Value::as_str).map(str::to_string))
196        .unwrap_or_else(|| format!("{:?}", answer.status))
197}
198
199/// How the peer answered one entry: `Applied` when it changed what it holds, `Skipped(why)` when
200/// it answered and kept what it had for a reason the writer should hear about, `Nothing` when
201/// there was nothing to do (it already holds it, or holds a newer one, which comes back on its own
202/// turn).
203enum Answered {
204    Applied,
205    Skipped(String),
206    Nothing,
207}
208
209fn answered(result: &Value) -> Answered {
210    match result.get("outcome").and_then(Value::as_str) {
211        Some("skipped") => match result.get("reason").and_then(Value::as_str).unwrap_or("not_applied") {
212            "same" | "older" | "already_removed" | "unknown" => Answered::Nothing,
213            why => Answered::Skipped(why.to_string()),
214        },
215        // An answer from a build that does not say what it did is counted as before.
216        _ => Answered::Applied,
217    }
218}
219
220/// List what `peer` holds and send it what it lacks. Returns how many entries and removals the peer
221/// applied, and which ones it answered but did not apply (an owner's `machine` entry, say) with why.
222/// An entry the peer takes badly (one too big to send, say) is skipped and counted, not retried
223/// now; the peer is retried later only when the list itself failed or a send could not reach it.
224async fn sync_peer<F, Fut>(
225    store: &Arc<Store>,
226    peer: &Peer,
227    local: &[FleetMeta],
228    call: &F,
229) -> Result<(usize, std::collections::BTreeMap<String, String>), String>
230where
231    F: Fn(String, &'static str, Value) -> Fut,
232    Fut: Future<Output = RemoteOpResult>,
233{
234    let answer = call(peer.host.clone(), "memory.global.list", json!({})).await;
235    if answer.status != OpStatus::Done {
236        return Err(format!("list: {}", why_not(&answer)));
237    }
238    let remote: Vec<FleetMeta> =
239        serde_json::from_value(answer.result.get("entries").cloned().unwrap_or(Value::Null)).map_err(|e| format!("list: not understood: {e}"))?;
240    let mut sent = 0;
241    let mut not_applied = std::collections::BTreeMap::new();
242    for push in fleet::to_push(local, &remote) {
243        let entry_id = match &push {
244            Push::Put { id } | Push::Remove { id, .. } => id.clone(),
245        };
246        let (op, params) = match push {
247            Push::Put { id } => match blocking(store.clone(), move |s| fleet::entry_for_push(s, &id)).await? {
248                Some(entry) => ("memory.global.put", serde_json::to_value(entry).map_err(|e| e.to_string())?),
249                // Removed or made machine-only since the listing: nothing to send.
250                None => continue,
251            },
252            Push::Remove { id, removed_at } => {
253                let removal = blocking(store.clone(), move |s| fleet::removal_for_push(s, &id, removed_at)).await?;
254                ("memory.global.remove", serde_json::to_value(removal).map_err(|e| e.to_string())?)
255            }
256        };
257        // The transport signs at most the operation's params limit. A bigger entry is skipped here,
258        // and logged, so the others still go.
259        if params.to_string().len() + SIGNING_SLACK > super::max_params_of(op) {
260            tracing::warn!(peer = %peer.host, op, bytes = params.to_string().len(), "fleet memory: an entry is too big to send; skipped");
261            not_applied.insert(entry_id, "too_big".to_string());
262            continue;
263        }
264        let answer = call(peer.host.clone(), op, params).await;
265        match answer.status {
266            OpStatus::Done => match answered(&answer.result) {
267                Answered::Applied => sent += 1,
268                Answered::Skipped(why) => {
269                    not_applied.insert(entry_id, why);
270                }
271                Answered::Nothing => {}
272            },
273            // The machine answered and said no to this one entry (too big, malformed): go on.
274            OpStatus::Refused if matches!(answer.refused_reason.as_deref(), Some("bad_params")) => {
275                tracing::warn!(peer = %peer.host, op, "fleet memory: the other machine refused an entry as malformed");
276                not_applied.insert(entry_id, "bad_params".to_string());
277            }
278            // The machine ran this one entry and it failed there (a store error on its side, from an
279            // older build than one that answers `name_taken`): say so for the entry and go on. One entry
280            // the peer cannot take must not stop the rest. An answer with no audit id never ran.
281            OpStatus::Failed if !answer.audit_id.is_empty() => {
282                let why = why_not(&answer);
283                tracing::warn!(peer = %peer.host, op, entry = %entry_id, why, "fleet memory: the other machine failed on an entry");
284                not_applied.insert(entry_id, format!("failed: {}", why.chars().take(120).collect::<String>()));
285            }
286            _ => return Err(format!("{op}: {}", why_not(&answer))),
287        }
288    }
289    Ok((sent, not_applied))
290}
291
292pub(crate) mod status;
293
294#[cfg(test)]
295mod tests;