Skip to main content

agentmux_srv/server/
jekt_held.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Replay of jekts held for an absent agent —
5//! `SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md` §2.3. The hold itself is in
6//! `reactive::deliver`; this delivers what was held once the agent is back.
7
8use std::time::Duration;
9
10use crate::backend::agent_availability::WaitReason;
11use crate::backend::agent_status::{decide, Decision, Intent};
12use crate::backend::obj::Block;
13use crate::backend::storage::jekt_held::HeldJekt;
14
15use super::availability_view::status_of;
16use super::AppState;
17
18/// Deliveries per pass, so a backlog cannot monopolise the handler (and the
19/// first-contact spawn it may trigger) in one go.
20const REPLAY_PER_PASS: usize = 8;
21/// Failed deliveries to a present target before a held message is dropped.
22const MAX_ATTEMPTS: i64 = 20;
23const SWEEP_EVERY: Duration = Duration::from_secs(30);
24/// How often a target the spawn gate refused is re-checked for sign-in.
25const GATE_RECHECK_EVERY: Duration = Duration::from_secs(60);
26
27/// The spawn gate refusing a target is recoverable (it signs in), so the
28/// message is held, not dropped.
29pub(crate) use crate::backend::reactive::is_spawn_gate_refusal;
30
31/// Targets the spawn gate refused, with when the gate was last checked.
32///
33/// A delivery attempt to such a target is not free: `run_agent_turn` writes an
34/// error frame into its pane and raises a failure event each time. So the
35/// replay never attempts one blind; it first runs the gate on its own, which
36/// has no side effect beyond a log line, at most every [`GATE_RECHECK_EVERY`],
37/// and delivers once it passes. In memory: after a restart the first replay
38/// attempt finds the gate closed again and re-marks the target, one frame.
39fn needs_login() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {
40    static MAP: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> =
41        std::sync::OnceLock::new();
42    MAP.get_or_init(Default::default)
43}
44
45/// Mark `uid` as refused by the spawn gate, checked just now.
46pub(crate) fn mark_needs_login(uid: &str) {
47    needs_login().lock().unwrap().insert(uid.to_string(), std::time::Instant::now());
48}
49
50/// What the replay should do about a target's sign-in, given when its gate was
51/// last checked (`None`: never refused).
52#[derive(Debug, PartialEq, Eq)]
53enum GateCheck {
54    /// Not refused before: deliver as usual.
55    Open,
56    /// Checked within [`GATE_RECHECK_EVERY`]: skip without checking.
57    Wait,
58    /// Due: run the gate.
59    Recheck,
60}
61
62fn gate_check_due(last: Option<std::time::Instant>, now: std::time::Instant) -> GateCheck {
63    match last {
64        None => GateCheck::Open,
65        Some(t) if now.duration_since(t) < GATE_RECHECK_EVERY => GateCheck::Wait,
66        Some(_) => GateCheck::Recheck,
67    }
68}
69
70/// Whether `uid` is still waiting for sign-in. Runs the spawn gate quietly
71/// (no pane frame, no failure event) when a recheck is due.
72async fn still_needs_login(state: &AppState, uid: &str) -> bool {
73    let last = needs_login().lock().unwrap().get(uid).copied();
74    match gate_check_due(last, std::time::Instant::now()) {
75        GateCheck::Open => return false,
76        GateCheck::Wait => return true,
77        GateCheck::Recheck => {}
78    }
79    let Some(block_id) = state.reactive_handler.block_for_uid(uid) else {
80        return true;
81    };
82    let (mstore, id_store, identity_store) =
83        (state.mstore.clone(), state.id_store.clone(), state.identity_store.clone());
84    let passed = tokio::task::spawn_blocking(move || {
85        // The spawn's own decision: an agent on a model server of its own is not refused for the account, so it
86        // is not held for it either (an endpoint set after the hold must release what was held).
87        let own_endpoint = mstore
88            .get::<Block>(&block_id)
89            .ok()
90            .flatten()
91            .is_some_and(|block| crate::backend::spawn_env::endpoint::own_claude_endpoint_of(&block.meta));
92        crate::identity::resolver::inject_identity_env_for_spawn(
93            mstore,
94            id_store,
95            identity_store,
96            None,
97            &block_id,
98            &mut Default::default(),
99            own_endpoint,
100        )
101        .is_ok()
102    })
103    .await
104    // A panicked check never opens the gate.
105    .unwrap_or(false);
106    if passed {
107        needs_login().lock().unwrap().remove(uid);
108        tracing::info!(target_uid = %uid, "durable jekt: signed in, delivering held messages");
109        return false;
110    }
111    mark_needs_login(uid);
112    true
113}
114
115/// [`decide`] for a routine message to an agent in `status`. The offline model API is asked apart from the
116/// cold-session rule: a cold session's verdict is `Wait Cold`, which would otherwise hide it, and the
117/// replay would inject what was held for the API into a turn that fails.
118fn routine_decision(status: &crate::backend::agent_status::AgentStatus, cold_after_ms: Option<u64>) -> Decision {
119    let message = |cold_after_ms| Intent::Message { urgent: false, routine: true, cold_after_ms };
120    match decide(status, message(None), || false) {
121        offline @ Decision::Wait { reason: WaitReason::ApiOffline, .. } => offline,
122        _ => decide(status, message(cold_after_ms), || false),
123    }
124}
125
126/// What a routine message to `uid` should do now: `decide` on the target's status, the answer
127/// `jekt_cold` gives a message arriving at this moment, so replay and a fresh send agree. A read
128/// of its block, no gate check. It ends at the reset, a confirmed sign-in or an account move
129/// (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §5). A target with no block is delivered to, as before.
130async fn target_decision(state: &AppState, uid: &str, cold_after_ms: Option<u64>) -> Decision {
131    let Some(block_id) = state.reactive_handler.block_for_uid(uid) else {
132        return Decision::Deliver;
133    };
134    let mstore = state.mstore.clone();
135    tokio::task::spawn_blocking(move || {
136        let block = mstore.get::<Block>(&block_id).ok().flatten();
137        let status = status_of(&mstore, Some(&block_id), block.as_ref(), &crate::connectivity::status(), agentmux_common::time::now_ms_u64());
138        routine_decision(&status, cold_after_ms)
139    })
140    .await
141    // A panicked read never delivers into a turn that may fail.
142    .unwrap_or(Decision::Wait { reason: WaitReason::UsageLimit, until_ms: None })
143}
144
145/// Longest one replay pass for messages held for peers' agents may take: it asks the relay about each
146/// agent whose machine is down, and a relay that does not answer costs seconds per agent.
147const PEER_PASS_LIMIT: Duration = Duration::from_secs(60);
148
149/// Replay held jekts: once now, then whenever an agent registers and every
150/// 30 s. Installed after `AppState` exists. The messages held for peers' agents are replayed by a loop
151/// of their own, so a slow relay never delays the local replay.
152pub(crate) fn install(state: &AppState) {
153    let peers = state.clone();
154    tokio::spawn(async move {
155        loop {
156            let _ = tokio::time::timeout(PEER_PASS_LIMIT, super::reactive::peer_hold::replay_pass(&peers)).await;
157            tokio::time::sleep(SWEEP_EVERY).await;
158        }
159    });
160    let state = state.clone();
161    tokio::spawn(async move {
162        loop {
163            replay_pass(&state).await;
164            tokio::select! {
165                _ = crate::backend::reactive::held_jekt_wake().notified() => {}
166                _ = tokio::time::sleep(SWEEP_EVERY) => {}
167            }
168        }
169    });
170}
171
172/// How one replay attempt ended.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub(crate) enum ReplayOutcome {
175    Delivered,
176    /// Still absent, rate-limited, or its queue full — try again later, no
177    /// attempt counted.
178    Deferred,
179    /// Refused while present; counted.
180    Failed,
181    /// Refused `MAX_ATTEMPTS` times; dropped.
182    Dropped,
183    /// The sender's expiry passed before the target could take it; dropped
184    /// at delivery time with one log line instead of delivered stale
185    /// (issue #3894).
186    Expired,
187}
188
189/// One pass: drop expired rows, then deliver to every target that is now
190/// registered, oldest first, at most [`REPLAY_PER_PASS`]. A target that is
191/// still absent costs a map lookup — no rate-limit token, no audit entry.
192pub(crate) async fn replay_pass(state: &AppState) -> Vec<(String, ReplayOutcome)> {
193    let mstore = state.mstore.clone();
194    let now = agentmux_common::time::now_ms();
195    let targets = tokio::task::spawn_blocking(move || {
196        match mstore.jekt_held_delete_expired(now) {
197            Ok(n) if n > 0 => {
198                for _ in 0..n {
199                    crate::backend::agent_resolve::record_uid_fallback("jekt.held_expired");
200                }
201                tracing::info!(expired = n, "durable jekt: held messages expired");
202            }
203            Ok(_) => {}
204            Err(e) => tracing::warn!(error = %e, "durable jekt: expiry failed"),
205        }
206        mstore.jekt_held_targets().unwrap_or_default()
207    })
208    .await
209    .unwrap_or_default();
210
211    // Rotate the starting target every pass, so targets that keep failing
212    // cannot take the budget ahead of a healthy one forever (Codex P2).
213    let mut targets = targets;
214    if !targets.is_empty() {
215        static ROTATION: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
216        let n = targets.len();
217        targets.rotate_left(ROTATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % n);
218    }
219    let extra = state.config_watcher.get_full_config().settings.extra.clone();
220    let cold_after_ms = crate::backend::cold_hold::cold_after_ms(&extra).and_then(|ms| u64::try_from(ms).ok());
221    let quota_tight = crate::backend::quota_mode::is_tight(&extra);
222    let mut outcomes = Vec::new();
223    let mut spent = 0;
224    for uid in targets {
225        if spent >= REPLAY_PER_PASS {
226            break;
227        }
228        if !state.reactive_handler.has_uid_registration(&uid) {
229            continue;
230        }
231        // Its pane registered it, but its controller is not there yet (every resumed pane, for
232        // seconds, when AgentMux starts): as absent as an unregistered one, so nothing is tried or
233        // counted. The controller registering wakes this loop (`controller_wait`).
234        if state.reactive_handler.block_for_uid(&uid).is_some_and(|b| crate::backend::reactive::controller_wait::awaits_controller(&b)) {
235            continue;
236        }
237        if still_needs_login(state, &uid).await {
238            continue;
239        }
240        // What was held because the session was cold waits until it is warm (the agent wrote
241        // something since: the operator typed, or an urgent message started a turn), or
242        // until it has waited out its 24 hours.
243        let warm = match target_decision(state, &uid, cold_after_ms).await {
244            Decision::Wait { reason: WaitReason::UsageLimit | WaitReason::NeedsLogin | WaitReason::ApiOffline, .. } => continue,
245            // A session with no process is not warm, whatever it last wrote: its `idle` rows wait.
246            Decision::Wait { reason: WaitReason::Cold | WaitReason::NotRunning, .. } => false,
247            _ => true,
248        };
249        // What quota mode held goes once the mode is off, a turn is in flight (it joins it), or the agent
250        // has written output since it was sent.
251        let activity = state.reactive_handler.block_for_uid(&uid).and_then(|block_id| crate::backend::cold_hold::session_activity(&block_id));
252        let gate = crate::backend::storage::jekt_held::ReplayGate {
253            now_ms: now,
254            warm,
255            quota_open: !quota_tight || matches!(activity, Some((true, _))),
256            active_at_ms: activity.and_then(|(_, last_output)| last_output).unwrap_or(0),
257        };
258        let mstore = state.mstore.clone();
259        let budget = REPLAY_PER_PASS - spent;
260        let rows = tokio::task::spawn_blocking(move || mstore.jekt_held_ready_for(&uid, budget, &gate))
261            .await
262            .ok()
263            .and_then(Result::ok)
264            .unwrap_or_default();
265        for row in rows {
266            let id = row.request_id.clone();
267            let outcome = replay_one(state, row).await;
268            outcomes.push((id, outcome));
269            // A deferral (queue full, starting) applies to this target's
270            // later rows too: move on, spending no budget. A failure also
271            // ends this target's turn, spending one slot — so a target that
272            // keeps refusing takes at most one slot per pass and cannot
273            // starve the others (Codex P2 on #3632).
274            match outcome {
275                ReplayOutcome::Deferred => break,
276                ReplayOutcome::Failed | ReplayOutcome::Dropped => {
277                    spent += 1;
278                    break;
279                }
280                // An expired row is gone — it cannot be retried — but it
281                // took a fetch slot, so it spends like a delivery: a target
282                // with a backlog of expired notices cannot crowd the pass.
283                ReplayOutcome::Expired | ReplayOutcome::Delivered => spent += 1,
284            }
285        }
286    }
287    outcomes
288}
289
290pub(crate) use crate::backend::reactive::held_request::request_from_held;
291
292async fn replay_one(state: &AppState, row: HeldJekt) -> ReplayOutcome {
293    // The sender's expiry (issue #3894): a notice that mattered for ten
294    // minutes is worse delivered an hour late, in a burst, than dropped.
295    // Delivery time — the moment this row would be injected — is the last
296    // honest check; the 30 s sweep drops most expired rows earlier, this
297    // covers a row whose expiry passed since the sweep or that was ready
298    // before it. No expiry: today's behaviour exactly.
299    if row.sender_expires_at_ms.is_some_and(|expires| expires <= agentmux_common::time::now_ms()) {
300        let mstore = state.mstore.clone();
301        let id = row.request_id.clone();
302        let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
303        crate::backend::agent_resolve::record_uid_fallback("jekt.held_sender_expired");
304        tracing::info!(
305            target_uid = %row.target_uid,
306            source_agent = %row.source_agent,
307            "durable jekt: the sender's expiry passed — dropping the held message instead of delivering it"
308        );
309        return ReplayOutcome::Expired;
310    }
311    // The transcript-request fields are restored as accepted, never
312    // recomputed: the replay addresses the target by UID, and the slug-keyed
313    // recompute would lose a forced escalation.
314    let mut req = request_from_held(&row);
315    super::jekt_files::prepare(&mut req).await;
316    let charged = req.clone();
317    let resp = state.reactive_handler.inject_held(req);
318    super::jekt_files::settle(&charged, resp.success);
319    let mstore = state.mstore.clone();
320    let id = row.request_id.clone();
321    if resp.success {
322        let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
323        crate::backend::agent_resolve::record_uid_fallback("jekt.held_delivered");
324        return ReplayOutcome::Delivered;
325    }
326    let error = resp.error.unwrap_or_default();
327    // Transient: still absent, rate-limited, its queue full, the agent
328    // starting, restarting or stopping ("… try again shortly"), or its
329    // controller gone between the look above and the delivery.
330    if crate::backend::reactive::is_transient_delivery_error(&error) {
331        return ReplayOutcome::Deferred;
332    }
333    // Not signed in: wait for sign-in, uncounted (G6 counted it, so a
334    // signed-out receiver lost its messages after 20 tries).
335    if is_spawn_gate_refusal(&error) {
336        mark_needs_login(&row.target_uid);
337        return ReplayOutcome::Deferred;
338    }
339    let attempts = tokio::task::spawn_blocking({
340        let mstore = mstore.clone();
341        let id = id.clone();
342        let error = error.clone();
343        // A store fault is not a failed delivery: never drop on it.
344        move || mstore.jekt_held_record_failure(&id, &error).unwrap_or(0)
345    })
346    .await
347    .unwrap_or(0);
348    if attempts >= MAX_ATTEMPTS {
349        let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
350        crate::backend::agent_resolve::record_uid_fallback("jekt.held_failed");
351        tracing::warn!(target_uid = %row.target_uid, error = %error, "durable jekt: dropped after repeated failures");
352        return ReplayOutcome::Dropped;
353    }
354    ReplayOutcome::Failed
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use std::time::Instant;
361
362    /// What was held for an offline API stays held when the session has gone cold meanwhile: the cold
363    /// verdict must not hide the offline API from the replay.
364    #[test]
365    fn a_cold_session_with_an_offline_api_still_waits_for_the_api() {
366        use crate::backend::agent_availability::Availability;
367        use crate::backend::agent_status::{AgentStatus, Pane, Reach, Wanted};
368        let after = 55 * 60_000;
369        let status = |quiet, api| AgentStatus {
370            availability: Availability::Idle { quiet_for_ms: Some(quiet) },
371            pane: Pane::Shown,
372            wanted: Wanted::Running,
373            api,
374            controller: true,
375        };
376        let api_wait = Decision::Wait { reason: WaitReason::ApiOffline, until_ms: None };
377        assert_eq!(routine_decision(&status(after + 1, Reach::Offline), Some(after)), api_wait, "cold and offline");
378        assert_eq!(routine_decision(&status(5, Reach::Offline), Some(after)), api_wait, "warm and offline");
379        assert_eq!(
380            routine_decision(&status(after + 1, Reach::Online), Some(after)),
381            Decision::Wait { reason: WaitReason::Cold, until_ms: None },
382            "cold, API fine: the cold rule as before"
383        );
384        assert_eq!(routine_decision(&status(5, Reach::Online), Some(after)), Decision::Deliver);
385    }
386
387    #[test]
388    fn a_spawn_gate_refusal_is_recognised_and_nothing_else_is() {
389        assert!(is_spawn_gate_refusal("identity spawn gate: no credentials for claude: …"));
390        for other in ["agent not found: x", "rate limit exceeded", "persistent process not running", ""] {
391            assert!(!is_spawn_gate_refusal(other), "{other}");
392        }
393    }
394
395    /// A refused target is re-checked at most every GATE_RECHECK_EVERY, so the
396    /// 30 s replay never attempts a delivery blind (each would write an error
397    /// frame into the receiver's pane).
398    #[test]
399    fn the_sign_in_check_runs_at_most_once_a_minute() {
400        let now = Instant::now();
401        assert_eq!(gate_check_due(None, now), GateCheck::Open);
402        assert_eq!(gate_check_due(Some(now), now), GateCheck::Wait);
403        assert_eq!(gate_check_due(Some(now), now + Duration::from_secs(59)), GateCheck::Wait);
404        assert_eq!(gate_check_due(Some(now), now + GATE_RECHECK_EVERY), GateCheck::Recheck);
405    }
406
407    /// Issue #3894: a row that reaches delivery with the sender's deadline
408    /// already past is dropped there too — the pass's own sweep is the usual
409    /// path, and this covers a row that expired between the sweep and its own
410    /// turn in the pass (or one re-held on the way).
411    #[tokio::test]
412    async fn a_row_past_its_senders_expiry_is_dropped_at_delivery_time() {
413        use crate::backend::reactive::types::InjectionRequest;
414        let state = crate::server::tests::test_state();
415        let now = agentmux_common::time::now_ms();
416        let req = InjectionRequest {
417            target_agent: "expired-target".to_string(),
418            message: "stale".to_string(),
419            source_agent: Some("sender".to_string()),
420            request_id: Some("req-expired-direct".to_string()),
421            expires_at_ms: Some(now - 1),
422            ..Default::default()
423        };
424        let mut row = crate::server::jekt_hold::held_row(&req, "req-expired-direct".to_string(), now - 1_000);
425        row.target_uid = "uid-expired-direct".to_string();
426        state.mstore.jekt_held_insert(&row).unwrap();
427
428        assert_eq!(replay_one(&state, row).await, ReplayOutcome::Expired);
429        assert!(state.mstore.jekt_held_for_target("uid-expired-direct", 10).unwrap().is_empty());
430    }
431
432    /// Issue #3894: the sender's deadline is kept on the held row and rides
433    /// the replay request again, so a delivery that ends up waiting once more
434    /// (the controller's startup queue) still drops it at its own deadline.
435    #[test]
436    fn a_held_rows_sender_expiry_rides_into_the_replay_request() {
437        use crate::backend::reactive::types::InjectionRequest;
438        let req = InjectionRequest {
439            target_agent: "agenty".to_string(),
440            message: "hi".to_string(),
441            source_agent: Some("sender".to_string()),
442            expires_at_ms: Some(1_234_567),
443            ..Default::default()
444        };
445        let row = crate::server::jekt_hold::held_row(&req, "req-sender-expiry".to_string(), 10);
446        assert_eq!(row.sender_expires_at_ms, Some(1_234_567), "kept on the row");
447        let replay = request_from_held(&row);
448        assert_eq!(replay.expires_at_ms, Some(1_234_567), "and on the delivery request");
449    }
450
451    /// #31433: a replay addresses the target by UID (it still reaches the same
452    /// agent after a rename) but the marker is addressed as the sender wrote
453    /// it, the way a live delivery is. Nothing is added when the row's name is
454    /// already the UID.
455    #[test]
456    fn a_replay_names_the_target_the_sender_addressed() {
457        use crate::backend::reactive::types::InjectionRequest;
458        let req = InjectionRequest { target_agent: "Glim".to_string(), message: "hi".to_string(), ..Default::default() };
459        let mut row = crate::server::jekt_hold::held_row(&req, "req-name".to_string(), 10);
460        row.target_uid = "17e48252-bf89-4be9-addc-71b29035c22c".to_string();
461
462        let replay = request_from_held(&row);
463        assert_eq!(replay.target_agent, row.target_uid, "routed by UID");
464        assert_eq!(replay.marker_target.as_deref(), Some("Glim"), "marked by name");
465
466        row.target_agent = row.target_uid.clone();
467        assert_eq!(request_from_held(&row).marker_target, None, "nothing to add when the name is the UID");
468    }
469}
470
471#[cfg(test)]
472#[path = "jekt_held_starting_tests.rs"]
473mod starting_tests;
474
475#[cfg(test)]
476#[path = "jekt_held_gate_tests.rs"]
477mod gate_tests;