agentmux_srv_core/backend/jobs/
remote.rs1use std::sync::Arc;
38
39use agentmux_common::time::now_ms;
40use serde_json::json;
41
42use super::follower::NO_TURN_AFTER_MS;
43use super::{registered_uid, RunLedger, SOURCE_CRON};
44use crate::backend::storage::job_runs::{infra, reason, JobRun};
45
46pub const FOLLOWED_BY_CHANNEL: &str = "followed_by_channel";
49pub const FOLLOWED_BY_PID: &str = "followed_by_pid";
50pub const FOLLOWED_AT_MS: &str = "followed_at_ms";
51
52pub const NOT_FOLLOWED: &str = "delivered to an agent in another channel; AgentMux can't follow its turn from here";
54pub const FOLLOWER_GONE: &str = "the AgentMux that followed this run stopped during it";
56
57pub const STOP_REQUESTED: &str = "stop_requested";
60pub const STOP_ERROR: &str = "stop_error";
61const STOP_RETRY_MS: i64 = 60_000;
65const STOP_ATTEMPTS: u64 = 5;
66
67#[derive(Debug, Clone, PartialEq)]
69pub struct RemoteStop {
70 pub run_id: String,
71 pub block_id: String,
73 pub from_channel: String,
75 pub infra: String,
76 pub reason: String,
77 pub summary: String,
78}
79
80pub type RemoteStopHook = Arc<dyn Fn(RemoteStop) + Send + Sync>;
84
85fn stop_is_known(infra_status: &str, why: &str) -> bool {
88 matches!((infra_status, why), (infra::TIMEOUT, reason::TIMEOUT) | (infra::INTERRUPTED, reason::OVERLAP))
89}
90
91#[derive(Debug, Clone, PartialEq)]
93pub struct FollowedBy {
94 pub channel: String,
95 pub pid: u32,
97 pub at_ms: Option<i64>,
98}
99
100pub fn followed_by(run: &JobRun) -> Option<FollowedBy> {
102 let channel = run.links.get(FOLLOWED_BY_CHANNEL)?.as_str().filter(|c| !c.is_empty())?;
103 let pid = run.links.get(FOLLOWED_BY_PID).and_then(|v| v.as_u64()).unwrap_or(0);
104 let at_ms = run.links.get(FOLLOWED_AT_MS).and_then(|v| v.as_i64());
105 Some(FollowedBy { channel: channel.to_string(), pid: u32::try_from(pid).unwrap_or(0), at_ms })
106}
107
108fn follower_alive(pid: u32, at_ms: Option<i64>) -> bool {
112 let at = at_ms.and_then(|ms| u64::try_from(ms).ok()).map(|ms| std::time::UNIX_EPOCH + std::time::Duration::from_millis(ms));
113 crate::backend::process_identity::srv_alive(pid, at)
114}
115
116fn recorded_in(recorded_by: &str, channel: &str) -> bool {
118 recorded_by == channel || recorded_by.strip_prefix(channel).is_some_and(|rest| rest.starts_with('@'))
119}
120
121#[derive(Debug, Clone, PartialEq)]
123pub enum Verdict {
124 Done,
126 Wait,
128 Close { infra: &'static str, summary: &'static str },
130}
131
132pub fn verdict(run: Option<&JobRun>, armed_at_ms: i64, now: i64, alive: impl Fn(u32, Option<i64>) -> bool) -> Verdict {
135 let Some(run) = run.filter(|r| r.ended_at_ms.is_none()) else {
136 return Verdict::Done;
137 };
138 match followed_by(run) {
139 Some(f) if f.pid != 0 && !alive(f.pid, f.at_ms) => Verdict::Close { infra: infra::INTERRUPTED, summary: FOLLOWER_GONE },
140 Some(_) => Verdict::Wait,
141 None if now - armed_at_ms > NO_TURN_AFTER_MS => Verdict::Close { infra: infra::OK, summary: NOT_FOLLOWED },
142 None => Verdict::Wait,
143 }
144}
145
146impl RunLedger {
147 pub(super) fn followed_elsewhere(&self, run_id: &str) -> bool {
149 let run = self.store.job_run_get(run_id).ok().flatten();
150 run.as_ref().and_then(followed_by).is_some_and(|f| f.channel != self.channel)
151 }
152
153 pub fn follow_forwarded(&self, run_id: &str, block_id: &str, delivery_started_ms: i64) -> bool {
164 if run_id.is_empty() || block_id.is_empty() {
165 return false;
166 }
167 let Ok(Some(run)) = self.store.job_run_get(run_id) else { return false };
168 if run.job_source != SOURCE_CRON || !run.is_open() || recorded_in(&run.recorded_by, &self.channel) || followed_by(&run).is_some() {
171 return false;
172 }
173 let now = delivery_started_ms;
174 let pane = self.pane(block_id);
175 let receiver = [pane.agent_uid.as_str(), registered_uid(block_id).as_deref().unwrap_or("")]
176 .into_iter()
177 .find(|u| !u.is_empty())
178 .unwrap_or("")
179 .to_string();
180 match self.store.job_run_mark_running(run_id, &receiver, block_id, &pane.account, &pane.provider, now) {
181 Ok(true) => {}
182 Ok(false) => return false,
183 Err(e) => {
184 tracing::warn!(run_id, error = %e, "jobs: couldn't take a forwarded run");
185 return false;
186 }
187 }
188 let links = json!({
189 FOLLOWED_BY_CHANNEL: self.channel,
190 FOLLOWED_BY_PID: std::process::id(),
191 FOLLOWED_AT_MS: now,
192 "transcript": { "block_id": block_id, "channel": self.channel },
193 });
194 if let Err(e) = self.store.job_run_add_links(run_id, &links) {
195 tracing::warn!(run_id, error = %e, "jobs: couldn't note who follows a forwarded run");
196 }
197 self.follower.arm(block_id, run_id, now, self.stop_at_usd(run_id, &pane.provider));
198 self.changed(&run.job_id);
201 tracing::info!(run_id, block_id, recorded_by = %run.recorded_by, "jobs: following a run another channel fired");
202 true
203 }
204
205 pub fn check_remote(&self, run_id: &str, armed_at_ms: i64, now: i64) -> bool {
208 let run = self.store.job_run_get(run_id).ok().flatten();
209 match verdict(run.as_ref(), armed_at_ms, now, follower_alive) {
210 Verdict::Done => {
211 if let Some(run) = &run {
214 self.changed(&run.job_id);
215 }
216 true
217 }
218 Verdict::Wait => false,
219 Verdict::Close { infra, summary } => {
220 self.turn_finished(run_id, infra, None, summary);
221 true
222 }
223 }
224 }
225
226 pub fn install_remote_stop(&self, hook: RemoteStopHook) {
228 let _ = self.remote_stop.set(hook);
229 }
230
231 pub(super) fn request_remote_stop(&self, run: &JobRun, infra_status: &str, why: &str, summary: &str) -> bool {
238 if followed_by(run).is_none() || run.block_id.is_empty() || !stop_is_known(infra_status, why) {
239 return false;
240 }
241 let Some(hook) = self.remote_stop.get() else { return false };
242 let asked = run.links.get(STOP_REQUESTED);
243 let attempts = asked.and_then(|a| a.get("attempts")).and_then(|v| v.as_u64()).unwrap_or(0);
244 let last = asked.and_then(|a| a.get("at_ms")).and_then(|v| v.as_i64()).unwrap_or(0);
245 let now = now_ms();
246 if attempts >= STOP_ATTEMPTS || now - last < STOP_RETRY_MS {
247 return false;
248 }
249 let note = json!({ STOP_REQUESTED: {
250 "at_ms": now, "attempts": attempts + 1, "by_channel": self.channel,
251 "infra": infra_status, "reason": why, "summary": summary,
252 }});
253 if let Err(e) = self.store.job_run_add_links(&run.id, ¬e) {
254 tracing::warn!(run_id = %run.id, error = %e, "jobs: couldn't note a stop asked of another channel");
256 return false;
257 }
258 hook(RemoteStop {
259 run_id: run.id.clone(),
260 block_id: run.block_id.clone(),
261 from_channel: self.channel.clone(),
262 infra: infra_status.to_string(),
263 reason: why.to_string(),
264 summary: summary.to_string(),
265 });
266 tracing::info!(run_id = %run.id, block_id = %run.block_id, reason = why, "jobs: asking the AgentMux that follows a run to stop it");
267 true
268 }
269
270 pub fn remote_stop_done(&self, run_id: &str) {
273 self.run_changed(run_id);
274 super::pending_wake().notify_one();
275 }
276
277 pub fn remote_stop_failed(&self, run_id: &str, error: &str) {
280 let note = json!({ STOP_ERROR: { "at_ms": now_ms(), "error": error } });
281 if let Err(e) = self.store.job_run_add_links(run_id, ¬e) {
282 tracing::warn!(run_id, error = %e, "jobs: couldn't note why a stop could not be delivered");
283 }
284 tracing::warn!(run_id, error, "jobs: the AgentMux that follows a run could not be asked to stop it");
285 self.run_changed(run_id);
286 }
287
288 pub fn stop_followed_here(&self, run_id: &str, block_id: &str, from_channel: &str) -> Result<bool, String> {
296 let run = self.store.job_run_get(run_id).map_err(|e| e.to_string())?.ok_or_else(|| "no such run".to_string())?;
297 let follows = followed_by(&run).is_some_and(|f| f.channel == self.channel && (f.pid == 0 || f.pid == std::process::id()));
298 if !follows {
299 return Err("this AgentMux does not follow that run".to_string());
300 }
301 if run.block_id.is_empty() || run.block_id != block_id {
302 return Err("that run is not in that pane".to_string());
303 }
304 if from_channel.is_empty() || !recorded_in(&run.recorded_by, from_channel) {
305 return Err("that run was not fired by that AgentMux".to_string());
306 }
307 let asked = run.links.get(STOP_REQUESTED).filter(|a| a.get("by_channel").and_then(|c| c.as_str()) == Some(from_channel));
308 let text = |key: &str| asked.and_then(|a| a.get(key)).and_then(|v| v.as_str()).unwrap_or("").to_string();
309 let (infra_status, why, summary) = (text("infra"), text("reason"), text("summary"));
310 if asked.is_none() || !stop_is_known(&infra_status, &why) {
311 return Err("that AgentMux has not asked for a stop of that run".to_string());
312 }
313 if !run.is_open() {
314 return Ok(false);
315 }
316 match self.store.job_run_stop(&run.id, &infra_status, &why, &summary, now_ms()) {
317 Ok(true) => {
318 self.interrupt_block(&run.block_id);
319 self.reap_worker(&run.id);
320 self.run_changed(&run.id);
321 super::pending_wake().notify_one();
322 Ok(true)
323 }
324 Ok(false) => Ok(false),
325 Err(e) => Err(e.to_string()),
326 }
327 }
328}
329
330#[cfg(test)]
331#[path = "remote_tests.rs"]
332mod tests;