Skip to main content

agentmux_srv/server/reactive/
peer_hold.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A message to an agent of a LAN peer that is down is kept on the sender's instance for 24 hours and
5//! delivered when the peer answers again, as a message to a stopped local agent is. Before this it went
6//! to the cloud relay, which drops it after 30 minutes if no install of the account picks it up; a
7//! machine that was off for an hour lost it (task #2228).
8//!
9//! The agent counts as a known peer's when a LAN peer listed it (`backend::lan::seen_agents`, kept
10//! across restarts) and that peer no longer answers its poll. A peer that does answer is left to the
11//! old path: it can start a stopped agent when the message reaches it, which a held copy here cannot.
12//! The relay keeps the message when it says another install of the account runs the agent, or cannot
13//! say (`absent_route_for`), as for a local agent that is absent.
14//!
15//! The row lives in `db_jekt_held` under the target key `peer:<route name>`, which no agent UID can be,
16//! so the replay for local agents never sees it.
17
18use super::*;
19use crate::backend::lan::discovery::LanInstance;
20use crate::backend::lan::seen_agents::{self, SeenAgent};
21use crate::backend::reactive::types::InjectionResponse;
22use crate::backend::storage::jekt_held::{HeldJekt, HoldOutcome};
23
24/// The target key of a message held for a peer's agent.
25const PEER_KEY_PREFIX: &str = "peer:";
26/// A peer whose last answered poll is older than this is not answering (polls run every 30 s).
27const POLL_FRESH_SECS: u64 = 90;
28/// Agents one replay pass looks at (their machine may be down, which costs only a cached lookup),
29/// agents it sends to, and messages it sends to one.
30const LOOKUPS_PER_PASS: usize = 32;
31const AGENTS_PER_PASS: usize = 8;
32const ROWS_PER_AGENT: usize = 16;
33/// Refusals by a peer that has the agent, before a held message is dropped (as for a local agent).
34const MAX_REFUSALS: i64 = 20;
35
36fn peer_key(route_name: &str) -> String {
37    format!("{PEER_KEY_PREFIX}{route_name}")
38}
39
40/// The host that listed the agent, when no live LAN peer of that name answers its poll now.
41fn down_host(seen: Option<SeenAgent>, peers: &[LanInstance], now_secs: u64) -> Option<String> {
42    let seen = seen?;
43    let answering = peers.iter().any(|p| {
44        p.hostname.eq_ignore_ascii_case(&seen.hostname) && now_secs.saturating_sub(p.last_polled_ok) <= POLL_FRESH_SECS
45    });
46    (!answering).then_some(seen.hostname)
47}
48
49/// Whether the relay should take the message for `name` instead: another install of the account runs
50/// it, or the relay cannot say (an older one). A relay that is not reachable, or a sender not signed in
51/// to it, has nothing to offer, so the message is kept here.
52async fn relay_has_it(state: &AppState, source: Option<&str>, name: &str) -> bool {
53    use crate::muxbus::wan_lease;
54    if wan_lease::held_elsewhere(name).is_some() {
55        return true;
56    }
57    let Some(source) = source.filter(|s| !s.is_empty()) else {
58        return false;
59    };
60    let Some(credential) = crate::muxbus::relay::relay_token(source, &state.id_store, &state.http_client).await else {
61        return false;
62    };
63    let answer = wan_lease::holder(&crate::muxbus::relay::rest_base_url(), name, source, &credential.token, &state.http_client).await;
64    absent_route_for(&answer) == AbsentRoute::Relay
65}
66
67/// Hold `req` for an agent of a LAN peer that is down. `None` leaves it to the relay and the other
68/// holds: the hold does not apply to this sender, the agent is not a known peer's, its machine is
69/// answering, it is defined here, or the relay has it.
70pub(super) async fn hold_for_down_peer(
71    state: &AppState,
72    auth_via: crate::server::ReactiveAuthVia,
73    req: &InjectionRequest,
74    resp: &InjectionResponse,
75) -> Option<serde_json::Value> {
76    if !hold_applies(auth_via, req, resp) {
77        return None;
78    }
79    let name = crate::backend::reactive::sanitize::route_name(&req.target_agent)?.to_lowercase();
80    let host = down_host(seen_agents::lookup(&name), &state.lan_discovery.get_instances(), now_unix_secs().max(0) as u64)?;
81    hold_for_peer(state, req, resp, &name, host).await
82}
83
84/// Hold `req` for an agent of a LAN peer that answers its polls but gave no answer to this message (its
85/// inbound check was stuck behind a cloud login refresh that never returned). The replay
86/// sends it again; the peer that receives it can still start a stopped agent, which this copy cannot.
87pub(super) async fn hold_for_silent_peer(
88    state: &AppState,
89    auth_via: crate::server::ReactiveAuthVia,
90    req: &InjectionRequest,
91    resp: &InjectionResponse,
92) -> Option<serde_json::Value> {
93    if !hold_applies(auth_via, req, resp) {
94        return None;
95    }
96    let name = crate::backend::reactive::sanitize::route_name(&req.target_agent)?.to_lowercase();
97    let host = seen_agents::lookup(&name).map_or_else(|| "its machine".to_string(), |seen| seen.hostname);
98    hold_for_peer(state, req, resp, &name, host).await
99}
100
101/// The hold itself, for [`hold_for_down_peer`] and [`hold_for_silent_peer`].
102async fn hold_for_peer(state: &AppState, req: &InjectionRequest, resp: &InjectionResponse, name: &str, host: String) -> Option<serde_json::Value> {
103    let mstore = state.mstore.clone();
104    let target = req.target_agent.clone();
105    if tokio::task::spawn_blocking(move || defined_here(&mstore, &target)).await.ok()?.is_some() {
106        return None;
107    }
108    if relay_has_it(state, req.source_agent.as_deref(), name).await {
109        return None;
110    }
111    let mut held = crate::server::jekt_hold::held_row(req, resp.request_id.clone(), agentmux_common::time::now_ms());
112    held.target_uid = peer_key(name);
113    let mstore = state.mstore.clone();
114    let outcome = tokio::task::spawn_blocking(move || mstore.jekt_held_insert(&held)).await.ok()?;
115    let target = &req.target_agent;
116    match outcome {
117        Ok(HoldOutcome::Held | HoldOutcome::AlreadyHeld) => {
118            tracing::info!(target = %target, host = %host, "peer jekt: the agent's machine is not answering, holding the message");
119            Some(serde_json::json!({
120                "success": false,
121                "held": true,
122                "held_reason": HoldReason::PeerOffline.as_str(),
123                "retry_when": "peer_online",
124                "held_host": host,
125                "request_id": resp.request_id,
126                "error": format!(
127                    "agent {target} is on {host}, which is not answering — held on this AgentMux instance for up to 24 h, delivered when it is seen again"
128                ),
129            }))
130        }
131        Ok(HoldOutcome::Full) => Some(serde_json::json!({
132            "success": false,
133            "request_id": resp.request_id,
134            "error": format!("agent {target} is on {host}, which is not answering (hold full: too many messages already held for {target})"),
135        })),
136        Err(e) => {
137            tracing::warn!(error = %e, target = %target, "peer jekt: hold failed");
138            None
139        }
140    }
141}
142
143/// What one held message came to on a replay pass.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145enum Sent {
146    /// Taken (or kept by the peer, or queued at the relay): the row goes.
147    Gone,
148    /// Not now: the row stays for the next pass.
149    Later,
150    /// The peer has the agent and refused it: counted, and dropped after [`MAX_REFUSALS`].
151    Refused,
152}
153
154/// The request a held row is sent as: addressed by the name the sender used, late messages marked.
155fn request_for(row: &HeldJekt) -> InjectionRequest {
156    let mut req = crate::server::jekt_held::request_from_held(row);
157    req.target_agent = row.target_agent.clone();
158    req.marker_target = None;
159    req
160}
161
162/// `message` with the note that it was sent earlier, when it has waited long enough to need one.
163fn late_message(row: &HeldJekt, now_ms: i64) -> String {
164    let late = crate::muxbus::delivery_status::notes::delayed_prefix(Some(row.sent_at_ms), now_ms);
165    format!("{late}{}", row.message)
166}
167
168async fn send_over_lan(state: &AppState, row: &HeldJekt, url: &str, auth_key: &str) -> Sent {
169    let mut req = request_for(row);
170    req.forward_hops = 1;
171    let mut on_the_wire = req.clone();
172    on_the_wire.message = late_message(row, agentmux_common::time::now_ms());
173    let signed = lan_v2::sign_and_log(&state.mstore, &row.audit_source_uid, on_the_wire, url);
174    let peer = ForwardPeer {
175        url,
176        auth_key,
177        kind: "lan-peer-held",
178        channel: None,
179        trust: EchoTrust { delivery_tier: "lan", sig_verified: None, reagent_verified: None, lan_verified: None, channel_verified: None },
180    };
181    match forward_inject_to_peer(state, &req, &signed, peer).await {
182        ForwardOutcome::Delivered(_) => Sent::Gone,
183        // The peer kept it itself (it holds for an agent that cannot work): ours is a second copy.
184        ForwardOutcome::Refused(body) if body.get("held").and_then(|v| v.as_bool()) == Some(true) => Sent::Gone,
185        ForwardOutcome::Refused(_) => Sent::Refused,
186        ForwardOutcome::Stale | ForwardOutcome::NoAnswer => {
187            state.lan_discovery.evict_agent(&row.target_agent);
188            Sent::Later
189        }
190        ForwardOutcome::Inconclusive => Sent::Later,
191    }
192}
193
194/// Whether a row's 24 h hold, or the sender's own deadline, has run out: it is dropped, not sent.
195fn spent(row: &HeldJekt, now_ms: i64) -> bool {
196    row.expires_at_ms <= now_ms || row.sender_expires_at_ms.is_some_and(|deadline| deadline <= now_ms)
197}
198
199/// One held message, sent over the LAN (`lan`) or the relay, unless it ran out while the pass was
200/// asking where its agent is or sending the ones before it. The peer that receives it cannot tell.
201async fn send_row(state: &AppState, row: &HeldJekt, lan: &Option<(String, String)>) -> Sent {
202    if spent(row, agentmux_common::time::now_ms()) {
203        return Sent::Gone;
204    }
205    match lan {
206        Some((url, auth_key)) => send_over_lan(state, row, url, auth_key).await,
207        None => send_over_relay(state, row).await,
208    }
209}
210
211async fn send_over_relay(state: &AppState, row: &HeldJekt) -> Sent {
212    let mut req = request_for(row);
213    req.message = late_message(row, agentmux_common::time::now_ms());
214    match try_cloud_relay(state, &req, &row.audit_source_uid).await {
215        Some(_) => Sent::Gone,
216        None => Sent::Later,
217    }
218}
219
220async fn settle(state: &AppState, row: &HeldJekt, sent: Sent) {
221    let mstore = state.mstore.clone();
222    let id = row.request_id.clone();
223    let _ = tokio::task::spawn_blocking(move || match sent {
224        Sent::Gone => {
225            let _ = mstore.jekt_held_delete(&id);
226        }
227        Sent::Refused => {
228            if mstore.jekt_held_record_failure(&id, "refused by the peer").unwrap_or(0) >= MAX_REFUSALS {
229                let _ = mstore.jekt_held_delete(&id);
230            }
231        }
232        Sent::Later => {}
233    })
234    .await;
235}
236
237/// `keys` starting at the `by`-th, so each pass looks first at a different agent.
238fn rotated(mut keys: Vec<String>, by: usize) -> Vec<String> {
239    if !keys.is_empty() {
240        let n = keys.len();
241        keys.rotate_left(by % n);
242    }
243    keys
244}
245
246/// One pass over the messages held for peers' agents: each agent now on the LAN gets its messages,
247/// oldest first; one the relay has (another install runs it) goes there. Run beside the replay for
248/// local agents, whose pass also drops what expired.
249pub(crate) async fn replay_pass(state: &AppState) {
250    let mstore = state.mstore.clone();
251    let keys: Vec<String> = tokio::task::spawn_blocking(move || mstore.jekt_held_targets().unwrap_or_default())
252        .await
253        .unwrap_or_default()
254        .into_iter()
255        .filter(|t| t.starts_with(PEER_KEY_PREFIX))
256        .collect();
257    // The list is oldest message first, so the agents of a machine that stays down would hold the front
258    // of it for good: start at a different one each pass, and count against the cap only an agent that
259    // can be sent to (the lookups of the rest are cached).
260    static ROTATION: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
261    let keys = rotated(keys, ROTATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
262    let mut sent_to = 0;
263    for key in keys.into_iter().take(LOOKUPS_PER_PASS) {
264        if sent_to >= AGENTS_PER_PASS {
265            break;
266        }
267        let mstore = state.mstore.clone();
268        let rows_key = key.clone();
269        let rows = tokio::task::spawn_blocking(move || mstore.jekt_held_for_target(&rows_key, ROWS_PER_AGENT))
270            .await
271            .ok()
272            .and_then(Result::ok)
273            .unwrap_or_default();
274        let Some(first) = rows.first() else { continue };
275        let name = key.trim_start_matches(PEER_KEY_PREFIX);
276        // Asked for as the sender wrote it, as the live path does.
277        let lan = state.lan_discovery.find_agent(&first.target_agent, &state.http_client).await;
278        if lan.is_none() && !relay_has_it(state, Some(&first.source_agent), name).await {
279            continue;
280        }
281        sent_to += 1;
282        for row in &rows {
283            let sent = send_row(state, row, &lan).await;
284            settle(state, row, sent).await;
285            if sent == Sent::Later {
286                break;
287            }
288        }
289    }
290}
291
292#[cfg(test)]
293mod tests;