Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
replace.rs

1// Copyright 2025, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a subprocess controller leaves for the one that replaces it.
5//!
6//! A resync that needs a different controller (a runtime-config or controller-type change) stops the old
7//! one with `stop_for_replace` and builds a new one for the same block. The messages the old one had accepted
8//! are not lost with it:
9//!
10//! - what was queued behind the turn the replace ended is run by the replacement, which starts a turn from
11//!   the first of them as soon as it is registered ([`SubprocessController::run_queue_left_by_replaced`]);
12//! - what a user stop held (`held_after_stop`) stays held, and is queued behind the next turn that is accepted.
13//!
14//! Both wait in [`LEFT_FOR_REPLACEMENT`] between the old controller's last act and the new one's construction.
15//! An entry nobody takes (the block is deleted, or its replacement is a controller of another type) is dropped
16//! when the block is deleted ([`forget_left_for_replacement`]) and after [`LEFT_FOR_REPLACEMENT_TTL`].
17
18use std::collections::{HashMap, VecDeque};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, Instant};
22
23use super::{SubprocessController, SubprocessSpawnConfig};
24use crate::backend::runtime_adapter::RuntimeAdapter;
25
26/// How long an entry waits for its replacement. A resync builds that within the same call, so this only
27/// bounds an entry whose replacement never comes.
28const LEFT_FOR_REPLACEMENT_TTL: Duration = Duration::from_secs(300);
29
30/// How long the replacement waits for the replaced controller's killed turn to be gone before it starts its own.
31const OLD_TURN_EXIT_WAIT: Duration = Duration::from_secs(10);
32
33/// The container a container turn ran in and the command it ran: a queued message's own CLI arguments were taken
34/// into that command when it was queued, so the queue is run with it again, not through the adapter.
35#[derive(Clone)]
36pub(super) struct ContainerContext {
37    pub(super) cm: crate::backend::container::ContainerManager,
38    pub(super) container_name: String,
39    pub(super) base_cmd: Vec<String>,
40}
41
42/// What one replaced controller leaves for the next one of its block.
43pub(super) struct LeftForReplacement {
44    /// Held by a user stop; stay held.
45    pub(super) held: VecDeque<SubprocessSpawnConfig>,
46    /// Queued behind the turn the replace ended; the replacement runs them.
47    pub(super) queued: VecDeque<SubprocessSpawnConfig>,
48    /// The session the old controller was on: a queued message continues it.
49    pub(super) session_id: Option<String>,
50    /// How the last message was launched (host process or container exec), to launch the queued ones the same way.
51    pub(super) adapter: Option<Arc<dyn RuntimeAdapter>>,
52    /// The old controller's run lock: set while its killed turn is still winding down.
53    pub(super) old_run_lock: Option<Arc<AtomicBool>>,
54    /// For a container agent: how its queued messages are launched.
55    pub(super) container: Option<ContainerContext>,
56    left_at: Instant,
57}
58
59static LEFT_FOR_REPLACEMENT: Mutex<Option<HashMap<String, LeftForReplacement>>> = Mutex::new(None);
60
61fn drop_expired(map: &mut HashMap<String, LeftForReplacement>) {
62    map.retain(|_, left| left.left_at.elapsed() < LEFT_FOR_REPLACEMENT_TTL);
63}
64
65/// The entry [`SubprocessController::hand_over_held_to_replacement`] left for `block_id`'s next controller.
66pub(super) fn take_left_for_replacement(block_id: &str) -> Option<LeftForReplacement> {
67    let mut guard = LEFT_FOR_REPLACEMENT.lock().unwrap();
68    let map = guard.as_mut()?;
69    drop_expired(map);
70    map.remove(block_id)
71}
72
73/// Drop what a replaced controller left for `block_id`: the block is gone, so nothing will take it.
74pub fn forget_left_for_replacement(block_id: &str) {
75    if let Some(map) = LEFT_FOR_REPLACEMENT.lock().unwrap().as_mut() {
76        map.remove(block_id);
77    }
78}
79
80#[cfg(test)]
81pub(crate) fn left_for_replacement_count(block_id: &str) -> usize {
82    LEFT_FOR_REPLACEMENT.lock().unwrap().as_ref().map_or(0, |m| usize::from(m.contains_key(block_id)))
83}
84
85#[cfg(test)]
86pub(crate) fn age_left_for_replacement(block_id: &str, by: Duration) {
87    if let Some(left) = LEFT_FOR_REPLACEMENT.lock().unwrap().as_mut().and_then(|m| m.get_mut(block_id)) {
88        left.left_at -= by;
89    }
90}
91
92impl SubprocessController {
93    /// How the next queued message is launched: remembered from the last message that was accepted.
94    pub fn remember_adapter(&self, adapter: Arc<dyn RuntimeAdapter>) {
95        *self.adapter.lock().unwrap() = Some(adapter);
96    }
97
98    /// A container turn is starting or queuing: remember what it runs in and with.
99    pub(super) fn remember_container_context(&self, cm: &crate::backend::container::ContainerManager, container_name: &str, base_cmd: &[String]) {
100        *self.container_context.lock().unwrap() =
101            Some(ContainerContext { cm: cm.clone(), container_name: container_name.to_string(), base_cmd: base_cmd.to_vec() });
102    }
103
104    /// `stop_for_replace`: end the turn, but keep what was queued behind it for the replacement. Unlike `stop`
105    /// this is not a user's stop, so nothing is held: the messages were accepted and are to run.
106    pub(super) fn stop_keeping_queue_for_replacement(&self, new_status: &str) -> Result<(), String> {
107        {
108            let mut inner = self.inner.lock().unwrap();
109            let queued = std::mem::take(&mut inner.pending_messages);
110            if !queued.is_empty() {
111                tracing::info!(
112                    block_id = %self.block_id,
113                    queued = queued.len(),
114                    "controller replaced: messages queued behind its turn go to the new one"
115                );
116            }
117            inner.queued_for_replacement.extend(queued);
118        }
119        self.stop_subprocess(true)?;
120        let mut inner = self.inner.lock().unwrap();
121        if inner.proc_status != new_status {
122            Self::set_status(&mut inner, new_status);
123        }
124        Ok(())
125    }
126
127    /// This controller is being replaced: what it holds goes to the controller that takes its place.
128    pub(crate) fn hand_over_held_to_replacement(&self) {
129        let (held, queued, session_id) = {
130            let mut inner = self.inner.lock().unwrap();
131            let mut queued = std::mem::take(&mut inner.queued_for_replacement);
132            queued.extend(std::mem::take(&mut inner.pending_messages));
133            (std::mem::take(&mut inner.held_after_stop), queued, inner.session_id.clone())
134        };
135        if held.is_empty() && queued.is_empty() {
136            return;
137        }
138        tracing::info!(
139            block_id = %self.block_id,
140            held = held.len(),
141            queued = queued.len(),
142            "controller replaced: its messages go to the new one"
143        );
144        let adapter = self.adapter.lock().unwrap().clone();
145        let mut guard = LEFT_FOR_REPLACEMENT.lock().unwrap();
146        let map = guard.get_or_insert_with(HashMap::new);
147        drop_expired(map);
148        let left = map.entry(self.block_id.clone()).or_insert_with(|| LeftForReplacement {
149            held: VecDeque::new(),
150            queued: VecDeque::new(),
151            session_id: None,
152            adapter: None,
153            old_run_lock: None,
154            container: None,
155            left_at: Instant::now(),
156        });
157        left.held.extend(held);
158        left.queued.extend(queued);
159        left.session_id = session_id.or_else(|| left.session_id.take());
160        left.adapter = adapter.or_else(|| left.adapter.take());
161        left.old_run_lock = Some(Arc::clone(&self.run_lock));
162        left.container = self.container_context.lock().unwrap().clone().or_else(|| left.container.take());
163        left.left_at = Instant::now();
164    }
165
166    /// A replacement built from what the old controller left: start a turn from the first message it had queued
167    /// (the rest run behind it), once the old controller's killed turn is gone. Without a way to launch
168    /// (no adapter was remembered, or there is no async runtime), the messages are held instead, to run behind
169    /// the next turn that is accepted: never dropped.
170    pub(crate) fn run_queue_left_by_replaced(self: &Arc<Self>) {
171        let adapter = self.adapter.lock().unwrap().clone();
172        let old_run_lock = self.left_old_run_lock.lock().unwrap().take();
173        let container = self.container_context.lock().unwrap().clone();
174        let handle = tokio::runtime::Handle::try_current().ok();
175        let (Some(adapter), Some(handle)) = (adapter, handle) else {
176            let mut inner = self.inner.lock().unwrap();
177            if !inner.pending_messages.is_empty() {
178                tracing::warn!(
179                    block_id = %self.block_id,
180                    queued = inner.pending_messages.len(),
181                    "replacement cannot launch the replaced controller's queue now: held for the next turn"
182                );
183                let queued = std::mem::take(&mut inner.pending_messages);
184                inner.held_after_stop.extend(queued);
185            }
186            return;
187        };
188        if self.inner.lock().unwrap().pending_messages.is_empty() {
189            return;
190        }
191        // The run lock is held while the old turn winds down, so a message that arrives meanwhile queues behind
192        // the handed-over ones instead of running ahead of them. (It was just built: the lock is free.)
193        let holding = self.try_lock_run();
194        let ctrl = Arc::clone(self);
195        handle.spawn(async move {
196            if let Some(lock) = old_run_lock {
197                let started = Instant::now();
198                while lock.load(Ordering::SeqCst) && started.elapsed() < OLD_TURN_EXIT_WAIT {
199                    tokio::time::sleep(Duration::from_millis(50)).await;
200                }
201            }
202            // The first queued message takes the lock back through the launch.
203            let first = ctrl.inner.lock().unwrap().pending_messages.pop_front();
204            if holding {
205                ctrl.unlock_run();
206            }
207            let Some(first) = first else { return };
208            adapter.materialize(&ctrl);
209            let launched = match container {
210                Some(c) => ctrl.spawn_container_turn(c.cm, c.container_name, c.base_cmd, first),
211                None => adapter.launch(&ctrl, first),
212            };
213            if let Err(e) = launched {
214                tracing::warn!(block_id = %ctrl.block_id, error = %e, "failed to start the replaced controller's queued turn");
215                SubprocessController::publish_queued_spawn_error(&ctrl.block_id, &e, &ctrl.broker, &ctrl.filestore, &ctrl.mstore);
216            }
217        });
218    }
219}