Skip to main content

agentmux_srv_core/backend/jobs/
remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A run delivered to an agent in another channel (#1988, spec §3.2).
5//!
6//! Each AgentMux publishes turn events to its own broker, so the instance
7//! that fired a run can't see the turn of a pane another channel holds. The
8//! ledger is shared, though, and the run id is the delivery's `request_id`:
9//! the receiving instance finds the open row by it, marks it running with
10//! its own pane's account, notes itself in `links.followed_by_channel` and
11//! follows the turn on its own broker ([`RunLedger::follow_forwarded`]).
12//!
13//! The firing instance only watches the row ([`RunLedger::check_remote`]):
14//! a run nobody followed (a receiver on an older build) is closed after the
15//! no-turn timeout, cost unknown, as before; a run whose follower's process
16//! is gone is interrupted. That process counts only while it is still the
17//! srv that wrote the claim (`process_identity::srv_alive`): a pid another
18//! program reused reads as gone. Every close is the conditional `job_run_finish`,
19//! so whichever side writes first wins and the other changes nothing.
20//!
21//! **Stopping such a run.** A timeout, or a `cancel_other` overlap, can't
22//! interrupt the pane from the firing instance, and closing the row there
23//! would free its place while the agent goes on working. So the firing
24//! instance asks the following one ([`RunLedger::request_remote_stop`], a
25//! [`RemoteStopHook`] the server installs), notes the ask in
26//! `links.stop_requested`, and leaves the row open. The following instance
27//! ([`RunLedger::stop_followed_here`]) closes the row with the status asked
28//! for and interrupts the pane, as a local stop does. When the ask can't be
29//! delivered the reason goes in `links.stop_error` and it is tried again.
30//!
31//! **Whose stop it is.** The ask over HTTP names only the run, the pane and the
32//! asking channel. What the follower acts on is the note in the shared ledger,
33//! which only the instance that fired the run writes, so another channel that
34//! guesses a run id, or names the right channel, stops nothing: the row has to
35//! carry a stop its own origin asked for.
36
37use 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
46/// The `links` keys the following instance writes: its channel, its
47/// process id, and when it took the run.
48pub 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
52/// The summary of a run no instance followed.
53pub const NOT_FOLLOWED: &str = "delivered to an agent in another channel; AgentMux can't follow its turn from here";
54/// The summary of a run whose following instance stopped during it.
55pub const FOLLOWER_GONE: &str = "the AgentMux that followed this run stopped during it";
56
57/// The `links` keys of a stop the firing instance asked for, and of why the
58/// ask could not be delivered.
59pub const STOP_REQUESTED: &str = "stop_requested";
60pub const STOP_ERROR: &str = "stop_error";
61/// An ask is repeated no sooner than this, and no more than `STOP_ATTEMPTS`
62/// times: a following instance that never answers is left to the checks
63/// above (its process gone, its turn ending).
64const STOP_RETRY_MS: i64 = 60_000;
65const STOP_ATTEMPTS: u64 = 5;
66
67/// A stop for a run another channel follows, as it is asked of that channel.
68#[derive(Debug, Clone, PartialEq)]
69pub struct RemoteStop {
70    pub run_id: String,
71    /// The pane in the following channel.
72    pub block_id: String,
73    /// The channel asking: the one that fired the run.
74    pub from_channel: String,
75    pub infra: String,
76    pub reason: String,
77    pub summary: String,
78}
79
80/// How the server delivers a [`RemoteStop`] (it needs the shared registry and
81/// an HTTP client, which the ledger has not). It reports back through
82/// [`RunLedger::remote_stop_done`] or [`RunLedger::remote_stop_failed`].
83pub type RemoteStopHook = Arc<dyn Fn(RemoteStop) + Send + Sync>;
84
85/// The statuses a stop may close a run with, and the reasons it may give:
86/// what a timeout and `cancel_other` write, so a request can't write others.
87fn 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/// Who follows a run, from its `links`.
92#[derive(Debug, Clone, PartialEq)]
93pub struct FollowedBy {
94    pub channel: String,
95    /// 0 when not written.
96    pub pid: u32,
97    pub at_ms: Option<i64>,
98}
99
100/// Who follows `run`, if anyone.
101pub 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
108/// Whether the follower `pid`, which took the run at `at_ms`, is still that
109/// srv: an `agentmux-srv` process started no later than then, give or take
110/// `process_identity::START_SLACK_SECS`.
111fn 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
116/// Whether `recorded_by` (`<channel>@<version>`) names `channel`.
117fn 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/// What the firing instance does with a watched cross-channel run.
122#[derive(Debug, Clone, PartialEq)]
123pub enum Verdict {
124    /// Closed already, or gone: stop watching.
125    Done,
126    /// Still the receiver's, or still inside the no-turn timeout.
127    Wait,
128    /// Close it with this status and summary, cost unknown.
129    Close { infra: &'static str, summary: &'static str },
130}
131
132/// Judge a watched run, armed at `armed_at_ms`. Pure, with the follower
133/// check (`pid`, `followed_at_ms`) passed in, so the rules are testable.
134pub 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    /// Whether another channel's instance follows run `run_id`.
148    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    /// A delivery this instance just placed in `block_id` was forwarded here
154    /// with `request_id` `run_id`. When that names a cron run another
155    /// channel fired and nobody follows yet, take the follow-up: mark it
156    /// running with this pane's account, note this channel in its links and
157    /// follow its turn here, from `delivery_started_ms`, taken before the
158    /// injection: a turn the delivery started, even one already over, is
159    /// this run's whole turn, as on the local path (`record_delivery`).
160    /// Called before the delivery's answer goes back,
161    /// so the firing instance sees the run is followed. Never inserts a row,
162    /// so the slot lease stays the firing scheduler's.
163    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        // Any open run, a catch-up `latest` pending fire included: the
169        // receiver sees it before the sender marks it running.
170        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        // This instance's Jobs tab sees the run start; its close publishes
199        // again (`turn_finished`, also behind `check_remote`).
200        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    /// Judge the watched cross-channel run `run_id` at `now` and write a
206    /// close it calls for. `true` when it needs no more watching.
207    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                // The receiver closed it: this instance, which has the job,
212                // looks at it too (its incident, §3.4).
213                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    /// How to ask another channel's instance to stop a run it follows.
227    pub fn install_remote_stop(&self, hook: RemoteStopHook) {
228        let _ = self.remote_stop.set(hook);
229    }
230
231    /// Ask the instance that follows `run` to stop it with `infra_status`,
232    /// `why` and `summary`: a timeout, or `cancel_other`. Notes the ask in
233    /// the run's links and leaves the row open, for the follower to close
234    /// (see the module doc). `true` when an ask went out now; `false` when
235    /// nobody follows it, there is no way to ask, or an ask is already under
236    /// way (or all of them were used).
237    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, &note) {
254            // Without the note the ask would repeat at every pass.
255            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    /// The follower stopped the run: its row is closed. This instance's
271    /// Jobs tab and a run waiting on this one's place move on.
272    pub fn remote_stop_done(&self, run_id: &str) {
273        self.run_changed(run_id);
274        super::pending_wake().notify_one();
275    }
276
277    /// The ask couldn't be delivered: say why in the run's links, where the
278    /// operator and the next pass see it. The row stays open.
279    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, &note) {
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    /// The following side of [`Self::request_remote_stop`]: close the run
289    /// this instance follows, as a local stop does, and interrupt its pane's
290    /// turn, when `from_channel` fired the run and asked, in the run's row,
291    /// for this stop. The status, reason and summary are the row's, not the
292    /// request's. `Ok(false)` when it had ended already; an error when the run
293    /// is not one this process follows in `block_id`, was fired by another
294    /// channel than `from_channel`, or carries no stop of that channel's.
295    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;