agentmux_srv_core/backend/blockcontroller/subprocess/
replace.rs1use 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
26const LEFT_FOR_REPLACEMENT_TTL: Duration = Duration::from_secs(300);
29
30const OLD_TURN_EXIT_WAIT: Duration = Duration::from_secs(10);
32
33#[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
42pub(super) struct LeftForReplacement {
44 pub(super) held: VecDeque<SubprocessSpawnConfig>,
46 pub(super) queued: VecDeque<SubprocessSpawnConfig>,
48 pub(super) session_id: Option<String>,
50 pub(super) adapter: Option<Arc<dyn RuntimeAdapter>>,
52 pub(super) old_run_lock: Option<Arc<AtomicBool>>,
54 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
65pub(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
73pub 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 pub fn remember_adapter(&self, adapter: Arc<dyn RuntimeAdapter>) {
95 *self.adapter.lock().unwrap() = Some(adapter);
96 }
97
98 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 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 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 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 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 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}