Skip to main content

agentmux_srv_core/backend/storage/
job_cloud.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Cloud job runs in the run ledger (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §4.1).
5//!
6//! A cloud job reports a run with up to three events: `started`, `heartbeat`, `finished`. Each is one write here,
7//! in one transaction, so two instances reading the same event off MuxBus (one ledger, many channels) cannot both
8//! write it. A real cloud run's row has no `scheduled_for_ms` (its slot is in `links`): that column is the unique
9//! slot lease, and the watchdog's `missed` row for a slot holds it. An event for a slot the watchdog already gave up
10//! on takes that row over, so the run reads "late" instead of appearing twice.
11
12use rusqlite::{params, OptionalExtension};
13
14use super::job_runs::{reason, row_to_run, state, JobRun, COLS};
15use super::store::Store;
16use super::StoreError;
17
18/// Event ids seen, so an event pulled twice (by two channels, or sent twice) is written once. An event older than
19/// [`KEEP_EVENT_IDS_MS`] is refused on its age, so its id is not needed any more.
20pub(crate) const SCHEMA: &str = "
21    CREATE TABLE IF NOT EXISTS db_job_events (
22        job_id    TEXT NOT NULL,
23        run_id    TEXT NOT NULL,
24        event_id  TEXT NOT NULL,
25        seen_ms   INTEGER NOT NULL,
26        PRIMARY KEY (job_id, run_id, event_id)
27    );
28    CREATE INDEX IF NOT EXISTS idx_ids_job_events_seen ON db_job_events(seen_ms);";
29
30/// Longer than the 7 days an event may be old (§4.2).
31const KEEP_EVENT_IDS_MS: i64 = 8 * 24 * 3600 * 1000;
32
33/// The event being written: its id is remembered in the same transaction as its effect, so an event that failed to
34/// write is not taken for one already seen when it is sent again.
35#[derive(Debug, Clone, Copy)]
36pub struct EventMark<'a> {
37    pub run_id: &'a str,
38    pub event_id: &'a str,
39    pub now_ms: i64,
40}
41
42/// What a `started` event did.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum CloudStart {
45    /// A new `running` row.
46    Opened,
47    /// The watchdog's `missed` row for its slot became this run, `running`.
48    TookOverMissed,
49    /// The run is already in the ledger (a `finished` event came first, or a repeat): nothing changed.
50    Known,
51}
52
53/// What a `finished` event did.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum CloudFinish {
56    /// A `running` row closed.
57    Closed,
58    /// No `started` event had arrived: a closed row of its own.
59    Created,
60    /// The row was `missed` or `lost`: it closed and reads "late".
61    Late,
62    /// The run had finished already: nothing changed.
63    Known,
64}
65
66/// The ledger id of a cloud run: the same for all of its events.
67pub fn cloud_run_id(job_id: &str, run_id: &str) -> String {
68    format!("cloud:{job_id}:{run_id}")
69}
70
71fn get(conn: &rusqlite::Connection, id: &str) -> Result<Option<JobRun>, StoreError> {
72    Ok(conn.query_row(&format!("SELECT {COLS} FROM db_job_runs WHERE id = ?1"), params![id], row_to_run).optional()?)
73}
74
75/// The watchdog's `missed`/`lost` row for the slot `run` reports on, if there is one. A run that names its slot is
76/// matched by it. One that names none is matched by when it ran: the watchdog's row keeps the window of start times
77/// that were the slot's (`links.window_from`, `links.window_until`), and the run's start falls in it.
78fn given_up_for(conn: &rusqlite::Connection, run: &JobRun, slot: Option<i64>) -> Result<Option<JobRun>, StoreError> {
79    if let Some(slot) = slot {
80        return Ok(conn
81            .query_row(
82                &format!("SELECT {COLS} FROM db_job_runs WHERE job_id = ?1 AND scheduled_for_ms = ?2 AND state IN ('missed','lost')"),
83                params![run.job_id, slot],
84                row_to_run,
85            )
86            .optional()?);
87    }
88    // By its start only, as `slot_covered` does: a run that ended in another slot's window did not run for it.
89    Ok(conn
90        .query_row(
91            &format!(
92                "SELECT {COLS} FROM db_job_runs
93                  WHERE job_id = ?1 AND job_source = 'cloud' AND state = 'missed' AND json_valid(links)
94                    AND json_extract(links, '$.window_from') <= ?2 AND ?2 < json_extract(links, '$.window_until')
95                  ORDER BY scheduled_for_ms LIMIT 1"
96            ),
97            params![run.job_id, run.started_at_ms],
98            row_to_run,
99        )
100        .optional()?)
101}
102
103/// The watchdog's `missed` or `lost` row `id` is being replaced by the run itself: the failure it was counted as into an
104/// incident is withdrawn, so the run is judged on its own and a success that ended before the miss was written can
105/// recover the incident (a failure counted after a success keeps an incident open).
106fn withdraw_failure(tx: &rusqlite::Connection, id: &str) -> Result<(), StoreError> {
107    let incident: Option<String> =
108        tx.query_row("SELECT incident_id FROM db_job_incident_runs WHERE run_id = ?1", params![id], |r| r.get(0)).optional()?;
109    if let Some(incident) = incident {
110        tx.execute("DELETE FROM db_job_incident_runs WHERE run_id = ?1", params![id])?;
111        // The run is judged again as itself: if it failed, it is counted again, once.
112        tx.execute("UPDATE db_job_incidents SET failures = MAX(failures - 1, 0) WHERE id = ?1", params![incident])?;
113    }
114    Ok(())
115}
116
117fn merge_links(old: &serde_json::Value, new: &serde_json::Value) -> serde_json::Value {
118    let mut merged = if old.is_object() { old.clone() } else { serde_json::json!({}) };
119    if let (Some(m), Some(n)) = (merged.as_object_mut(), new.as_object()) {
120        for (k, v) in n {
121            m.insert(k.clone(), v.clone());
122        }
123    }
124    merged
125}
126
127/// Remember the event in `tx`. `true` for the first time, `false` for a repeat. Ids past their keeping time are
128/// dropped on the way.
129fn record_event(tx: &rusqlite::Connection, mark: &EventMark, job_id: &str) -> Result<bool, StoreError> {
130    tx.execute("DELETE FROM db_job_events WHERE seen_ms < ?1", params![mark.now_ms - KEEP_EVENT_IDS_MS])?;
131    let n = tx.execute(
132        "INSERT OR IGNORE INTO db_job_events (job_id, run_id, event_id, seen_ms) VALUES (?1, ?2, ?3, ?4)",
133        params![job_id, mark.run_id, mark.event_id, mark.now_ms],
134    )?;
135    Ok(n > 0)
136}
137
138/// Whether the ledger has a run of cloud job `job_id` for the slot at `slot_ms`: one that names the slot, or, for a run
139/// that names no slot, one that started in `[from_ms, until_ms)`.
140fn slot_covered(conn: &rusqlite::Connection, job_id: &str, slot_ms: i64, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
141    Ok(conn
142        .query_row(
143            "SELECT 1 FROM db_job_runs
144              WHERE job_id = ?1 AND job_source = 'cloud'
145                AND (scheduled_for_ms = ?2
146                     OR (json_valid(links) AND json_extract(links, '$.scheduled_for_ms') = ?2)
147                     OR (started_at_ms >= ?3 AND started_at_ms < ?4
148                         AND scheduled_for_ms IS NULL
149                         AND NOT (json_valid(links) AND json_extract(links, '$.scheduled_for_ms') IS NOT NULL)))
150              LIMIT 1",
151            params![job_id, slot_ms, from_ms, until_ms],
152            |_| Ok(()),
153        )
154        .optional()?
155        .is_some())
156}
157
158impl Store {
159    /// [`slot_covered`] for the watchdog's reading pass.
160    pub fn job_cloud_slot_covered(&self, job_id: &str, slot_ms: i64, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
161        slot_covered(&self.conn().lock().unwrap(), job_id, slot_ms, from_ms, until_ms)
162    }
163
164    /// The watchdog gives up on a slot: `missed` is its row, written only if the slot still has no run, which is
165    /// looked at again here in the same transaction the events are written in, so a report that arrived since the
166    /// watchdog read the ledger is not made into a miss as well. `false` when the slot has a run or a miss already.
167    pub fn job_cloud_give_up_slot(&self, missed: &JobRun, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
168        let mut conn = self.conn().lock().unwrap();
169        let tx = conn.transaction()?;
170        let Some(slot) = missed.scheduled_for_ms else {
171            return Ok(false);
172        };
173        if slot_covered(&tx, &missed.job_id, slot, from_ms, until_ms)? {
174            return Ok(false);
175        }
176        insert(&tx, missed)?;
177        tx.commit()?;
178        Ok(true)
179    }
180
181    /// Every cloud run that has started and not finished.
182    pub fn job_cloud_running(&self) -> Result<Vec<JobRun>, StoreError> {
183        let conn = self.conn().lock().unwrap();
184        let mut stmt = conn.prepare(&format!("SELECT {COLS} FROM db_job_runs WHERE job_source = 'cloud' AND state = 'running'"))?;
185        let rows = stmt.query_map([], row_to_run)?;
186        Ok(rows.collect::<Result<Vec<_>, _>>()?)
187    }
188
189    /// The watchdog gives up on a running cloud run `id`: it becomes `lost` if it is still running and has not been
190    /// heard from (its start, or its latest heartbeat) within `max_run_ms` of `now_ms`. Checked in the update itself,
191    /// so a heartbeat or a finish that arrived since the watchdog read the run keeps it alive. `false` then.
192    pub fn job_cloud_lose(&self, id: &str, now_ms: i64, max_run_ms: i64) -> Result<bool, StoreError> {
193        let conn = self.conn().lock().unwrap();
194        let n = conn.execute(
195            "UPDATE db_job_runs SET state = 'lost', reason = ?2, ended_at_ms = ?3
196              WHERE id = ?1 AND state = 'running'
197                AND MAX(started_at_ms, CASE WHEN json_valid(links) THEN COALESCE(json_extract(links, '$.heartbeat_ms'), 0) ELSE 0 END) + ?4 < ?3",
198            params![id, reason::NO_REPORT, now_ms, max_run_ms],
199        )?;
200        Ok(n > 0)
201    }
202
203    /// A cloud run's `started` event: `run` is its `running` row, whose `links.scheduled_for_ms` names the slot.
204    /// `None` for an event seen before.
205    pub fn job_cloud_start(&self, run: &JobRun, slot: Option<i64>, mark: &EventMark) -> Result<Option<CloudStart>, StoreError> {
206        let mut conn = self.conn().lock().unwrap();
207        let tx = conn.transaction()?;
208        if !record_event(&tx, mark, &run.job_id)? {
209            return Ok(None);
210        }
211        if get(&tx, &run.id)?.is_some() {
212            tx.commit()?;
213            return Ok(Some(CloudStart::Known));
214        }
215        let result = if let Some(given_up) = given_up_for(&tx, run, slot)? {
216            tx.execute(
217                "UPDATE db_job_runs SET id = ?2, state = 'running', reason = ?3, infra = '', ended_at_ms = NULL, started_at_ms = ?4,
218                        trigger_kind = ?5, attempt = ?6, links = ?7, reporter = ?8, recorded_by = ?9
219                  WHERE id = ?1",
220                params![
221                    given_up.id,
222                    run.id,
223                    reason::LATE,
224                    run.started_at_ms,
225                    run.trigger,
226                    run.attempt,
227                    merge_links(&given_up.links, &run.links).to_string(),
228                    run.reporter,
229                    run.recorded_by
230                ],
231            )?;
232            withdraw_failure(&tx, &given_up.id)?;
233            CloudStart::TookOverMissed
234        } else {
235            insert(&tx, run)?;
236            CloudStart::Opened
237        };
238        tx.commit()?;
239        Ok(Some(result))
240    }
241
242    /// A `heartbeat`: the run is alive at `at_ms`, which pushes its lost deadline back (§4.4). `Some(false)` for a
243    /// run that isn't `running`, `None` for an event seen before.
244    pub fn job_cloud_heartbeat(&self, job_id: &str, id: &str, at_ms: i64, mark: &EventMark) -> Result<Option<bool>, StoreError> {
245        let mut conn = self.conn().lock().unwrap();
246        let tx = conn.transaction()?;
247        if !record_event(&tx, mark, job_id)? {
248            return Ok(None);
249        }
250        let n = tx.execute(
251            "UPDATE db_job_runs SET links = json_set(CASE WHEN json_valid(links) THEN links ELSE '{}' END, '$.heartbeat_ms', MAX(?2, COALESCE(json_extract(links, '$.heartbeat_ms'), 0)))
252              WHERE id = ?1 AND state = 'running'",
253            params![id, at_ms],
254        )?;
255        tx.commit()?;
256        Ok(Some(n > 0))
257    }
258
259    /// A cloud run's `finished` event: `run` is its closed row (`finished`, with infra, outcome, summary, cost,
260    /// `links`). `None` for an event seen before.
261    pub fn job_cloud_finish(&self, run: &JobRun, slot: Option<i64>, mark: &EventMark) -> Result<Option<CloudFinish>, StoreError> {
262        let mut conn = self.conn().lock().unwrap();
263        let tx = conn.transaction()?;
264        if !record_event(&tx, mark, &run.job_id)? {
265            return Ok(None);
266        }
267        let existing = match get(&tx, &run.id)? {
268            Some(row) => Some(row),
269            None => given_up_for(&tx, run, slot)?,
270        };
271        let result = match existing {
272            None => {
273                insert(&tx, run)?;
274                CloudFinish::Created
275            }
276            Some(row) if row.state == state::FINISHED => {
277                tx.commit()?;
278                return Ok(Some(CloudFinish::Known));
279            }
280            Some(row) => {
281                let late = matches!(row.state.as_str(), state::MISSED | state::LOST);
282                // A running row keeps the start it was given; a given-up row takes the run's own.
283                let started = if late { run.started_at_ms } else { row.started_at_ms };
284                tx.execute(
285                    "UPDATE db_job_runs SET id = ?2, state = 'finished', reason = ?3, infra = ?4, outcome = ?5, summary = ?6,
286                            started_at_ms = ?7, ended_at_ms = ?8, cost_usd = ?9, cost_known = ?10, output_tokens = ?11,
287                            links = ?12, reporter = ?13, recorded_by = ?14, trigger_kind = ?15, attempt = ?16
288                      WHERE id = ?1",
289                    params![
290                        row.id,
291                        run.id,
292                        if late || row.reason == reason::LATE { reason::LATE } else { "" },
293                        run.infra,
294                        run.outcome,
295                        run.summary,
296                        started,
297                        run.ended_at_ms,
298                        run.cost_usd,
299                        run.cost_known as i64,
300                        run.output_tokens,
301                        merge_links(&row.links, &run.links).to_string(),
302                        run.reporter,
303                        run.recorded_by,
304                        run.trigger,
305                        run.attempt
306                    ],
307                )?;
308                if late {
309                    withdraw_failure(&tx, &row.id)?;
310                }
311                if late || row.reason == reason::LATE {
312                    // The incident keeper may have judged this slot as a miss: have it judge the run again. The run
313                    // can have ended before the miss was written (an event the relay held), so the cursor goes back
314                    // to before the earlier of the two.
315                    if let Some(ended) = [row.ended_at_ms, run.ended_at_ms].into_iter().flatten().min() {
316                        tx.execute(
317                            "UPDATE db_job_incident_cursors SET ended_at_ms = ?2 - 1, run_id = '' WHERE job_id = ?1 AND ended_at_ms >= ?2",
318                            params![row.job_id, ended],
319                        )?;
320                    }
321                }
322                if late {
323                    CloudFinish::Late
324                } else {
325                    CloudFinish::Closed
326                }
327            }
328        };
329        tx.commit()?;
330        Ok(Some(result))
331    }
332}
333
334fn insert(conn: &rusqlite::Connection, run: &JobRun) -> Result<(), StoreError> {
335    conn.execute(
336        &format!(
337            "INSERT OR IGNORE INTO db_job_runs ({COLS}) VALUES \
338             (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28,?29,?30,?31,?32)"
339        ),
340        params![
341            run.id,
342            run.job_id,
343            run.job_source,
344            run.job_name,
345            run.template_id,
346            run.template_version,
347            run.trigger,
348            run.scheduled_for_ms,
349            run.triggered_by,
350            run.attempt,
351            run.state,
352            run.reason,
353            run.infra,
354            run.outcome,
355            run.summary,
356            run.target_agent_uid,
357            run.block_id,
358            run.turn_id,
359            run.account_id,
360            run.provider,
361            run.started_at_ms,
362            run.ended_at_ms,
363            run.cost_usd,
364            run.cost_known as i64,
365            run.cost_partial as i64,
366            run.output_tokens,
367            run.steps,
368            run.links.to_string(),
369            run.skip_count,
370            run.last_skip_at_ms,
371            run.reporter,
372            run.recorded_by,
373        ],
374    )?;
375    Ok(())
376}