agentmux_srv_core/backend/jobs/
follower.rs1use std::collections::HashMap;
14use std::sync::{Arc, Weak};
15use std::time::Duration;
16
17use agentmux_common::time::now_ms;
18
19use super::{caps, RunLedger};
20use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_TURN};
21use crate::backend::storage::job_runs::{infra, RunCost};
22
23pub const NO_TURN_AFTER_MS: i64 = 15 * 60 * 1000;
27const SWEEP_EVERY: Duration = Duration::from_secs(60);
28
29#[derive(Debug, Clone, PartialEq)]
31pub struct TurnSeen {
32 pub block_id: String,
33 pub turn_id: i64,
34 pub started_at_ms: i64,
35 pub ended_at_ms: Option<i64>,
36 pub end: Option<String>,
38 pub cost_usd: f64,
39 pub output_tokens: i64,
40 pub steps: i64,
41}
42
43impl TurnSeen {
44 pub fn parse(data: &serde_json::Value) -> Option<Self> {
45 let i64_at = |k: &str| data.get(k).and_then(|v| v.as_i64());
46 Some(TurnSeen {
47 block_id: data.get("block_id")?.as_str()?.to_string(),
48 turn_id: i64_at("turn_id")?,
49 started_at_ms: i64_at("started_at_ms").unwrap_or(0),
50 ended_at_ms: i64_at("ended_at_ms"),
51 end: data.get("end").and_then(|v| v.as_str()).map(str::to_string),
52 cost_usd: data.get("cost_usd").and_then(|v| v.as_f64()).unwrap_or(0.0),
53 output_tokens: i64_at("output_tokens").unwrap_or(0),
54 steps: i64_at("steps").unwrap_or(0),
55 })
56 }
57
58 pub fn cost(&self) -> RunCost {
61 RunCost {
62 cost_usd: self.cost_usd,
63 cost_known: self.cost_usd > 0.0,
64 output_tokens: self.output_tokens,
65 steps: self.steps,
66 }
67 }
68}
69
70#[derive(Debug, Clone, PartialEq)]
72pub struct Armed {
73 pub run_id: String,
74 pub armed_at_ms: i64,
76 pub turn_id: Option<i64>,
77 pub last: Option<TurnSeen>,
78 pub cap_usd: Option<f64>,
81 pub partial: bool,
84}
85
86#[derive(Debug, Clone, PartialEq)]
88pub enum Effect {
89 Bind { turn_id: i64, partial: bool },
90 Finish { infra: &'static str, cost: Option<RunCost>, summary: &'static str },
91 OverBudget { cost: RunCost, cap: f64 },
93}
94
95pub fn on_turn(a: &mut Armed, t: &TurnSeen) -> Vec<Effect> {
97 let mut out = Vec::new();
98 match a.turn_id {
99 None => {
100 if t.ended_at_ms.is_some_and(|e| e < a.armed_at_ms) {
101 return out;
102 }
103 a.turn_id = Some(t.turn_id);
104 a.partial = t.started_at_ms < a.armed_at_ms;
105 out.push(Effect::Bind { turn_id: t.turn_id, partial: a.partial });
106 }
107 Some(bound) if t.turn_id < bound => return out,
109 Some(bound) if t.turn_id > bound => {
112 out.push(Effect::Finish {
113 infra: infra::OK,
114 cost: a.last.as_ref().map(TurnSeen::cost),
115 summary: "",
116 });
117 return out;
118 }
119 Some(_) => {}
120 }
121 a.last = Some(t.clone());
122 if let Some(cap) = a.cap_usd.filter(|cap| !a.partial && t.end.is_none() && caps::reached(t.cost_usd, *cap)) {
123 out.push(Effect::OverBudget { cost: t.cost(), cap });
124 return out;
125 }
126 if let Some(end) = t.end.as_deref() {
127 let status = if end == "exited" { infra::INTERRUPTED } else { infra::OK };
128 out.push(Effect::Finish { infra: status, cost: Some(t.cost()), summary: "" });
129 }
130 out
131}
132
133enum Msg {
134 Arm { block_id: String, run_id: String, armed_at_ms: i64, cap_usd: Option<f64> },
135 Watch { run_id: String, armed_at_ms: i64 },
138 Turn(TurnSeen),
139 Sweep,
140}
141
142pub struct Follower {
144 tx: tokio::sync::mpsc::UnboundedSender<Msg>,
145}
146
147impl Follower {
148 pub(super) fn start(ledger: Weak<RunLedger>, broker: Arc<Broker>) -> Self {
151 let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Msg>();
152 let Ok(handle) = tokio::runtime::Handle::try_current() else {
153 return Follower { tx };
154 };
155 let observer_tx = tx.clone();
156 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
157 if ev.event != EVENT_AGENT_TURN {
158 return;
159 }
160 if let Some(t) = ev.data.as_ref().and_then(TurnSeen::parse) {
161 let _ = observer_tx.send(Msg::Turn(t));
162 }
163 }));
164 let sweep_tx = tx.clone();
165 handle.spawn(async move {
166 loop {
167 tokio::time::sleep(SWEEP_EVERY).await;
168 if sweep_tx.send(Msg::Sweep).is_err() {
169 break;
170 }
171 }
172 });
173 handle.spawn(run(ledger, broker, rx));
174 Follower { tx }
175 }
176
177 pub(super) fn arm(&self, block_id: &str, run_id: &str, armed_at_ms: i64, cap_usd: Option<f64>) {
178 let _ = self.tx.send(Msg::Arm { block_id: block_id.to_string(), run_id: run_id.to_string(), armed_at_ms, cap_usd });
179 }
180
181 pub(super) fn watch(&self, run_id: &str, armed_at_ms: i64) {
182 let _ = self.tx.send(Msg::Watch { run_id: run_id.to_string(), armed_at_ms });
183 }
184}
185
186async fn run(ledger: Weak<RunLedger>, broker: Arc<Broker>, mut rx: tokio::sync::mpsc::UnboundedReceiver<Msg>) {
187 let mut armed: HashMap<String, Vec<Armed>> = HashMap::new();
188 let mut watched: HashMap<String, i64> = HashMap::new();
189 while let Some(msg) = rx.recv().await {
190 let Some(ledger) = ledger.upgrade() else { break };
191 match msg {
192 Msg::Watch { run_id, armed_at_ms } => {
193 watched.insert(run_id, armed_at_ms);
194 }
195 Msg::Arm { block_id, run_id, armed_at_ms, cap_usd } => {
196 armed.entry(block_id.clone()).or_default().push(Armed { run_id, armed_at_ms, turn_id: None, last: None, cap_usd, partial: false });
197 let latest = broker
198 .read_event_history(EVENT_AGENT_TURN, &format!("block:{block_id}"), 1)
199 .pop()
200 .and_then(|e| e.data)
201 .and_then(|d| TurnSeen::parse(&d));
202 if let Some(t) = latest {
203 apply(&ledger, &mut armed, &t).await;
204 }
205 }
206 Msg::Turn(t) => apply(&ledger, &mut armed, &t).await,
207 Msg::Sweep => {
208 let now = now_ms();
209 let mut stale = Vec::new();
210 for runs in armed.values_mut() {
211 runs.retain(|a| {
212 let lapsed = a.turn_id.is_none() && now - a.armed_at_ms > NO_TURN_AFTER_MS;
213 if lapsed {
214 stale.push(a.run_id.clone());
215 }
216 !lapsed
217 });
218 }
219 armed.retain(|_, runs| !runs.is_empty());
220 for run_id in stale {
221 let ledger = ledger.clone();
222 let _ = tokio::task::spawn_blocking(move || {
223 ledger.turn_finished(&run_id, infra::OK, None, "AgentMux saw no turn for this run")
224 })
225 .await;
226 }
227 if !watched.is_empty() {
228 let (l, list) = (ledger.clone(), watched.clone());
229 let done = tokio::task::spawn_blocking(move || {
230 list.into_iter().filter(|(id, at)| l.check_remote(id, *at, now)).map(|(id, _)| id).collect::<Vec<_>>()
231 })
232 .await
233 .unwrap_or_default();
234 for id in done {
235 watched.remove(&id);
236 }
237 }
238 }
239 }
240 }
241}
242
243async fn apply(ledger: &Arc<RunLedger>, armed: &mut HashMap<String, Vec<Armed>>, t: &TurnSeen) {
245 let Some(runs) = armed.get_mut(&t.block_id) else { return };
246 let mut writes = Vec::new();
247 runs.retain_mut(|a| {
248 let effects = on_turn(a, t);
249 let done = effects.iter().any(|e| matches!(e, Effect::Finish { .. } | Effect::OverBudget { .. }));
250 writes.push((a.run_id.clone(), effects));
251 !done
252 });
253 if runs.is_empty() {
254 armed.remove(&t.block_id);
255 }
256 let ledger = ledger.clone();
257 let _ = tokio::task::spawn_blocking(move || {
258 for (run_id, effects) in writes {
259 for e in effects {
260 match e {
261 Effect::Bind { turn_id, partial } => ledger.turn_bound(&run_id, turn_id, partial),
262 Effect::Finish { infra, cost, summary } => ledger.turn_finished(&run_id, infra, cost, summary),
263 Effect::OverBudget { cost, cap } => ledger.over_budget(&run_id, cost, cap),
264 }
265 }
266 }
267 })
268 .await;
269}