Skip to main content

agentmux_srv_core/backend/storage/
job_runs.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The run ledger: one row per time a job was meant to run, including the
5//! times it didn't (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3.1).
6//!
7//! It lives in the always-global identity store, beside the work queue, so
8//! every channel and version on this computer sees one ledger. The unique
9//! index on `(job_id, scheduled_for_ms)` is the slot lease: a scheduler
10//! inserts its slot's row before it fires, and a second scheduler sharing the
11//! job finds the slot taken and doesn't fire.
12//!
13//! Nothing here deletes a run: history is kept forever (§3.1, "Retention:
14//! none"). A skip folded into the previous row of the same job and reason
15//! keeps its own row, marked `collapsed_into` that row and left out of
16//! history, so its slot stays leased.
17
18use rusqlite::{params, OptionalExtension, Row};
19use serde::{Deserialize, Serialize};
20
21use super::store::Store;
22use super::StoreError;
23
24/// The table, created on every open of the identity store, with no schema
25/// version bump (see `work_claims::SCHEMA`).
26pub(crate) const SCHEMA: &str = "
27    CREATE TABLE IF NOT EXISTS db_job_runs (
28        id               TEXT PRIMARY KEY,
29        job_id           TEXT NOT NULL,
30        job_source       TEXT NOT NULL,
31        job_name         TEXT NOT NULL DEFAULT '',
32        template_id      TEXT NOT NULL DEFAULT '',
33        template_version TEXT NOT NULL DEFAULT '',
34        trigger_kind     TEXT NOT NULL,
35        scheduled_for_ms INTEGER,
36        triggered_by     TEXT NOT NULL DEFAULT '',
37        attempt          INTEGER NOT NULL DEFAULT 1,
38        state            TEXT NOT NULL,
39        reason           TEXT NOT NULL DEFAULT '',
40        infra            TEXT NOT NULL DEFAULT '',
41        outcome          TEXT NOT NULL DEFAULT 'unknown',
42        summary          TEXT NOT NULL DEFAULT '',
43        target_agent_uid TEXT NOT NULL DEFAULT '',
44        block_id         TEXT NOT NULL DEFAULT '',
45        turn_id          INTEGER,
46        account_id       TEXT NOT NULL DEFAULT '',
47        provider         TEXT NOT NULL DEFAULT '',
48        started_at_ms    INTEGER NOT NULL,
49        ended_at_ms      INTEGER,
50        cost_usd         REAL NOT NULL DEFAULT 0,
51        cost_known       INTEGER NOT NULL DEFAULT 0,
52        cost_partial     INTEGER NOT NULL DEFAULT 0,
53        output_tokens    INTEGER NOT NULL DEFAULT 0,
54        steps            INTEGER NOT NULL DEFAULT 0,
55        links            TEXT NOT NULL DEFAULT '{}',
56        skip_count       INTEGER NOT NULL DEFAULT 0,
57        last_skip_at_ms  INTEGER,
58        reporter         TEXT NOT NULL DEFAULT '',
59        recorded_by      TEXT NOT NULL DEFAULT '',
60        collapsed_into   TEXT NOT NULL DEFAULT ''
61    );
62    CREATE INDEX IF NOT EXISTS idx_ids_job_runs_job_started ON db_job_runs(job_id, started_at_ms);
63    CREATE UNIQUE INDEX IF NOT EXISTS idx_ids_job_runs_slot ON db_job_runs(job_id, scheduled_for_ms)
64        WHERE scheduled_for_ms IS NOT NULL;
65    CREATE INDEX IF NOT EXISTS idx_ids_job_runs_state ON db_job_runs(state);
66    CREATE INDEX IF NOT EXISTS idx_ids_job_runs_account_started ON db_job_runs(account_id, started_at_ms);
67    CREATE TABLE IF NOT EXISTS db_job_flags (
68        key        TEXT PRIMARY KEY,
69        value      TEXT NOT NULL DEFAULT '',
70        set_at_ms  INTEGER NOT NULL,
71        set_by     TEXT NOT NULL DEFAULT ''
72    );";
73
74/// Columns added to `db_job_runs` after its first shape, run on every open
75/// (`apply_schema`) as `cron::JOB_TABLES` is: a table an earlier
76/// build created gains them, and a new column with a default needs no
77/// schema version bump.
78const JOB_RUNS_COLUMNS: [&str; 1] = ["ALTER TABLE db_job_runs ADD COLUMN collapsed_into TEXT NOT NULL DEFAULT ''"];
79
80/// Create the tables (the ledger's, and its incidents', `job_incidents`),
81/// then add any column the ledger lacks; "duplicate column" is the column
82/// already being there.
83pub(crate) fn apply_schema(conn: &rusqlite::Connection) -> Result<(), StoreError> {
84    conn.execute_batch(SCHEMA)?;
85    conn.execute_batch(super::job_incidents::SCHEMA)?;
86    conn.execute_batch(super::job_cloud::SCHEMA)?;
87    conn.execute_batch(super::job_events::SCHEMA)?;
88    super::migrations::apply_additive_columns(conn, super::job_events::COLUMNS)?;
89    super::migrations::apply_additive_columns(conn, JOB_RUNS_COLUMNS)
90}
91
92pub(super) const COLS: &str = "id, job_id, job_source, job_name, template_id, template_version, trigger_kind, \
93     scheduled_for_ms, triggered_by, attempt, state, reason, infra, outcome, summary, target_agent_uid, \
94     block_id, turn_id, account_id, provider, started_at_ms, ended_at_ms, cost_usd, cost_known, \
95     cost_partial, output_tokens, steps, links, skip_count, last_skip_at_ms, reporter, recorded_by";
96
97/// Run states (§3.1).
98pub mod state {
99    pub const SCHEDULED: &str = "scheduled";
100    pub const SKIPPED: &str = "skipped";
101    /// Catch-up `latest`'s one coalesced fire, waiting for its agent.
102    pub const PENDING: &str = "pending";
103    pub const RUNNING: &str = "running";
104    pub const FINISHED: &str = "finished";
105    pub const MISSED: &str = "missed";
106    /// A cloud run that reported start and then nothing within its time limit (§4.4).
107    pub const LOST: &str = "lost";
108    /// The states a run can still move on from, while `ended_at_ms` is
109    /// unset: `OPEN_NOT_ENDED`'s list, and [`super::JobRun::is_open`].
110    pub const OPEN: [&str; 3] = [SCHEDULED, PENDING, RUNNING];
111}
112
113/// Why a run was skipped, missed or stopped, or how a pending one ended
114/// (§3.1; the ones P1 writes).
115pub mod reason {
116    pub const APP_NOT_RUNNING: &str = "app_not_running";
117    /// A cloud job's expected slot and its grace passed with no event for it (§4.4).
118    pub const NO_REPORT: &str = "no_report";
119    /// A local job's slot passed while AgentMux was running and nothing started it: the job's
120    /// scheduler task is gone or stalled, and no row was written for the slot (§4.4).
121    pub const NOT_STARTED: &str = "not_started";
122    /// A cloud run's `finished` event came after the watchdog gave it up.
123    pub const LATE: &str = "late";
124    pub const TARGET_MISSING: &str = "target_missing";
125    pub const TARGET_STOPPED: &str = "target_stopped";
126    /// A newer pending fire replaced this one.
127    pub const SUPERSEDED: &str = "superseded";
128    /// The job's next fire time passed before its agent came back.
129    pub const EXPIRED: &str = "expired";
130    /// The job was paused when its slot came.
131    pub const PAUSED: &str = "paused";
132    /// Every job was paused by the operator (Pause all) when its slot came.
133    pub const PAUSED_ALL: &str = "paused_all";
134    /// The job's previous run was still running (policy `overlap`): a skipped
135    /// slot, or the one buffered run waiting for it.
136    pub const OVERLAP: &str = "overlap";
137    /// A run of the job's concurrency group is running; this one waits.
138    pub const GROUP_BUSY: &str = "group_busy";
139    /// Three unattended agent runs are running already; this one waits.
140    pub const GLOBAL_LIMIT: &str = "global_limit";
141    /// An infrastructure failure's retry, waiting out its backoff.
142    pub const RETRY_WAIT: &str = "retry_wait";
143    /// An event's run, waiting out the trigger's `delay` (`links.due_at_ms` is when it may start).
144    pub const DELAY_WAIT: &str = "delay_wait";
145    /// The run was stopped at the job's `timeout_minutes`.
146    pub const TIMEOUT: &str = "timeout";
147    /// The job's spend today, with the run's own cap, would pass its daily
148    /// cap (§5.3): the slot is skipped.
149    pub const JOB_CAP: &str = "job_cap";
150    /// The same for the account the run would use.
151    pub const ACCOUNT_CAP: &str = "account_cap";
152    /// An event job already started its `max_per_hour` runs in the last hour: the event is skipped.
153    pub const RATE: &str = "rate";
154    /// A `message` job reached its messages a day to another agent.
155    pub const MESSAGE_CAP: &str = "message_cap";
156    /// The run was stopped at its per-run cap.
157    pub const RUN_CAP: &str = "run_cap";
158    /// The skips a cap makes: the once-a-day alert and "over cap today".
159    pub const CAPS: [&str; 4] = [JOB_CAP, ACCOUNT_CAP, MESSAGE_CAP, RATE];
160    /// The reasons a `scheduled` run waits to start with.
161    pub const WAITING: [&str; 5] = [OVERLAP, GROUP_BUSY, GLOBAL_LIMIT, RETRY_WAIT, DELAY_WAIT];
162}
163
164/// Infrastructure status (§3.1; the ones P1 writes).
165pub mod infra {
166    pub const OK: &str = "ok";
167    pub const ERROR: &str = "error";
168    pub const TIMEOUT: &str = "timeout";
169    pub const INTERRUPTED: &str = "interrupted";
170    /// The run reached its per-run cap and was stopped (§5.3).
171    pub const OVER_BUDGET: &str = "over_budget";
172}
173
174/// What a run concluded, separate from whether it ran (§2).
175pub const OUTCOMES: &[&str] = &["ok", "findings", "failed", "unknown"];
176
177/// The longest `summary` kept (§3.1).
178pub const SUMMARY_MAX_CHARS: usize = 300;
179
180/// `text` cut to [`SUMMARY_MAX_CHARS`], on a character boundary.
181pub fn clip_summary(text: &str) -> String {
182    let text = text.trim();
183    if text.chars().count() <= SUMMARY_MAX_CHARS {
184        return text.to_string();
185    }
186    let mut s: String = text.chars().take(SUMMARY_MAX_CHARS - 1).collect();
187    s.push('…');
188    s
189}
190
191/// One row of `db_job_runs`. Field meanings are the spec's table (§3.1).
192#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
193#[ts(export, export_to = "../../../frontend/types/rpc/")]
194pub struct JobRun {
195    pub id: String,
196    pub job_id: String,
197    pub job_source: String,
198    pub job_name: String,
199    #[serde(default)]
200    pub template_id: String,
201    #[serde(default)]
202    pub template_version: String,
203    pub trigger: String,
204    #[ts(type = "number | null")]
205    pub scheduled_for_ms: Option<i64>,
206    pub triggered_by: String,
207    #[ts(type = "number")]
208    pub attempt: i64,
209    pub state: String,
210    pub reason: String,
211    pub infra: String,
212    pub outcome: String,
213    pub summary: String,
214    pub target_agent_uid: String,
215    pub block_id: String,
216    #[ts(type = "number | null")]
217    pub turn_id: Option<i64>,
218    pub account_id: String,
219    pub provider: String,
220    #[ts(type = "number")]
221    pub started_at_ms: i64,
222    #[ts(type = "number | null")]
223    pub ended_at_ms: Option<i64>,
224    pub cost_usd: f64,
225    pub cost_known: bool,
226    pub cost_partial: bool,
227    #[ts(type = "number")]
228    pub output_tokens: i64,
229    #[ts(type = "number")]
230    pub steps: i64,
231    /// JSON object: the transcript, a Drone run, reported links.
232    #[ts(type = "Record<string, unknown>")]
233    pub links: serde_json::Value,
234    #[ts(type = "number")]
235    pub skip_count: i64,
236    #[ts(type = "number | null")]
237    pub last_skip_at_ms: Option<i64>,
238    #[serde(default)]
239    pub reporter: String,
240    pub recorded_by: String,
241}
242
243impl JobRun {
244    /// A new row for `job_id` in `state`, started now, with every other field
245    /// empty.
246    pub fn new(id: &str, job_id: &str, job_source: &str, job_name: &str, trigger: &str, state: &str, now_ms: i64) -> Self {
247        JobRun {
248            id: id.to_string(),
249            job_id: job_id.to_string(),
250            job_source: job_source.to_string(),
251            job_name: job_name.to_string(),
252            trigger: trigger.to_string(),
253            attempt: 1,
254            state: state.to_string(),
255            outcome: "unknown".to_string(),
256            started_at_ms: now_ms,
257            links: serde_json::json!({}),
258            ..Default::default()
259        }
260    }
261
262    /// Whether the run can still move on: what `OPEN_NOT_ENDED` selects.
263    pub fn is_open(&self) -> bool {
264        self.ended_at_ms.is_none() && state::OPEN.contains(&self.state.as_str())
265    }
266}
267
268pub(super) fn row_to_run(row: &Row) -> rusqlite::Result<JobRun> {
269    let links: String = row.get("links")?;
270    Ok(JobRun {
271        id: row.get("id")?,
272        job_id: row.get("job_id")?,
273        job_source: row.get("job_source")?,
274        job_name: row.get("job_name")?,
275        template_id: row.get("template_id")?,
276        template_version: row.get("template_version")?,
277        trigger: row.get("trigger_kind")?,
278        scheduled_for_ms: row.get("scheduled_for_ms")?,
279        triggered_by: row.get("triggered_by")?,
280        attempt: row.get("attempt")?,
281        state: row.get("state")?,
282        reason: row.get("reason")?,
283        infra: row.get("infra")?,
284        outcome: row.get("outcome")?,
285        summary: row.get("summary")?,
286        target_agent_uid: row.get("target_agent_uid")?,
287        block_id: row.get("block_id")?,
288        turn_id: row.get("turn_id")?,
289        account_id: row.get("account_id")?,
290        provider: row.get("provider")?,
291        started_at_ms: row.get("started_at_ms")?,
292        ended_at_ms: row.get("ended_at_ms")?,
293        cost_usd: row.get("cost_usd")?,
294        cost_known: row.get::<_, i64>("cost_known")? != 0,
295        cost_partial: row.get::<_, i64>("cost_partial")? != 0,
296        output_tokens: row.get("output_tokens")?,
297        steps: row.get("steps")?,
298        links: serde_json::from_str(&links).unwrap_or_else(|_| serde_json::json!({})),
299        skip_count: row.get("skip_count")?,
300        last_skip_at_ms: row.get("last_skip_at_ms")?,
301        reporter: row.get("reporter")?,
302        recorded_by: row.get("recorded_by")?,
303    })
304}
305
306/// A finished turn's figures, from the turn ledger (§3.2).
307#[derive(Debug, Clone, Copy, Default, PartialEq)]
308pub struct RunCost {
309    pub cost_usd: f64,
310    pub cost_known: bool,
311    pub output_tokens: i64,
312    pub steps: i64,
313}
314
315/// States a run can still move on from. A pending run that was superseded
316/// or expired keeps its state, with `ended_at_ms` set: it is closed. The
317/// list is [`state::OPEN`] (a test holds them equal).
318const OPEN_NOT_ENDED: &str = "state IN ('scheduled','pending','running') AND ended_at_ms IS NULL";
319
320/// A decisive run: one that finished, or failed (a miss, a lost run, an
321/// expired pending fire, a failing infrastructure status or outcome). The
322/// same rule as `jobs::verdict::decisive`, whose test checks the two agree.
323const DECISIVE: &str = "((state IN ('finished','missed','lost')
324                             OR (state = 'pending' AND reason = 'expired')
325                             OR infra IN ('error','timeout','over_budget','interrupted')
326                             OR outcome = 'failed')
327                            AND NOT (json_valid(links) AND json_extract(links, '$.retried_by') IS NOT NULL))";
328
329impl Store {
330    /// Create the table if this store doesn't have it yet (a test store, or
331    /// one opened before this build). Idempotent.
332    pub fn job_runs_ensure_schema(&self) -> Result<(), StoreError> {
333        apply_schema(&self.conn().lock().unwrap())
334    }
335
336    /// Insert `run`. `Ok(false)` when its slot (`job_id`, `scheduled_for_ms`)
337    /// or its id is already taken: another scheduler has this slot.
338    pub fn job_run_insert(&self, run: &JobRun) -> Result<bool, StoreError> {
339        let conn = self.conn().lock().unwrap();
340        let n = conn.execute(
341            &format!(
342                "INSERT OR IGNORE INTO db_job_runs ({COLS}) VALUES \
343                 (?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)"
344            ),
345            params![
346                run.id,
347                run.job_id,
348                run.job_source,
349                run.job_name,
350                run.template_id,
351                run.template_version,
352                run.trigger,
353                run.scheduled_for_ms,
354                run.triggered_by,
355                run.attempt,
356                run.state,
357                run.reason,
358                run.infra,
359                run.outcome,
360                run.summary,
361                run.target_agent_uid,
362                run.block_id,
363                run.turn_id,
364                run.account_id,
365                run.provider,
366                run.started_at_ms,
367                run.ended_at_ms,
368                run.cost_usd,
369                run.cost_known as i64,
370                run.cost_partial as i64,
371                run.output_tokens,
372                run.steps,
373                run.links.to_string(),
374                run.skip_count,
375                run.last_skip_at_ms,
376                run.reporter,
377                run.recorded_by,
378            ],
379        )?;
380        Ok(n > 0)
381    }
382
383    pub fn job_run_get(&self, id: &str) -> Result<Option<JobRun>, StoreError> {
384        let conn = self.conn().lock().unwrap();
385        Ok(conn
386            .query_row(&format!("SELECT {COLS} FROM db_job_runs WHERE id = ?1"), params![id], row_to_run)
387            .optional()?)
388    }
389
390    /// A job's runs, newest first, at most `limit`, started before `before`
391    /// when given (for paging).
392    pub fn job_runs_for_job(&self, job_id: &str, limit: i64, before: Option<i64>) -> Result<Vec<JobRun>, StoreError> {
393        let conn = self.conn().lock().unwrap();
394        let mut stmt = conn.prepare(&format!(
395            "SELECT {COLS} FROM db_job_runs
396              WHERE job_id = ?1 AND collapsed_into = '' AND (?2 IS NULL OR started_at_ms < ?2)
397              ORDER BY started_at_ms DESC, rowid DESC LIMIT ?3"
398        ))?;
399        let rows = stmt.query_map(params![job_id, before, limit.max(0)], row_to_run)?;
400        Ok(rows.collect::<Result<Vec<_>, _>>()?)
401    }
402
403    /// The newest run of `job_id` that finished and did its work (outcome `ok` or `findings`), however many newer runs
404    /// did not: a listing cut to the newest few can miss it.
405    pub fn job_run_last_good(&self, job_id: &str) -> Result<Option<JobRun>, StoreError> {
406        let conn = self.conn().lock().unwrap();
407        let mut stmt = conn.prepare(&format!(
408            "SELECT {COLS} FROM db_job_runs
409              WHERE job_id = ?1 AND collapsed_into = '' AND state = 'finished' AND outcome IN ('ok', 'findings')
410              ORDER BY COALESCE(ended_at_ms, started_at_ms) DESC, rowid DESC LIMIT 1"
411        ))?;
412        let mut rows = stmt.query_map(params![job_id], row_to_run)?;
413        Ok(rows.next().transpose()?)
414    }
415
416    /// The newest run of every job the ledger has runs of, whatever its source (scheduled, Drone or cloud),
417    /// newest first, at most `limit`.
418    pub fn job_runs_latest_per_job(&self, limit: i64) -> Result<Vec<JobRun>, StoreError> {
419        let conn = self.conn().lock().unwrap();
420        let mut stmt = conn.prepare(&format!(
421            "SELECT {COLS} FROM db_job_runs r
422              WHERE collapsed_into = ''
423                AND r.rowid = (SELECT rowid FROM db_job_runs
424                                WHERE job_id = r.job_id AND collapsed_into = ''
425                                ORDER BY started_at_ms DESC, rowid DESC LIMIT 1)
426              ORDER BY started_at_ms DESC, rowid DESC LIMIT ?1"
427        ))?;
428        let rows = stmt.query_map(params![limit.max(0)], row_to_run)?;
429        Ok(rows.collect::<Result<Vec<_>, _>>()?)
430    }
431
432    /// The ids of the jobs the ledger has runs of that `text` names: by id, or by the name its runs carry.
433    pub fn job_ids_named(&self, text: &str) -> Result<Vec<String>, StoreError> {
434        let conn = self.conn().lock().unwrap();
435        let mut stmt = conn.prepare("SELECT DISTINCT job_id FROM db_job_runs WHERE job_id = ?1 OR job_name = ?1 ORDER BY job_id")?;
436        let rows = stmt.query_map(params![text], |r| r.get::<_, String>(0))?;
437        Ok(rows.collect::<Result<Vec<_>, _>>()?)
438    }
439
440    /// Whether the ledger has a row for the job's `slot_ms`, whatever its state: a run, a skip or a miss. Every
441    /// way a scheduled slot is handled writes one (the slot's unique index, §3.1), so a slot without a row was
442    /// never handled.
443    pub fn job_run_slot_taken(&self, job_id: &str, slot_ms: i64) -> Result<bool, StoreError> {
444        let conn = self.conn().lock().unwrap();
445        let n: i64 = conn.query_row(
446            "SELECT COUNT(*) FROM db_job_runs WHERE job_id = ?1 AND scheduled_for_ms = ?2",
447            params![job_id, slot_ms],
448            |r| r.get(0),
449        )?;
450        Ok(n > 0)
451    }
452
453    /// The job's newest run, if any.
454    pub fn job_run_last(&self, job_id: &str) -> Result<Option<JobRun>, StoreError> {
455        Ok(self.job_runs_for_job(job_id, 1, None)?.pop())
456    }
457
458    /// The job's newest decisive run: one that finished, or failed (a miss,
459    /// a lost run, an expired pending fire, a failing infrastructure status
460    /// or outcome). Skips, and runs still scheduled, pending or running, are
461    /// passed over however many there are. The same rule as
462    /// `jobs::verdict::decisive`, whose test checks the two agree.
463    pub fn job_run_last_decisive(&self, job_id: &str) -> Result<Option<JobRun>, StoreError> {
464        let conn = self.conn().lock().unwrap();
465        Ok(conn
466            .query_row(
467                &format!(
468                    "SELECT {COLS} FROM db_job_runs
469                      WHERE job_id = ?1 AND collapsed_into = '' AND {DECISIVE}
470                      ORDER BY started_at_ms DESC, rowid DESC LIMIT 1"
471                ),
472                params![job_id],
473                row_to_run,
474            )
475            .optional()?)
476    }
477
478    /// The job's decisive runs that have ended, in the order they ended
479    /// (`ended_at_ms`, then `id`): the ones after `after` (an ended time and
480    /// a run id), at most `limit`; with no `after`, only the newest. What
481    /// the incident keeper walks (`jobs::incidents`).
482    pub fn job_runs_decisive_after(
483        &self,
484        job_id: &str,
485        after: Option<(i64, &str)>,
486        limit: i64,
487    ) -> Result<Vec<JobRun>, StoreError> {
488        let conn = self.conn().lock().unwrap();
489        let base = format!(
490            "SELECT {COLS} FROM db_job_runs
491              WHERE job_id = ?1 AND collapsed_into = '' AND ended_at_ms IS NOT NULL AND {DECISIVE}"
492        );
493        let rows = match after {
494            Some((ended, id)) => {
495                let mut stmt = conn.prepare(&format!(
496                    "{base} AND (ended_at_ms > ?2 OR (ended_at_ms = ?2 AND id > ?3)) ORDER BY ended_at_ms, id LIMIT ?4"
497                ))?;
498                let rows = stmt.query_map(params![job_id, ended, id, limit.max(0)], row_to_run)?;
499                rows.collect::<Result<Vec<_>, _>>()?
500            }
501            None => {
502                let mut stmt = conn.prepare(&format!("{base} ORDER BY ended_at_ms DESC, id DESC LIMIT 1"))?;
503                let rows = stmt.query_map(params![job_id], row_to_run)?;
504                rows.collect::<Result<Vec<_>, _>>()?
505            }
506        };
507        Ok(rows)
508    }
509
510    /// Turn the just-inserted placeholder `id` into a skip for `reason`, or,
511    /// when the job's previous row is a skip for the same reason, fold it
512    /// into that row (`skip_count` + `count`), so consecutive skips show as
513    /// one row (§3.1). A folded placeholder stays, marked `collapsed_into`
514    /// and hidden from history, so the unique index keeps its slot taken: a
515    /// second scheduler accounting for the same slot finds it leased and
516    /// doesn't count it again. Returns the id of the row that shows the skip.
517    pub fn job_run_skip(&self, id: &str, reason: &str, count: i64, now_ms: i64) -> Result<String, StoreError> {
518        let mut conn = self.conn().lock().unwrap();
519        let tx = conn.transaction()?;
520        let job_id: Option<String> =
521            tx.query_row("SELECT job_id FROM db_job_runs WHERE id = ?1", params![id], |r| r.get(0)).optional()?;
522        let Some(job_id) = job_id else {
523            return Ok(id.to_string());
524        };
525        let previous: Option<(String, String, String)> = tx
526            .query_row(
527                "SELECT id, state, reason FROM db_job_runs
528                  WHERE job_id = ?1 AND id <> ?2 AND collapsed_into = ''
529                  ORDER BY started_at_ms DESC, rowid DESC LIMIT 1",
530                params![job_id, id],
531                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
532            )
533            .optional()?;
534        let held_by = match previous {
535            Some((prev, st, why)) if st == state::SKIPPED && why == reason => {
536                tx.execute(
537                    "UPDATE db_job_runs SET skip_count = skip_count + ?2, last_skip_at_ms = ?3 WHERE id = ?1",
538                    params![prev, count, now_ms],
539                )?;
540                tx.execute(
541                    "UPDATE db_job_runs SET state = ?2, reason = ?3, collapsed_into = ?4, ended_at_ms = ?5 WHERE id = ?1",
542                    params![id, state::SKIPPED, reason, prev, now_ms],
543                )?;
544                prev
545            }
546            _ => {
547                tx.execute(
548                    "UPDATE db_job_runs SET state = ?2, reason = ?3, skip_count = ?4, last_skip_at_ms = ?5,
549                            ended_at_ms = ?5
550                      WHERE id = ?1",
551                    params![id, state::SKIPPED, reason, count, now_ms],
552                )?;
553                id.to_string()
554            }
555        };
556        tx.commit()?;
557        Ok(held_by)
558    }
559
560    /// A delivered run is being worked on: who has it, from when.
561    pub fn job_run_mark_running(
562        &self,
563        id: &str,
564        target_agent_uid: &str,
565        block_id: &str,
566        account_id: &str,
567        provider: &str,
568        now_ms: i64,
569    ) -> Result<bool, StoreError> {
570        let conn = self.conn().lock().unwrap();
571        let n = conn.execute(
572            &format!(
573                "UPDATE db_job_runs
574                    SET state = ?2, reason = '', block_id = ?3,
575                        account_id = CASE WHEN ?4 <> '' THEN ?4 ELSE account_id END, provider = ?5,
576                        target_agent_uid = CASE WHEN ?6 <> '' THEN ?6 ELSE target_agent_uid END,
577                        started_at_ms = ?7, ended_at_ms = NULL
578                  WHERE id = ?1 AND {OPEN_NOT_ENDED}"
579            ),
580            params![id, state::RUNNING, block_id, account_id, provider, target_agent_uid, now_ms],
581        )?;
582        Ok(n > 0)
583    }
584
585    /// A fire that reached no one: `missed` (closed) or, under catch-up
586    /// `latest`, `pending` (waiting for its agent), with `why`.
587    pub fn job_run_set_undelivered(&self, id: &str, new_state: &str, why: &str, now_ms: i64) -> Result<bool, StoreError> {
588        let ended = (new_state != state::PENDING).then_some(now_ms);
589        let conn = self.conn().lock().unwrap();
590        let n = conn.execute(
591            &format!(
592                "UPDATE db_job_runs SET state = ?2, reason = ?3, ended_at_ms = ?4
593                  WHERE id = ?1 AND {OPEN_NOT_ENDED}"
594            ),
595            params![id, new_state, why, ended],
596        )?;
597        Ok(n > 0)
598    }
599
600    /// End a job's waiting pending fires (other than `except`) with `why`
601    /// (`superseded`, `expired`). Returns their ids.
602    pub fn job_runs_end_pending(&self, job_id: &str, except: &str, why: &str, now_ms: i64) -> Result<Vec<String>, StoreError> {
603        let conn = self.conn().lock().unwrap();
604        let mut stmt = conn.prepare(
605            "UPDATE db_job_runs SET reason = ?3, ended_at_ms = ?4
606              WHERE job_id = ?1 AND id <> ?2 AND state = 'pending' AND ended_at_ms IS NULL
607              RETURNING id",
608        )?;
609        let rows = stmt.query_map(params![job_id, except, why, now_ms], |r| r.get(0))?;
610        Ok(rows.collect::<Result<Vec<String>, _>>()?)
611    }
612
613    /// End one waiting pending fire with `why`.
614    pub fn job_run_end_one_pending(&self, id: &str, why: &str, now_ms: i64) -> Result<bool, StoreError> {
615        let conn = self.conn().lock().unwrap();
616        let n = conn.execute(
617            "UPDATE db_job_runs SET reason = ?2, ended_at_ms = ?3
618              WHERE id = ?1 AND state = 'pending' AND ended_at_ms IS NULL",
619            params![id, why, now_ms],
620        )?;
621        Ok(n > 0)
622    }
623
624    /// The cron runs that take a place: running, or admitted and being
625    /// delivered (`scheduled` with no waiting reason). Overlap, concurrency
626    /// groups and the global limit count these.
627    pub fn job_runs_occupying(&self) -> Result<Vec<JobRun>, StoreError> {
628        let conn = self.conn().lock().unwrap();
629        let mut stmt = conn.prepare(&format!(
630            "SELECT {COLS} FROM db_job_runs
631              WHERE job_source = 'cron' AND ended_at_ms IS NULL
632                AND (state = 'running' OR (state = 'scheduled' AND reason = ''))
633              ORDER BY started_at_ms"
634        ))?;
635        let rows = stmt.query_map([], row_to_run)?;
636        Ok(rows.collect::<Result<Vec<_>, _>>()?)
637    }
638
639    /// The cron runs waiting to start, oldest first: `scheduled` with a
640    /// waiting reason ([`reason::WAITING`]).
641    pub fn job_runs_waiting(&self) -> Result<Vec<JobRun>, StoreError> {
642        let conn = self.conn().lock().unwrap();
643        let list = reason::WAITING.iter().map(|r| format!("'{r}'")).collect::<Vec<_>>().join(",");
644        let mut stmt = conn.prepare(&format!(
645            "SELECT {COLS} FROM db_job_runs
646              WHERE job_source = 'cron' AND state = 'scheduled' AND ended_at_ms IS NULL AND reason IN ({list})
647              ORDER BY started_at_ms, rowid"
648        ))?;
649        let rows = stmt.query_map([], row_to_run)?;
650        Ok(rows.collect::<Result<Vec<_>, _>>()?)
651    }
652
653    /// Make the just-inserted `scheduled` run wait for `why`.
654    pub fn job_run_set_wait(&self, id: &str, why: &str) -> Result<bool, StoreError> {
655        let conn = self.conn().lock().unwrap();
656        let n = conn.execute(
657            "UPDATE db_job_runs SET reason = ?2 WHERE id = ?1 AND state = 'scheduled' AND ended_at_ms IS NULL",
658            params![id, why],
659        )?;
660        Ok(n > 0)
661    }
662
663    /// A waiting run starts: its reason is cleared if it still is `from`
664    /// (only one scheduler admits it), and its start is now.
665    pub fn job_run_admit(&self, id: &str, from: &str, now_ms: i64) -> Result<bool, StoreError> {
666        let conn = self.conn().lock().unwrap();
667        let n = conn.execute(
668            "UPDATE db_job_runs SET reason = '', started_at_ms = ?3
669              WHERE id = ?1 AND state = 'scheduled' AND reason = ?2 AND ended_at_ms IS NULL",
670            params![id, from, now_ms],
671        )?;
672        Ok(n > 0)
673    }
674
675    /// Close a still-open run that something stopped (the timeout, a
676    /// `cancel_other` overlap): `finished` with `infra`, `why` as its reason
677    /// and `summary`. `false` when it was already closed.
678    pub fn job_run_stop(&self, id: &str, infra_status: &str, why: &str, summary: &str, now_ms: i64) -> Result<bool, StoreError> {
679        let conn = self.conn().lock().unwrap();
680        let n = conn.execute(
681            &format!(
682                "UPDATE db_job_runs
683                    SET state = 'finished', infra = ?2, reason = ?3, summary = ?4, ended_at_ms = ?5
684                  WHERE id = ?1 AND {OPEN_NOT_ENDED}"
685            ),
686            params![id, infra_status, why, clip_summary(summary), now_ms],
687        )?;
688        Ok(n > 0)
689    }
690
691    /// Close an open run that did its work at once (a filed task): `finished`,
692    /// infra `ok`, with the outcome it concluded.
693    pub fn job_run_conclude(&self, id: &str, outcome: &str, summary: &str, now_ms: i64) -> Result<bool, StoreError> {
694        let conn = self.conn().lock().unwrap();
695        let n = conn.execute(
696            &format!(
697                "UPDATE db_job_runs
698                    SET state = 'finished', infra = 'ok', outcome = ?2, summary = ?3, ended_at_ms = ?4
699                  WHERE id = ?1 AND {OPEN_NOT_ENDED}"
700            ),
701            params![id, outcome, clip_summary(summary), now_ms],
702        )?;
703        Ok(n > 0)
704    }
705
706    /// The turn a running run started or joined; `partial` when it joined a
707    /// turn already running, so its cost includes other work.
708    pub fn job_run_bind_turn(&self, id: &str, turn_id: i64, partial: bool) -> Result<bool, StoreError> {
709        let conn = self.conn().lock().unwrap();
710        let n = conn.execute(
711            "UPDATE db_job_runs SET turn_id = ?2, cost_partial = ?3 WHERE id = ?1 AND state = 'running'",
712            params![id, turn_id, partial as i64],
713        )?;
714        Ok(n > 0)
715    }
716
717    /// Close a still-open run as `finished` with `infra`, its cost, and a
718    /// summary when the run has none yet. `false` when it was already closed.
719    pub fn job_run_finish(
720        &self,
721        id: &str,
722        infra_status: &str,
723        cost: Option<RunCost>,
724        summary: &str,
725        now_ms: i64,
726    ) -> Result<bool, StoreError> {
727        let conn = self.conn().lock().unwrap();
728        let c = cost.unwrap_or_default();
729        let n = conn.execute(
730            &format!(
731                "UPDATE db_job_runs
732                    SET state = ?10, infra = ?2, ended_at_ms = ?3,
733                        cost_usd = CASE WHEN ?4 THEN ?5 ELSE cost_usd END,
734                        cost_known = CASE WHEN ?4 THEN ?6 ELSE cost_known END,
735                        output_tokens = CASE WHEN ?4 THEN ?7 ELSE output_tokens END,
736                        steps = CASE WHEN ?4 THEN ?8 ELSE steps END,
737                        summary = CASE WHEN summary = '' THEN ?9 ELSE summary END
738                  WHERE id = ?1 AND {OPEN_NOT_ENDED}"
739            ),
740            params![
741                id,
742                infra_status,
743                now_ms,
744                cost.is_some(),
745                c.cost_usd,
746                c.cost_known as i64,
747                c.output_tokens,
748                c.steps,
749                clip_summary(summary),
750                state::FINISHED
751            ],
752        )?;
753        Ok(n > 0)
754    }
755
756    /// The run's own verdict (§3.2): its outcome, a summary, links merged
757    /// into `links.reported`. Refused for a run that never ran. A report
758    /// that changes the outcome of a run that has ended moves the incident
759    /// keeper's cursor back to just before it, in the same transaction, so
760    /// the run is judged again (`job_incidents`).
761    pub fn job_run_report(
762        &self,
763        id: &str,
764        outcome: &str,
765        summary: &str,
766        links: &serde_json::Value,
767    ) -> Result<bool, StoreError> {
768        let mut conn = self.conn().lock().unwrap();
769        let tx = conn.transaction()?;
770        let current: Option<(String, String, String, Option<i64>)> = tx
771            .query_row(
772                "SELECT links, outcome, job_id, ended_at_ms FROM db_job_runs WHERE id = ?1 AND state IN ('running','finished')",
773                params![id],
774                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
775            )
776            .optional()?;
777        let Some((current, was, job_id, ended)) = current else {
778            return Ok(false);
779        };
780        let mut merged: serde_json::Value = serde_json::from_str(&current).unwrap_or_else(|_| serde_json::json!({}));
781        if !merged.is_object() {
782            merged = serde_json::json!({});
783        }
784        if !links.is_null() {
785            merged["reported"] = links.clone();
786        }
787        tx.execute(
788            "UPDATE db_job_runs SET outcome = ?2, summary = ?3, links = ?4 WHERE id = ?1",
789            params![id, outcome, clip_summary(summary), merged.to_string()],
790        )?;
791        if let (true, Some(ended)) = (was != outcome, ended) {
792            tx.execute(
793                "UPDATE db_job_incident_cursors SET ended_at_ms = ?2, run_id = ''
794                  WHERE job_id = ?1 AND (ended_at_ms > ?2 OR (ended_at_ms = ?2 AND run_id >= ?3))",
795                params![job_id, ended, id],
796            )?;
797        }
798        tx.commit()?;
799        Ok(true)
800    }
801
802    /// Merge `extra`'s keys into the run's `links`.
803    pub fn job_run_add_links(&self, id: &str, extra: &serde_json::Value) -> Result<(), StoreError> {
804        let mut conn = self.conn().lock().unwrap();
805        let tx = conn.transaction()?;
806        let current: Option<String> =
807            tx.query_row("SELECT links FROM db_job_runs WHERE id = ?1", params![id], |r| r.get(0)).optional()?;
808        let Some(current) = current else {
809            return Ok(());
810        };
811        let mut merged: serde_json::Value = serde_json::from_str(&current).unwrap_or_else(|_| serde_json::json!({}));
812        if let (Some(m), Some(e)) = (merged.as_object_mut(), extra.as_object()) {
813            for (k, v) in e {
814                m.insert(k.clone(), v.clone());
815            }
816        }
817        tx.execute("UPDATE db_job_runs SET links = ?2 WHERE id = ?1", params![id, merged.to_string()])?;
818        tx.commit()?;
819        Ok(())
820    }
821
822    /// Every open run of `job_source` this channel wrote (`recorded_by`
823    /// `<channel>@…`), in `states`.
824    pub fn job_runs_open_recorded_by(
825        &self,
826        channel: &str,
827        job_source: &str,
828        states: &[&str],
829    ) -> Result<Vec<JobRun>, StoreError> {
830        let conn = self.conn().lock().unwrap();
831        let list = states.iter().map(|s| format!("'{}'", s.replace('\'', ""))).collect::<Vec<_>>().join(",");
832        let mut stmt = conn.prepare(&format!(
833            "SELECT {COLS} FROM db_job_runs
834              WHERE job_source = ?1 AND state IN ({list})
835                AND (recorded_by = ?2 OR substr(recorded_by, 1, length(?2) + 1) = ?2 || '@')
836              ORDER BY started_at_ms"
837        ))?;
838        let rows = stmt.query_map(params![job_source, channel], row_to_run)?;
839        Ok(rows.collect::<Result<Vec<_>, _>>()?)
840    }
841
842    /// Every open run `channel` follows for the channel that fired it
843    /// (`links.followed_by_channel`, #1988).
844    pub fn job_runs_open_followed_by(&self, channel: &str) -> Result<Vec<JobRun>, StoreError> {
845        let conn = self.conn().lock().unwrap();
846        let mut stmt = conn.prepare(&format!(
847            "SELECT {COLS} FROM db_job_runs
848              WHERE {OPEN_NOT_ENDED}
849                AND CASE WHEN json_valid(links) THEN json_extract(links, '$.followed_by_channel') END = ?1
850              ORDER BY started_at_ms"
851        ))?;
852        let rows = stmt.query_map(params![channel], row_to_run)?;
853        Ok(rows.collect::<Result<Vec<_>, _>>()?)
854    }
855
856    /// Record `skip`, a `skipped` row for one slot (`scheduled_for_ms` set,
857    /// `skip_count` 1). When the job's newest row is a skip for the same
858    /// reason, the slot is counted into that row (`skip_count` + 1,
859    /// `last_skip_at_ms`) and `skip` is kept hidden under it
860    /// (`collapsed_into`), so consecutive skips show as one row while every
861    /// slot keeps its own row in the unique `(job_id, scheduled_for_ms)`
862    /// index: the slot stays leased, and another scheduler sharing the job
863    /// can't fire it later (after Resume all, say). A slot already taken (by
864    /// another instance's count, or a fire) counts nothing.
865    pub fn job_run_record_skip_slot(&self, skip: &JobRun) -> Result<(), StoreError> {
866        let mut conn = self.conn().lock().unwrap();
867        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
868        let newest: Option<(String, String, String)> = tx
869            .query_row(
870                "SELECT id, state, reason FROM db_job_runs
871                  WHERE job_id = ?1 AND collapsed_into = ''
872                  ORDER BY started_at_ms DESC, rowid DESC LIMIT 1",
873                params![skip.job_id],
874                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
875            )
876            .optional()?;
877        let fold_into = newest.filter(|(_, st, why)| st == state::SKIPPED && *why == skip.reason).map(|(id, _, _)| id);
878        let inserted = tx.execute(
879            &format!(
880                "INSERT OR IGNORE INTO db_job_runs ({COLS}, collapsed_into) VALUES \
881                 (?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,?33)"
882            ),
883            params![
884                skip.id,
885                skip.job_id,
886                skip.job_source,
887                skip.job_name,
888                skip.template_id,
889                skip.template_version,
890                skip.trigger,
891                skip.scheduled_for_ms,
892                skip.triggered_by,
893                skip.attempt,
894                skip.state,
895                skip.reason,
896                skip.infra,
897                skip.outcome,
898                skip.summary,
899                skip.target_agent_uid,
900                skip.block_id,
901                skip.turn_id,
902                skip.account_id,
903                skip.provider,
904                skip.started_at_ms,
905                skip.ended_at_ms,
906                skip.cost_usd,
907                skip.cost_known as i64,
908                skip.cost_partial as i64,
909                skip.output_tokens,
910                skip.steps,
911                skip.links.to_string(),
912                if fold_into.is_some() { 0 } else { skip.skip_count },
913                skip.last_skip_at_ms,
914                skip.reporter,
915                skip.recorded_by,
916                fold_into.as_deref().unwrap_or(""),
917            ],
918        )?;
919        if inserted > 0 {
920            if let Some(into) = &fold_into {
921                tx.execute(
922                    "UPDATE db_job_runs SET skip_count = skip_count + 1,
923                            last_skip_at_ms = MAX(COALESCE(last_skip_at_ms, 0), ?2)
924                      WHERE id = ?1",
925                    params![into, skip.scheduled_for_ms],
926                )?;
927            }
928        }
929        tx.commit()?;
930        Ok(())
931    }
932
933    /// The job's spend since `since_ms`: the summed `cost_usd` of its runs
934    /// started then or later, and whether any of them reported a cost.
935    pub fn job_runs_cost_since(&self, job_id: &str, since_ms: i64) -> Result<(f64, bool), StoreError> {
936        let conn = self.conn().lock().unwrap();
937        Ok(conn.query_row(
938            "SELECT COALESCE(SUM(cost_usd), 0), COALESCE(MAX(cost_known), 0) FROM db_job_runs
939              WHERE job_id = ?1 AND collapsed_into = '' AND started_at_ms >= ?2",
940            params![job_id, since_ms],
941            |r| Ok((r.get::<_, f64>(0)?, r.get::<_, i64>(1)? != 0)),
942        )?)
943    }
944
945    /// A switch every job honours (`db_job_flags`), if it is set.
946    pub fn job_flag_get(&self, key: &str) -> Result<Option<JobFlag>, StoreError> {
947        let conn = self.conn().lock().unwrap();
948        Ok(conn
949            .query_row(
950                "SELECT value, set_at_ms, set_by FROM db_job_flags WHERE key = ?1",
951                params![key],
952                |r| Ok(JobFlag { value: r.get(0)?, set_at_ms: r.get(1)?, set_by: r.get(2)? }),
953            )
954            .optional()?)
955    }
956
957    /// Set the switch `key`, by `set_by`, now. Setting it again keeps the
958    /// first time it was set.
959    pub fn job_flag_set(&self, key: &str, value: &str, set_by: &str, now_ms: i64) -> Result<(), StoreError> {
960        let conn = self.conn().lock().unwrap();
961        conn.execute(
962            "INSERT INTO db_job_flags (key, value, set_at_ms, set_by) VALUES (?1, ?2, ?3, ?4)
963             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
964            params![key, value, now_ms, set_by],
965        )?;
966        Ok(())
967    }
968
969    /// Clear the switch `key`. `false` when it wasn't set.
970    pub fn job_flag_clear(&self, key: &str) -> Result<bool, StoreError> {
971        let conn = self.conn().lock().unwrap();
972        Ok(conn.execute("DELETE FROM db_job_flags WHERE key = ?1", params![key])? > 0)
973    }
974}
975
976/// A switch in `db_job_flags`: its value, when it was set and by whom.
977#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ts_rs::TS)]
978#[ts(export, export_to = "../../../frontend/types/rpc/")]
979pub struct JobFlag {
980    pub value: String,
981    #[ts(type = "number")]
982    pub set_at_ms: i64,
983    pub set_by: String,
984}
985
986#[cfg(test)]
987#[path = "job_runs_tests.rs"]
988mod tests;