Skip to main content

agentmux_srv_core/backend/jobs/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Jobs: things that run by themselves, and the one run ledger under them
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3).
6//!
7//! [`RunLedger`] writes `db_job_runs` rows (`storage::job_runs`) for cron
8//! fires and Drone runs, follows a delivered fire's turn to its end
9//! ([`follower`]), and on startup closes the runs a restart interrupted.
10//! After each change it nudges [`incidents`], which opens one incident per
11//! failing job (§3.4).
12//! Cron fires are never held for a stopped agent: an undelivered fire is
13//! `missed`, or, under catch-up `latest`, the job's one `pending` fire (§3.2,
14//! §5.2), which the scheduler delivers when the agent is back.
15
16pub mod admission;
17pub mod app_events;
18pub mod cap_alert;
19pub mod caps;
20pub mod cloud_events;
21pub mod cloud_hub;
22pub mod definition;
23pub mod expect;
24pub mod file_watch;
25pub mod follower;
26pub mod from_template;
27pub mod incidents;
28pub mod paused;
29pub mod policy;
30pub mod poll;
31pub mod remote;
32pub mod reporters;
33pub mod reservation;
34pub mod verdict;
35pub mod webhook_local;
36pub mod watchdog;
37
38use std::sync::Arc;
39
40use agentmux_common::time::now_ms;
41use serde_json::{json, Value};
42
43use crate::backend::cron::{FireOutcome, MissReason};
44use crate::backend::mps::Broker;
45use crate::backend::storage::job_runs::{infra, reason, state, JobFlag, JobRun, RunCost};
46use crate::backend::storage::store::Store;
47use crate::backend::storage::drone_store::DroneStore;
48
49/// Job kinds in `job_source` (§3.1).
50pub const SOURCE_CRON: &str = "cron";
51pub const SOURCE_DRONE: &str = "drone";
52pub const SOURCE_CLOUD: &str = "cloud";
53
54/// Run triggers in `trigger` (§3.1).
55pub const TRIGGER_SCHEDULE: &str = "schedule";
56pub const TRIGGER_CATCH_UP: &str = "catch_up";
57pub const TRIGGER_MANUAL: &str = "manual";
58pub const TRIGGER_RETRY: &str = "retry";
59pub const TRIGGER_EVENT: &str = "event";
60
61/// `triggered_by` for runs the scheduler starts, and for the operator.
62pub const BY_SCHEDULER: &str = "scheduler";
63pub const BY_OPERATOR: &str = "operator";
64/// `triggered_by` for an event's run is this, then `:` and the source (`event:app_event`).
65pub const BY_EVENT: &str = "event";
66
67/// A cron job's catch-up policy (§5.2): what an undelivered fire leaves.
68pub const CATCH_UP_SKIP: &str = "skip";
69pub const CATCH_UP_LATEST: &str = "latest";
70
71/// The identity-store switch Pause all sets (§3.3): while it is on, every
72/// scheduled fire is a collapsed `skipped (paused_all)` row and Run now is
73/// refused. Only the operator turns it on or off.
74pub const FLAG_PAUSED_ALL: &str = "jobs:paused_all";
75
76/// What a Run now gets while the job's previous run is still going and its
77/// policy `overlap` is `skip`.
78pub const OVERLAP_REFUSAL: &str = "this job's previous run is still running (policy overlap: skip)";
79
80/// What a Run now gets while Pause all is on.
81pub const PAUSED_ALL_REFUSAL: &str =
82    "the operator has paused every job (Pause all); Run now is off until they resume them";
83
84/// The status a Drone run left `running` by a restart gets in
85/// `db_drone_runs` (§3.2). An open string there, like every other status.
86pub const DRONE_STATUS_INTERRUPTED: &str = "interrupted";
87
88/// Woken whenever an agent registers (`reactive::registered`), so a pending
89/// fire reaches its agent as soon as it is back.
90pub fn pending_wake() -> &'static tokio::sync::Notify {
91    static WAKE: std::sync::LazyLock<tokio::sync::Notify> = std::sync::LazyLock::new(tokio::sync::Notify::new);
92    &WAKE
93}
94
95/// The line a fire's prompt ends with: the run id, and how to report (§3.2).
96/// A late fire (a catch-up, a pending fire delivered when its agent came
97/// back) also says which slot it was for and when it started, so the agent
98/// can tell its work is late. Plain text: srv rewrites `[AgentMux]` markers
99/// in anything forwarded.
100pub fn brief_line(run_id: &str, late_for_ms: Option<i64>, now_ms: i64) -> String {
101    let late = late_for_ms
102        .and_then(|slot| {
103            let slot = chrono::DateTime::from_timestamp_millis(slot)?;
104            let now = chrono::DateTime::from_timestamp_millis(now_ms)?;
105            Some(format!(
106                " It was due {} and started {} (late).",
107                slot.format("%Y-%m-%d %H:%M UTC"),
108                now.format("%Y-%m-%d %H:%M UTC")
109            ))
110        })
111        .unwrap_or_default();
112    format!(
113        "(Scheduled run {run_id}.{late} When it is done, say how it went: Schedule action report with run_id \
114         \"{run_id}\", outcome ok, findings or failed, and a one-line summary.)"
115    )
116}
117
118/// Something done to a pane, by its block id: interrupting its turn, stopping a worker.
119pub type BlockHook = Arc<dyn Fn(&str) + Send + Sync>;
120
121/// What [`RunLedger::pane`] reads from a pane's meta.
122#[derive(Debug, Default)]
123struct Pane {
124    /// The block is in this channel's store.
125    found: bool,
126    agent_uid: String,
127    account: String,
128    provider: String,
129}
130
131/// Whether an agent is registered in `block_id` on this instance.
132fn registered_here(block_id: &str) -> bool {
133    crate::backend::reactive::get_global_handler().list_agents().iter().any(|r| r.block_id == block_id)
134}
135
136/// The UID the agent registered in `block_id` gave, if any.
137fn registered_uid(block_id: &str) -> Option<String> {
138    if block_id.is_empty() {
139        return None;
140    }
141    crate::backend::reactive::get_global_handler()
142        .list_agents()
143        .into_iter()
144        .find(|r| r.block_id == block_id)
145        .and_then(|r| r.uid)
146        .filter(|u| !u.is_empty())
147}
148
149/// What inserting a cron slot's row answered.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum Begin {
152    /// The slot is ours; this is its run id.
153    Run(String),
154    /// Another scheduler sharing the job has this slot: don't fire.
155    SlotTaken,
156    /// The row couldn't be written (logged): fire anyway, unrecorded.
157    Unrecorded,
158}
159
160/// The run ledger, shared by the cron scheduler, the Drone handlers and the
161/// Schedule routes.
162pub struct RunLedger {
163    store: Arc<Store>,
164    /// The channel's object store: a pane's meta (its account) and agent
165    /// definitions. `None` in tests that don't need them.
166    mstore: Option<Arc<Store>>,
167    /// This instance's channel (`registry::local_channel_id`).
168    channel: String,
169    /// The channel and version that write rows here, `<channel>@<version>`.
170    /// Startup cleanup and the pending-fire delivery only touch rows their
171    /// own channel wrote: the ledger is shared by every instance on the
172    /// computer.
173    recorded_by: String,
174    follower: follower::Follower,
175    /// Where `JobsChanged` goes after each write, so the Jobs tab refreshes.
176    broker: Arc<Broker>,
177    /// Failure incidents (§3.4), once [`Self::install_incidents`] ran.
178    incidents: std::sync::OnceLock<Arc<incidents::Incidents>>,
179    /// Where jobs are, for policy (`admission.rs`).
180    jobs: std::sync::OnceLock<Arc<Store>>,
181    /// Held while a run's place is decided and its row written.
182    admission: std::sync::Mutex<()>,
183    /// Pending fires that were told to start and are being delivered: run id to
184    /// job id. A pending row doesn't occupy a place in the ledger, so until the
185    /// delivery lands these count as running.
186    pending_claims: std::sync::Mutex<std::collections::HashMap<String, String>>,
187    interrupt: std::sync::OnceLock<BlockHook>,
188    worker_stop: std::sync::OnceLock<BlockHook>,
189    /// How to ask another channel's instance to stop a run it follows (`remote.rs`).
190    remote_stop: std::sync::OnceLock<remote::RemoteStopHook>,
191    /// Spending caps: Settings' figures and where a run would go
192    /// (`reservation.rs`).
193    caps: std::sync::OnceLock<reservation::CapSources>,
194    /// Tests: the start of the day, as a fixed clock gives it.
195    #[cfg(any(test, feature = "test-support"))]
196    day_start: std::sync::Mutex<Option<Arc<dyn Fn(i64) -> i64 + Send + Sync>>>,
197    /// Tests: the cap alerts raised, as `(job id, reason)`.
198    #[cfg(any(test, feature = "test-support"))]
199    cap_alerts: std::sync::Mutex<Vec<(String, String)>>,
200}
201
202impl RunLedger {
203    /// A ledger over `store` (the work store), following turns on
204    /// `broker`. Needs a tokio runtime (the follower's task).
205    pub fn new(store: Arc<Store>, mstore: Option<Arc<Store>>, broker: Arc<Broker>) -> Arc<Self> {
206        Self::new_in(store, mstore, broker, &crate::backend::reactive::registry::local_channel_id())
207    }
208
209    /// [`Self::new`] as the instance of `channel`: tests run two channels'
210    /// ledgers in one process.
211    pub fn new_in(store: Arc<Store>, mstore: Option<Arc<Store>>, broker: Arc<Broker>, channel: &str) -> Arc<Self> {
212        if let Err(e) = store.job_runs_ensure_schema() {
213            tracing::warn!(error = %e, "jobs: couldn't create the run ledger table");
214        }
215        Arc::new_cyclic(|weak: &std::sync::Weak<RunLedger>| RunLedger {
216            store: store.clone(),
217            mstore,
218            channel: channel.to_string(),
219            recorded_by: format!("{channel}@{}", env!("CARGO_PKG_VERSION")),
220            follower: follower::Follower::start(weak.clone(), broker.clone()),
221            broker,
222            incidents: std::sync::OnceLock::new(),
223            jobs: std::sync::OnceLock::new(),
224            admission: std::sync::Mutex::new(()),
225            pending_claims: std::sync::Mutex::default(),
226            interrupt: std::sync::OnceLock::new(),
227            worker_stop: std::sync::OnceLock::new(),
228            remote_stop: std::sync::OnceLock::new(),
229            caps: std::sync::OnceLock::new(),
230            #[cfg(any(test, feature = "test-support"))]
231            day_start: std::sync::Mutex::new(None),
232            #[cfg(any(test, feature = "test-support"))]
233            cap_alerts: std::sync::Mutex::new(Vec::new()),
234        })
235    }
236
237    pub fn store(&self) -> &Arc<Store> {
238        &self.store
239    }
240
241    /// Open an incident when a job fails, from now on (§3.4). `jobs` is
242    /// where cron jobs are, for a job's owner.
243    pub fn install_incidents(&self, jobs: Option<Arc<Store>>) {
244        if let Some(jobs) = &jobs {
245            self.install_jobs(jobs.clone());
246        }
247        let keeper = incidents::Incidents::new(self.store.clone(), self.mstore.clone(), jobs, self.broker.clone());
248        if self.incidents.set(keeper.clone()).is_ok() {
249            keeper.start();
250        }
251    }
252
253    /// Tell the Jobs tab job `job_id`'s runs changed (`JobsChanged`); `""`
254    /// for a change to every job. A job's change is also looked at for an
255    /// incident.
256    pub fn changed(&self, job_id: &str) {
257        let event = crate::backend::mps_events::JobsChangedEvent { job_id: job_id.to_string() };
258        self.broker.publish_event::<crate::backend::mps_events::JobsChanged>(&event, vec![], 0);
259        if !job_id.is_empty() {
260            if let Some(keeper) = self.incidents.get() {
261                keeper.nudge(job_id);
262            }
263        }
264    }
265
266    /// [`Self::changed`] for the job run `run_id` belongs to.
267    pub(crate) fn run_changed(&self, run_id: &str) {
268        let job_id = self.store.job_run_get(run_id).ok().flatten().map(|r| r.job_id).unwrap_or_default();
269        self.changed(&job_id);
270    }
271
272    /// Pause all, when the operator has it on: since when, and by whom.
273    pub fn paused_all(&self) -> Option<JobFlag> {
274        self.store.job_flag_get(FLAG_PAUSED_ALL).unwrap_or_else(|e| {
275            tracing::warn!(error = %e, "jobs: couldn't read Pause all");
276            None
277        })
278    }
279
280    /// Turn Pause all on or off. The caller has checked that the operator
281    /// asked: agents can't (§7).
282    pub fn set_paused_all(&self, on: bool, by: &str) -> Result<(), crate::backend::storage::StoreError> {
283        if on {
284            self.store.job_flag_set(FLAG_PAUSED_ALL, "1", by, now_ms())?;
285        } else {
286            self.store.job_flag_clear(FLAG_PAUSED_ALL)?;
287        }
288        self.changed("");
289        Ok(())
290    }
291
292    /// A slot of `job` that didn't fire because the job, or every job, was
293    /// paused (`reason`): counted into the job's newest row when that is the
294    /// same skip, else a new `skipped` row; either way the slot keeps its own
295    /// leased row, so no scheduler fires it later (§3.1, §3.3).
296    pub fn record_skip_slot(&self, job: &crate::backend::storage::cron::CronJob, slot_ms: i64, why: &str) {
297        let now = now_ms();
298        let mut run = self.row(&job.id, SOURCE_CRON, &job.name, TRIGGER_SCHEDULE, now);
299        run.state = state::SKIPPED.to_string();
300        run.reason = why.to_string();
301        run.scheduled_for_ms = Some(slot_ms);
302        run.triggered_by = BY_SCHEDULER.to_string();
303        run.target_agent_uid = job.target_uid.clone();
304        run.skip_count = 1;
305        run.last_skip_at_ms = Some(slot_ms);
306        run.ended_at_ms = Some(now);
307        match self.store.job_run_record_skip_slot(&run) {
308            Ok(()) => self.changed(&job.id),
309            Err(e) => tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a paused slot"),
310        }
311    }
312
313    pub(crate) fn row(&self, job_id: &str, job_source: &str, job_name: &str, trigger: &str, now: i64) -> JobRun {
314        let mut run =
315            JobRun::new(&uuid::Uuid::new_v4().to_string(), job_id, job_source, job_name, trigger, state::SCHEDULED, now);
316        run.recorded_by = self.recorded_by.clone();
317        run
318    }
319
320    /// Insert the `scheduled` row of a cron fire before firing it. For a
321    /// slot, that insert is the lease (§3.1): a second scheduler sharing
322    /// the job finds the slot taken.
323    pub fn begin_cron(
324        &self,
325        job: &crate::backend::storage::cron::CronJob,
326        trigger: &str,
327        scheduled_for_ms: Option<i64>,
328        triggered_by: &str,
329    ) -> Begin {
330        let mut run = self.row(&job.id, SOURCE_CRON, &job.name, trigger, now_ms());
331        run.scheduled_for_ms = scheduled_for_ms;
332        run.triggered_by = triggered_by.to_string();
333        run.target_agent_uid = job.target_uid.clone();
334        match self.store.job_run_insert(&run) {
335            Ok(true) => Begin::Run(run.id),
336            Ok(false) => Begin::SlotTaken,
337            Err(e) => {
338                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a cron run");
339                Begin::Unrecorded
340            }
341        }
342    }
343
344    /// Record what a cron fire's delivery decided for run `run_id` of
345    /// `job`. `delivery_started_ms` is when the delivery began: delivery can
346    /// wait for the turn it starts, so that turn may begin, or even end,
347    /// before the answer. A scheduled fire also ends the job's older pending
348    /// fire: it is superseded when this one is pending in its place, else
349    /// expired (its next fire time came).
350    pub fn record_delivery(
351        &self,
352        run_id: &str,
353        job: &crate::backend::storage::cron::CronJob,
354        outcome: &FireOutcome,
355        scheduled: bool,
356        delivery_started_ms: i64,
357    ) {
358        let now = now_ms();
359        let latest = job.catch_up == CATCH_UP_LATEST;
360        let result = match outcome {
361            FireOutcome::Delivered { block_id } => {
362                self.mark_running(run_id, &job.target_uid, block_id.as_deref().unwrap_or(""), delivery_started_ms);
363                Ok(())
364            }
365            FireOutcome::Missed { reason: MissReason::TargetStopped } => {
366                let st = if latest && scheduled { state::PENDING } else { state::MISSED };
367                self.store.job_run_set_undelivered(run_id, st, reason::TARGET_STOPPED, now).map(drop)
368            }
369            FireOutcome::Missed { reason: MissReason::TargetMissing } => {
370                self.store.job_run_skip(run_id, reason::TARGET_MISSING, 1, now).map(drop)
371            }
372            FireOutcome::Failed { error } => {
373                let finished = self.store.job_run_finish(run_id, infra::ERROR, None, error, now);
374                self.maybe_retry(run_id);
375                self.reap_worker(run_id);
376                finished.map(drop)
377            }
378        };
379        if let Err(e) = result {
380            tracing::warn!(run_id, error = %e, "jobs: couldn't record a fire's delivery");
381        }
382        self.changed(&job.id);
383        if scheduled {
384            let now_pending = self.store.job_run_get(run_id).ok().flatten().is_some_and(|r| r.state == state::PENDING && r.ended_at_ms.is_none());
385            let why = if now_pending { reason::SUPERSEDED } else { reason::EXPIRED };
386            if let Err(e) = self.store.job_runs_end_pending(&job.id, run_id, why, now) {
387                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't end an older pending fire");
388            }
389        }
390    }
391
392    /// A pending fire was delivered, or failed for good, when its agent came
393    /// back (`CronScheduler::deliver_pending`, which expires it first once
394    /// its next fire time has passed). Still missing, or a failure the
395    /// held-jekt replay also retries (the agent still starting, a rate
396    /// limit, a full queue, not signed in yet), keeps it pending for the
397    /// next wake or sweep. `delivery_started_ms` as for [`Self::record_delivery`].
398    pub fn record_pending_delivery(&self, run: &JobRun, outcome: &FireOutcome, delivery_started_ms: i64) {
399        let now = now_ms();
400        let result = match outcome {
401            FireOutcome::Delivered { block_id } => {
402                self.mark_running(&run.id, &run.target_agent_uid, block_id.as_deref().unwrap_or(""), delivery_started_ms);
403                Ok(())
404            }
405            FireOutcome::Missed { .. } => Ok(()),
406            FireOutcome::Failed { error } if retry_later(error) => Ok(()),
407            FireOutcome::Failed { error } => self.store.job_run_finish(&run.id, infra::ERROR, None, error, now).map(drop),
408        };
409        if let Err(e) = result {
410            tracing::warn!(run_id = %run.id, error = %e, "jobs: couldn't record a pending fire's delivery");
411        }
412        self.changed(&run.job_id);
413    }
414
415    /// End a pending fire whose next fire time passed, or whose job is gone.
416    pub fn expire_pending(&self, run_id: &str) {
417        if let Err(e) = self.store.job_run_end_one_pending(run_id, reason::EXPIRED, now_ms()) {
418            tracing::warn!(run_id, error = %e, "jobs: couldn't expire a pending fire");
419        }
420        self.run_changed(run_id);
421    }
422
423    /// This channel's pending fires still waiting for their agent.
424    pub fn waiting_here(&self) -> Vec<JobRun> {
425        self.store
426            .job_runs_open_recorded_by(&self.channel, SOURCE_CRON, &[state::PENDING])
427            .unwrap_or_default()
428            .into_iter()
429            .filter(|r| r.ended_at_ms.is_none())
430            .collect()
431    }
432
433    /// A run reached its agent: running from now, with the pane's account,
434    /// and its turn followed to the end. `target_agent_uid` becomes the UID
435    /// of the agent whose pane took it (a job created by name records none),
436    /// so that agent can report the run.
437    ///
438    /// A pane on another instance (another channel took it) sends its turn
439    /// events to that instance's broker, so that instance follows the run
440    /// ([`Self::follow_forwarded`], #1988). This one only watches the row:
441    /// a receiver too old to follow is closed after the no-turn timeout.
442    pub(crate) fn mark_running(&self, run_id: &str, target_uid: &str, block_id: &str, now: i64) {
443        let pane = self.pane(block_id);
444        let remote = !block_id.is_empty() && self.mstore.is_some() && !pane.found && !registered_here(block_id);
445        if remote && self.followed_elsewhere(run_id) {
446            // The receiver marked it running with its pane's account.
447            self.follower.watch(run_id, now);
448            return;
449        }
450        let receiver = [pane.agent_uid.as_str(), registered_uid(block_id).as_deref().unwrap_or(""), target_uid]
451            .into_iter()
452            .find(|u| !u.is_empty())
453            .unwrap_or("")
454            .to_string();
455        let (account, provider) = (pane.account, pane.provider);
456        if let Err(e) = self.store.job_run_mark_running(run_id, &receiver, block_id, &account, &provider, now) {
457            tracing::warn!(run_id, error = %e, "jobs: couldn't mark a run running");
458            return;
459        }
460        if block_id.is_empty() {
461            // Delivered with no pane to follow (a relay answer names none):
462            // nothing would ever close it, and a restart would call it
463            // interrupted. It ran as far as AgentMux can tell (#5390).
464            self.turn_finished(run_id, infra::OK, None, "delivered; AgentMux can't follow this run's turn");
465            return;
466        }
467        if remote {
468            // No transcript link: it wouldn't resolve here.
469            self.follower.watch(run_id, now);
470            return;
471        }
472        let _ = self.store.job_run_add_links(run_id, &json!({ "transcript": { "block_id": block_id } }));
473        self.follower.arm(block_id, run_id, now, self.stop_at_usd(run_id, &provider));
474    }
475
476    /// Who a pane belongs to (its `agentId`, the agent's UID), the account
477    /// it runs on (`agent:run_account`) and its provider.
478    fn pane(&self, block_id: &str) -> Pane {
479        let Some(mstore) = &self.mstore else { return Pane::default() };
480        if block_id.is_empty() {
481            return Pane::default();
482        }
483        let Ok(Some(block)) = mstore.get::<crate::backend::obj::Block>(block_id) else {
484            return Pane::default();
485        };
486        let account = crate::backend::obj::meta_get_string(
487            &block.meta,
488            crate::backend::agent_state::RUN_ACCOUNT_META_KEY,
489            "",
490        );
491        let agent_uid = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
492        let provider = match mstore.agent_def_get(&agent_uid) {
493            Ok(Some(def)) if !agent_uid.is_empty() => crate::backend::providers::resolve_provider_alias(&def.provider).to_string(),
494            _ => String::new(),
495        };
496        Pane { found: true, agent_uid, account, provider }
497    }
498
499    /// Write the collapsed skip for slots missed while AgentMux was off
500    /// (`app_not_running`, §3.2): `count` slots from `first_slot_ms`.
501    pub fn record_missed_while_off(&self, job: &crate::backend::storage::cron::CronJob, first_slot_ms: i64, count: i64) {
502        if count <= 0 {
503            return;
504        }
505        let Begin::Run(id) = self.begin_cron(job, TRIGGER_SCHEDULE, Some(first_slot_ms), BY_SCHEDULER) else {
506            return;
507        };
508        if let Err(e) = self.store.job_run_skip(&id, reason::APP_NOT_RUNNING, count, now_ms()) {
509            tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record missed slots");
510        }
511        self.changed(&job.id);
512    }
513
514    /// The followed turn ended (or never showed up).
515    pub fn turn_finished(&self, run_id: &str, infra_status: &str, cost: Option<RunCost>, summary: &str) {
516        // Only the call that closes the row retries and reaps: a run stopped on
517        // purpose (overlap, timeout) is already closed, and its turn ending later
518        // must not file a retry of a run nobody wants again.
519        match self.store.job_run_finish(run_id, infra_status, cost, summary, now_ms()) {
520            Ok(true) => {
521                self.maybe_retry(run_id);
522                self.reap_worker(run_id);
523            }
524            Ok(false) => {}
525            Err(e) => tracing::warn!(run_id, error = %e, "jobs: couldn't close a run"),
526        }
527        self.run_changed(run_id);
528        pending_wake().notify_one();
529    }
530
531    pub(crate) fn turn_bound(&self, run_id: &str, turn_id: i64, partial: bool) {
532        if let Err(e) = self.store.job_run_bind_turn(run_id, turn_id, partial) {
533            tracing::warn!(run_id, error = %e, "jobs: couldn't record a run's turn");
534        }
535    }
536
537    /// A Drone run started: its `manual` row, running, linked to the run.
538    pub fn drone_started(
539        &self,
540        drone_run_id: &str,
541        drone_id: &str,
542        drone_name: &str,
543        started_at_ms: i64,
544        trigger: &Value,
545    ) -> Option<String> {
546        self.drone_started_by(drone_run_id, drone_id, drone_name, started_at_ms, trigger, BY_OPERATOR)
547    }
548
549    /// [`Self::drone_started`] for a run somebody other than the operator started: `triggered_by` is
550    /// the agent's id (an agent that fires a drone with `Drone` is recorded as itself).
551    pub fn drone_started_by(
552        &self,
553        drone_run_id: &str,
554        drone_id: &str,
555        drone_name: &str,
556        started_at_ms: i64,
557        trigger: &Value,
558        triggered_by: &str,
559    ) -> Option<String> {
560        let mut run = self.row(drone_id, SOURCE_DRONE, drone_name, TRIGGER_MANUAL, started_at_ms);
561        run.state = state::RUNNING.to_string();
562        run.triggered_by = triggered_by.to_string();
563        run.links = json!({
564            "drone_run_id": drone_run_id,
565            "channel": crate::backend::reactive::registry::local_channel_id(),
566        });
567        add_trigger_digest(&mut run.links, trigger);
568        match self.store.job_run_insert(&run) {
569            Ok(true) => {
570                self.changed(drone_id);
571                Some(run.id)
572            }
573            Ok(false) => None,
574            Err(e) => {
575                tracing::warn!(drone_id, error = %e, "jobs: couldn't record a Drone run");
576                None
577            }
578        }
579    }
580
581    /// A job's `drone` action started Drone run `drone_run_id`: the job's
582    /// own row (made when the fire began) runs from now and links to it, and
583    /// `drone_finished` closes it. No transcript: the run is the Drone's.
584    pub fn drone_attached(&self, run_id: &str, drone_run_id: &str, trigger: &Value, now: i64) {
585        if let Err(e) = self.store.job_run_mark_running(run_id, "", "", "", "", now) {
586            tracing::warn!(run_id, error = %e, "jobs: couldn't mark a Drone run running");
587            return;
588        }
589        let mut links = json!({
590            "drone_run_id": drone_run_id,
591            "channel": crate::backend::reactive::registry::local_channel_id(),
592        });
593        add_trigger_digest(&mut links, trigger);
594        if let Err(e) = self.store.job_run_add_links(run_id, &links) {
595            tracing::warn!(run_id, error = %e, "jobs: couldn't link a Drone run");
596        }
597        self.run_changed(run_id);
598    }
599
600    /// A Drone run ended: `ok` and the summed cost of its Agent blocks, or
601    /// `error` with its message.
602    pub fn drone_finished(
603        &self,
604        run_id: &str,
605        ok: bool,
606        block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>,
607        error: &str,
608    ) {
609        let infra_status = if ok { infra::OK } else { infra::ERROR };
610        self.turn_finished(run_id, infra_status, Some(drone_cost(block_states)), error);
611    }
612
613    /// A Drone run was cancelled: its row closes `interrupted` with the reason,
614    /// unless whoever stopped it (a timeout, `cancel_other`) closed it already.
615    pub fn drone_stopped(
616        &self,
617        run_id: &str,
618        block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>,
619        reason: &str,
620    ) {
621        self.turn_finished(run_id, infra::INTERRUPTED, Some(drone_cost(block_states)), reason);
622    }
623
624    /// After a restart: close what this channel left open (§3.2). Cron runs
625    /// still `scheduled` or `running`, and Drone runs still `running`, were
626    /// interrupted, in the ledger and in `db_drone_runs`; so were the runs
627    /// it followed for another channel (#1988). A run another channel
628    /// follows goes on there, and is watched again from here. Pending fires
629    /// stay: they wait for their agent across a restart. Call before the
630    /// scheduler starts.
631    pub fn recover_after_restart(&self) -> usize {
632        self.recover_after_restart_except(&std::collections::HashSet::new())
633    }
634
635    /// The open ledger row of Drone run `drone_run_id`, written by this channel:
636    /// the one a run taken up again after a restart goes on under.
637    pub fn open_run_of_drone(&self, drone_run_id: &str) -> Option<String> {
638        let sources: [(&str, &[&str]); 2] = [(SOURCE_CRON, &[state::SCHEDULED, state::RUNNING]), (SOURCE_DRONE, &[state::RUNNING])];
639        sources
640            .into_iter()
641            .flat_map(|(source, states)| self.store.job_runs_open_recorded_by(&self.channel, source, states).unwrap_or_default())
642            .find(|r| r.links["drone_run_id"].as_str() == Some(drone_run_id))
643            .map(|r| r.id)
644    }
645
646    /// [`recover_after_restart`](Self::recover_after_restart), except that the
647    /// Drone runs in `resuming` (by Drone run id) are being taken up again from
648    /// their checkpoints: their rows stay open, in the ledger and in
649    /// `db_drone_runs`, and they finish as any run does.
650    pub fn recover_after_restart_except(&self, resuming: &std::collections::HashSet<String>) -> usize {
651        let now = now_ms();
652        let is_resuming = |r: &JobRun| r.links["drone_run_id"].as_str().is_some_and(|d| resuming.contains(d));
653        let open = |source: &str, states: &[&str]| {
654            self.store.job_runs_open_recorded_by(&self.channel, source, states).unwrap_or_else(|e| {
655                tracing::warn!(error = %e, "jobs: couldn't read open runs");
656                Vec::new()
657            })
658        };
659        let mut closed = 0;
660        let followed_here = self.store.job_runs_open_followed_by(&self.channel).unwrap_or_else(|e| {
661            tracing::warn!(error = %e, "jobs: couldn't read followed runs");
662            Vec::new()
663        });
664        // A run waiting for a place (overlap, group, the global limit, a retry's
665        // backoff) never started: it stays open for the scheduler to start.
666        let (ours, followed_elsewhere): (Vec<JobRun>, Vec<JobRun>) = open(SOURCE_CRON, &[state::SCHEDULED, state::RUNNING])
667            .into_iter()
668            .filter(|r| !(r.state == state::SCHEDULED && reason::WAITING.contains(&r.reason.as_str())))
669            .partition(|r| remote::followed_by(r).is_none_or(|f| f.channel == self.channel));
670        for run in &followed_elsewhere {
671            self.follower.watch(&run.id, now);
672        }
673        let stale = ours.into_iter().chain(open(SOURCE_DRONE, &[state::RUNNING])).chain(followed_here).filter(|r| !is_resuming(r));
674        let mut jobs = std::collections::BTreeSet::new();
675        for run in stale {
676            if self.store.job_run_finish(&run.id, infra::INTERRUPTED, None, "AgentMux restarted during this run", now).unwrap_or(false) {
677                closed += 1;
678                jobs.insert(run.job_id);
679            }
680        }
681        if let Some(mstore) = &self.mstore {
682            let except: Vec<String> = resuming.iter().cloned().collect();
683            match mstore.drone_runs_mark_interrupted(DRONE_STATUS_INTERRUPTED, now, &except) {
684                Ok(n) if n > 0 => tracing::info!(count = n, "jobs: Drone runs interrupted by the restart marked"),
685                Ok(_) => {}
686                Err(e) => tracing::warn!(error = %e, "jobs: couldn't mark interrupted Drone runs"),
687            }
688        }
689        if closed > 0 {
690            tracing::info!(count = closed, "jobs: closed runs left open by the restart");
691            self.changed("");
692            for job_id in jobs {
693                self.changed(&job_id);
694            }
695        }
696        closed
697    }
698}
699
700/// Whether a pending fire's failed delivery is retried at the next wake or
701/// sweep rather than closing the run: the same classification as the
702/// held-jekt replay (`server::jekt_held`), plus an account out of quota
703/// (`HoldReason::Limited`), which clears at its reset.
704fn retry_later(error: &str) -> bool {
705    crate::backend::reactive::is_transient_delivery_error(error)
706        || crate::backend::reactive::is_spawn_gate_refusal(error)
707        || crate::backend::reactive::is_unavailable_refusal(error)
708        || error.contains("out of quota")
709        || error.contains("usage limit")
710}
711
712/// Note what started a Drone run without keeping it: its size and SHA-256,
713/// so the ledger shows that two runs had the same input (the body can hold
714/// text nobody should keep; real-world jobs spec D11). `Null` is no input.
715fn add_trigger_digest(links: &mut Value, trigger: &Value) {
716    use sha2::{Digest, Sha256};
717    if trigger.is_null() {
718        return;
719    }
720    let body = trigger.to_string();
721    links["trigger"] = json!({ "sha256": hex::encode(Sha256::digest(body.as_bytes())), "bytes": body.len() });
722}
723
724/// The summed `cost_usd` of a Drone run's blocks: only Agent blocks report
725/// one, in their output (`drone/executor/blocks/agent.rs`). Known only when
726/// at least one block reported a cost.
727pub fn drone_cost(block_states: &std::collections::HashMap<String, crate::backend::storage::drone_types::BlockState>) -> RunCost {
728    let mut cost = RunCost::default();
729    for b in block_states.values() {
730        let Some(out) = &b.output else { continue };
731        if let Some(c) = out.get("cost_usd").and_then(|v| v.as_f64()) {
732            cost.cost_usd += c;
733            cost.cost_known = true;
734        }
735        if let Some(t) = out.pointer("/tokens/output").and_then(|v| v.as_i64()) {
736            cost.output_tokens += t;
737        }
738    }
739    cost
740}
741
742/// Missed slots of a job's `schedule` after `base_ms` and before `now_ms`:
743/// the newest, and the earlier ones as `(first, count)`. The newest is the
744/// schedule's last slot before now, found directly, so it is right after any
745/// downtime; only the count of earlier ones stops at `cap`, so a one-minute
746/// job off for a year costs bounded work.
747pub fn missed_slots(
748    schedule: &crate::backend::cron::schedule::JobSchedule,
749    base_ms: i64,
750    now_ms: i64,
751    cap: usize,
752) -> Option<(i64, Option<(i64, i64)>)> {
753    let newest = schedule.prev_before(now_ms)?;
754    if newest <= base_ms {
755        return None;
756    }
757    let mut first = None;
758    let mut count: i64 = 0;
759    for ms in schedule.after(base_ms).take(cap) {
760        if ms >= newest {
761            break;
762        }
763        first.get_or_insert(ms);
764        count += 1;
765    }
766    Some((newest, first.map(|f| (f, count))))
767}
768
769/// Whether the agent with `uid` is registered by another channel's
770/// AgentMux on this computer and that process is alive: the cross-channel
771/// tier the inject path forwards to (Tier 2b, the host-global shared
772/// registry). A pending fire whose agent lives there is delivered through
773/// it, rather than expiring here unseen.
774pub fn registered_in_another_channel(shared_dir: &std::path::Path, uid: &str, channel: &str) -> bool {
775    !uid.is_empty()
776        && crate::backend::reactive::registry::list_all_shared(shared_dir)
777            .iter()
778            .any(|e| e.uid == uid && e.channel != channel && e.srv_alive())
779}
780
781/// The job's next fire time after `slot_ms`: when a pending fire for that
782/// slot expires (§5.2). `None` for a job whose trigger has no later slot or
783/// doesn't read.
784pub fn next_slot_after(job: &crate::backend::storage::cron::CronJob, slot_ms: i64) -> Option<i64> {
785    crate::backend::cron::schedule::JobSchedule::of(job).ok()?.next_after(slot_ms)
786}
787
788#[cfg(test)]
789#[path = "tests.rs"]
790mod tests;