magi/daemon.rs
1//! The unattended loop: take the next task, run the graph, record what
2//! happened, take the next one.
3//!
4//! This is what turns magi from a command a human types into something an
5//! agent can hand work to. [`crate::queue`] is the mailbox; this module is the
6//! thing that empties it. Nothing here decides *how* a task is implemented —
7//! that is [`crate::graph`] — it only decides which task runs next, and what a
8//! finished run means for the task that produced it.
9//!
10//! # One run at a time, on purpose
11//!
12//! There is no `--jobs` flag and there will not be one. A single run is
13//! already internally parallel: candidates implement concurrently and judges
14//! rank concurrently, so the machine is not idle while one task is in flight.
15//! The real constraint is not CPU but the agent CLIs' quota, and two graphs at
16//! once doubles the burn rate on exactly the resource whose exhaustion produces
17//! [`RunStatus::Stalled`]. Serialising the loop is what keeps a full backlog
18//! from converting the whole day's quota into a pile of untrustworthy verdicts.
19//!
20//! # A crash is legible, and the loop notices on its own
21//!
22//! The task is written as [`crate::queue::TaskStatus::Running`], with its run
23//! id, *before* the graph starts, and is only rewritten once the run reaches a
24//! terminal status. A daemon killed mid-run therefore leaves the task
25//! `Running` and pointing at the run that was in flight. The alternative —
26//! reverting the task to `Queued` on the way out — would hide the abandoned
27//! run and re-spend its quota on the next poll.
28//!
29//! A task left `Running` forever is not the point, though:
30//! [`crate::queue::TaskStatus::runnable`] never offers it again, so a daemon
31//! that died mid-run would otherwise strand its task for good.
32//! [`reclaim_orphaned_running`] runs on every poll and settles exactly the
33//! tasks no live process is actually driving — proven by [`Queue::claim`]
34//! succeeding rather than by a staleness guess — against whatever their last
35//! run actually became, through the same [`settle`] a live finish uses. A run
36//! that genuinely cannot be read still holds its task for a human; the run's
37//! own report explains how far it got.
38//!
39//! # Retries are bounded
40//!
41//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
42//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
43//! exception is a run that ended `Stalled`: the panel collapsed because the
44//! agent CLIs hit their quota, which is a fact about the machine and not about
45//! the task, so it must not spend an attempt. Without that exception a quota
46//! outage would quietly hold the entire backlog, and the operator would come
47//! back to a reset quota and nothing left that the loop is willing to run.
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::clean;
61use crate::config::{Config, MergeMode};
62use crate::graph::Runner;
63use crate::queue::{Queue, Task, TaskStatus};
64use crate::run::{RunState, RunStatus};
65
66/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
67pub const SCHEMA: u32 = 1;
68
69/// How often the status file is refreshed. A reader treats a status file older
70/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
71/// that a busy daemon is never mistaken for a dead one.
72pub const HEARTBEAT: Duration = Duration::from_secs(5);
73
74/// How old a heartbeat may be before a reader calls the daemon dead. Six
75/// missed beats: long enough to survive a slow filesystem, short enough that
76/// a crashed daemon is not still reported as running a task.
77///
78/// The single threshold every reader shares — the web UI's `/api/health` and
79/// `magi doctor` both call [`Reading::running`] rather than each comparing
80/// against their own copy of this number, so a crashed daemon cannot look
81/// alive on one screen and dead on another.
82pub const STALE_SECS: i64 = 30;
83
84/// Default queue poll interval.
85pub const POLL: Duration = Duration::from_secs(5);
86
87/// How old a claim has to be before startup sweeps it. Longer than any run
88/// this graph plausibly takes, so a sweep cannot pull a task out from under a
89/// daemon that is merely slow.
90pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
91
92/// What the loop is working on, for the status file.
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(default)]
95pub struct Current {
96 /// Task id being run.
97 pub task: String,
98 /// Run id the task produced.
99 pub run: String,
100}
101
102/// The daemon's liveness, published to `<home>/daemon.json`.
103///
104/// This is the only interface between the loop and the web UI, which is why it
105/// carries `updated_at` as well as `started_at`: a reader cannot tell a
106/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
107/// can compare the heartbeat against the clock.
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct Status {
110 /// On-disk format version.
111 pub schema: u32,
112 /// Process id, so a human can find or kill the daemon.
113 pub pid: u32,
114 /// When this process started.
115 pub started_at: Timestamp,
116 /// Last heartbeat.
117 pub updated_at: Timestamp,
118 /// True when the queue has nothing runnable.
119 pub idle: bool,
120 /// The task and run in flight, if any.
121 pub current: Option<Current>,
122 /// Tasks that reached a terminal status in this process.
123 pub completed: usize,
124 /// Queue polls since start, so a wedged loop shows up as a frozen count.
125 pub polls: u64,
126}
127
128impl Status {
129 /// A fresh, idle status for this process.
130 #[must_use]
131 pub fn new() -> Self {
132 let now = Timestamp::now();
133 Self {
134 schema: SCHEMA,
135 pid: std::process::id(),
136 started_at: now,
137 updated_at: now,
138 idle: true,
139 current: None,
140 completed: 0,
141 polls: 0,
142 }
143 }
144}
145
146impl Default for Status {
147 fn default() -> Self {
148 Self::new()
149 }
150}
151
152/// How the loop should behave.
153#[derive(Debug, Clone)]
154pub struct Opts {
155 /// Repository used by tasks that name none.
156 pub repo: PathBuf,
157 /// Explicit `magi.toml`, instead of the discovered layer stack.
158 pub config: Option<PathBuf>,
159 /// Queue poll interval.
160 pub poll: Duration,
161 /// Attempts a task gets before it is held for a human.
162 pub max_attempts: usize,
163 /// Drain what is runnable now, then return, instead of waiting for more.
164 pub once: bool,
165 /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
166 pub merge: Option<String>,
167}
168
169impl Default for Opts {
170 fn default() -> Self {
171 Self {
172 repo: PathBuf::from("."),
173 config: None,
174 poll: POLL,
175 max_attempts: 2,
176 once: false,
177 merge: None,
178 }
179 }
180}
181
182/// Where the status file lives.
183#[must_use]
184pub fn status_path() -> PathBuf {
185 crate::run::home().join("daemon.json")
186}
187
188/// Publish the status file for this process.
189pub fn write_status(status: &Status) -> Result<()> {
190 write_status_to(&status_path(), status)
191}
192
193/// Publish a status to an explicit path.
194///
195/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
196/// on every health poll and must never see a half-written one.
197pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
198 if let Some(parent) = path.parent() {
199 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
200 }
201 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
202 let tmp = path.with_extension("json.tmp");
203 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
204 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
205 Ok(())
206}
207
208/// Delete the status file. Called on the way out so a clean exit reads as
209/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
210pub fn clear_status() {
211 clear_status_at(&status_path());
212}
213
214/// Delete a status file at an explicit path, so the loop's teardown and
215/// [`clear_status`] cannot drift apart: the loop is handed the path it
216/// published to, and a test can watch a temp file disappear.
217fn clear_status_at(path: &Path) {
218 let _ = std::fs::remove_file(path);
219}
220
221/// A cooperative stop, shared with whoever asked the loop to run.
222///
223/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
224/// Ctrl-C listener and the web UI keep others, and every clone points at the
225/// same flag. There is no channel because there is nothing to send — the only
226/// message is "stop", it is idempotent, and a flag cannot be missed by a
227/// receiver that was not listening yet.
228///
229/// The handle also answers the question the operator's screen asks next: a
230/// stop does not take effect until the run in flight has finished, so
231/// [`Stop::finishing`] reports "asked to stop, still working" rather than
232/// leaving a caller to infer it from a heartbeat and hope.
233#[derive(Debug, Clone, Default)]
234pub struct Stop {
235 /// Set once, never cleared: a stop is not something an operator takes back
236 /// half way through, and a clearable flag would let a start racing a stop
237 /// resurrect a loop that is already unwinding.
238 stopped: Arc<AtomicBool>,
239 /// Whether a run is in flight, so `finishing` can distinguish a stop that
240 /// has landed from one that is waiting on `execute`.
241 busy: Arc<AtomicBool>,
242 /// Wakes the idle wait. Without this a stop would not be seen until the
243 /// poll interval elapsed, and an operator tapping stop on a phone would
244 /// watch a button do nothing for five seconds.
245 wake: Arc<Notify>,
246 /// Handed to the run in flight, so a stop can also mean "park at the next
247 /// node boundary" instead of "finish the whole competition first".
248 pause: crate::graph::Pause,
249}
250
251impl Stop {
252 /// A stop nobody has asked for yet.
253 #[must_use]
254 pub fn new() -> Self {
255 Self::default()
256 }
257
258 /// Ask the loop to stop. Idempotent, and safe to call before the loop
259 /// starts: the flag is checked before the first poll.
260 pub fn stop(&self) {
261 self.stopped.store(true, Ordering::SeqCst);
262 // `notify_one` rather than `notify_waiters` because the loop may not be
263 // parked yet: this stores a permit, so a wait that registers a moment
264 // later returns at once instead of sleeping out the whole interval.
265 self.wake.notify_one();
266 }
267
268 /// Has a stop been asked for?
269 #[must_use]
270 pub fn stopped(&self) -> bool {
271 self.stopped.load(Ordering::SeqCst)
272 }
273
274 /// Has a stop been asked for that has not taken effect yet, because a run
275 /// is still in flight?
276 ///
277 /// This is the state a screen has to be able to show. A stop never abandons
278 /// a run — see [`serve_until`] — so between the tap and the loop's return
279 /// there is a window of tens of minutes in which "running" and "stopped"
280 /// are both misleading answers.
281 #[must_use]
282 pub fn finishing(&self) -> bool {
283 self.stopped() && self.busy.load(Ordering::SeqCst)
284 }
285
286 /// Ask the loop to stop *and* the run in flight to park at its next node
287 /// boundary.
288 ///
289 /// The plain [`Stop::stop`] never abandons a run, which is right when the
290 /// operator only wants the queue to drain: a competition is tens of
291 /// minutes and its worktrees are paid for. But an operator who wants to
292 /// replace the binary cannot wait out a run that has an hour left, and
293 /// killing the process loses whatever the seats in flight had not written.
294 /// Parking costs at most the node in progress and leaves the run
295 /// resumable.
296 pub fn park(&self) {
297 self.pause.park();
298 self.stop();
299 }
300
301 /// Has a park been asked for?
302 #[must_use]
303 pub fn parking(&self) -> bool {
304 self.pause.parked()
305 }
306
307 /// The pause handle to give a runner.
308 #[must_use]
309 pub fn pause(&self) -> crate::graph::Pause {
310 self.pause.clone()
311 }
312
313 /// Is a run in flight right now?
314 ///
315 /// `finishing` answers "a stop is waiting on a run", which is false until
316 /// someone asks to stop. An upgrade needs the plain question, because it
317 /// is about to be the one asking.
318 #[must_use]
319 pub fn busy_now(&self) -> bool {
320 self.busy.load(Ordering::SeqCst)
321 }
322
323 /// Mark a run as in flight, or finished, for [`Stop::finishing`].
324 fn busy(&self, running: bool) {
325 self.busy.store(running, Ordering::SeqCst);
326 }
327
328 /// Wait out one poll interval, returning early once a stop is asked for.
329 async fn idle(&self, poll: Duration) {
330 tokio::select! {
331 () = tokio::time::sleep(poll) => {}
332 () = self.wake.notified() => {}
333 }
334 }
335}
336
337/// The daemon's published state, read permissively.
338///
339/// This mirrors [`Status`], but is a separate declaration on purpose: every
340/// field defaults, so a status file from an older or newer magi still yields
341/// a usable reading — one this build has never heard of — instead of a parse
342/// error that hides the daemon entirely.
343#[derive(Debug, Clone, Default, Deserialize)]
344#[serde(default)]
345pub struct Reading {
346 /// Format version the daemon claims.
347 pub schema: u32,
348 /// Daemon process id, for an operator who wants to stop it.
349 pub pid: Option<u32>,
350 /// When that process started.
351 pub started_at: Option<Timestamp>,
352 /// Last heartbeat. Absent means the file is unusable, hence not running.
353 pub updated_at: Option<Timestamp>,
354 /// True when the queue had nothing runnable at the last poll.
355 pub idle: bool,
356 /// What the daemon is working on.
357 pub current: Option<Current>,
358 /// Tasks this daemon process has finished.
359 pub completed: u64,
360 /// Queue polls this daemon process has made.
361 pub polls: u64,
362}
363
364impl Reading {
365 /// Seconds since the last heartbeat, or `None` when there has never been
366 /// one.
367 #[must_use]
368 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
369 self.updated_at
370 .map(|at| (now.as_second() - at.as_second()).max(0))
371 }
372
373 /// Whether the loop counts as running: a heartbeat no older than
374 /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
375 /// progress hours after the daemon that owned it was killed.
376 #[must_use]
377 pub fn running(&self, now: Timestamp) -> bool {
378 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
379 }
380}
381
382/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
383/// usable there.
384///
385/// Missing, half-written and unparseable all collapse to `None`, because the
386/// only question a reader asks is whether a daemon is alive, and a file it
387/// cannot read is not evidence that one is.
388#[must_use]
389pub fn read_status(home: &Path) -> Option<Reading> {
390 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
391 serde_json::from_str(&body).ok()
392}
393
394/// What a live daemon is working on right now, or `None`.
395///
396/// One definition of liveness, because deleting a task and deleting a run are
397/// both gated on it from both the CLI and the web UI - four callers that must
398/// never disagree about whether the same thing is in flight. A stale heartbeat
399/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
400/// left at `running` or a run left at `implementing` by a killed daemon is a
401/// leftover record rather than work in progress.
402#[must_use]
403pub fn current_work(home: &Path, now: Timestamp) -> Option<Current> {
404 read_status(home)
405 .filter(|reading| reading.running(now))
406 .and_then(|reading| reading.current)
407}
408
409/// Whether a live daemon is working on this run at this moment.
410#[must_use]
411pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
412 current_work(home, now).is_some_and(|c| c.run == run)
413}
414
415/// Whether a live daemon is working on this task at this moment.
416#[must_use]
417pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
418 current_work(home, now).is_some_and(|c| c.task == task)
419}
420
421/// Remove claim files older than `older_than` and return the task ids swept.
422///
423/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
424/// destructor, and the orphaned `.lock` file would make its task permanently
425/// unclaimable — the backlog would stop for good at exactly the task that was
426/// in flight when the machine went down.
427///
428/// The test is age alone. There is no portable way to ask whether the pid
429/// recorded in the lock is still alive and still magi (pids are reused, and
430/// `/proc` does not exist on two of the three platforms magi targets), so this
431/// trades a check it cannot make for a bound it can. The risk is real and
432/// one-sided: a run that outlives `older_than` can have its claim swept while
433/// it is still working, letting a second daemon start a second run on the same
434/// task. [`STALE_CLAIM`] is therefore set an order of magnitude above any
435/// plausible run. It runs at startup and on every poll after, always safe
436/// because a daemon only ever holds a claim of its own while [`attempt`] is
437/// running — between iterations of the very loop that calls this, never at
438/// the top of one.
439pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
440 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
441 .into_iter()
442 .flatten()
443 .flatten()
444 .map(|e| e.path())
445 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
446 .filter(|p| {
447 p.metadata()
448 .and_then(|m| m.modified())
449 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
450 .is_ok_and(|age| age >= older_than)
451 })
452 .filter(|p| std::fs::remove_file(p).is_ok())
453 .filter_map(|p| {
454 p.file_stem()
455 .and_then(|s| s.to_str())
456 .map(std::borrow::ToOwned::to_owned)
457 })
458 .collect();
459 swept.sort_unstable();
460 swept
461}
462
463/// What a finished run tells the queue about the task it came from.
464///
465/// A struct rather than a fourth and fifth boolean argument: the two flags
466/// answer different questions about the same run, and a call site passing
467/// `(…, true, false)` is one transposition away from refunding attempts
468/// forever.
469#[derive(Debug, Clone, Copy)]
470pub struct Verdict {
471 /// Where the graph stopped.
472 pub status: RunStatus,
473 /// The run opened a pull request.
474 pub left_pr: bool,
475 /// At least one seat was lost to a rate limit.
476 pub quota_hit: bool,
477 /// The run parked at a node boundary because it was asked to.
478 pub parked: bool,
479}
480
481/// Record a finished run against the task it came from.
482///
483/// Kept pure and separate from the loop because this mapping *is* the retry
484/// policy, and a policy that can only be exercised by spawning a graph is a
485/// policy nobody checks. The table:
486///
487/// | run status | task becomes | attempt spent |
488/// |-------------------------|---------------------|---------------|
489/// | parked at a boundary | `Failed` (requeued) | **no** |
490/// | `Merged`, `Ready` | `Done` | yes |
491/// | `Stalled`, quota hit | `Failed` (requeued) | **no** |
492/// | `Stalled`, no quota | `Failed`, or `Held` | yes |
493/// | `Blocked` with a PR | `Held` | yes |
494/// | `Blocked`, `Failed` | `Failed`, or `Held` | yes |
495/// | anything non-terminal | `Failed`, or `Held` | yes |
496///
497/// The two `Stalled` rows are the ones worth reading twice. A quorum lost to
498/// rate limits is a property of the machine and not of the task, so the
499/// attempt is refunded and a reset quota picks the work up where it stopped.
500/// A quorum lost to judges that answered with the wrong shape is ordinary
501/// flakiness, and refunding *that* takes the bound off the retry loop
502/// entirely: run e633 stalled with `quota: []` after two judges wrote
503/// unusable JSON, was refunded, and the next attempt paid for a fresh
504/// hour-long implement wave before it could fail the same way. `max_attempts`
505/// exists precisely so that cannot repeat forever.
506///
507/// A non-terminal status means `execute` returned while the graph was still
508/// mid-flight, which is a bug rather than a verdict; it is treated as a
509/// failure so that a task cannot loop on it either.
510///
511/// `left_pr` splits the `Blocked` row, and it is the difference between a run
512/// that failed and a run that finished into a gate. See [`Task::handed_off`].
513pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
514 // A parked run is the operator's own doing, and its work is intact on
515 // disk. The task goes back in line with its attempt refunded so the next
516 // loop resumes the same run - which `one_task` prefers over competing
517 // again - and so that swapping the binary a few times cannot exhaust a
518 // budget meant for agents that actually misbehaved.
519 if verdict.parked {
520 task.stall(detail);
521 return;
522 }
523 match verdict.status {
524 RunStatus::Merged | RunStatus::Ready => task.succeed(),
525 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
526 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
527 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
528 RunStatus::Blocked => task.fail(detail, max_attempts),
529 other => task.fail(
530 format!(
531 "the graph stopped at `{}` without reaching a terminal status: {detail}",
532 label(other)
533 ),
534 max_attempts,
535 ),
536 }
537}
538
539/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
540/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
541/// by some other means entirely, like a manual `magi run` resume that
542/// finishes the graph outside the queue's bookkeeping.
543///
544/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
545/// `settle` is separate from `attempt`: a task recovered this way must land
546/// exactly where a live daemon would have put it — the same policy table,
547/// not a second one that quietly drifts from it — and that is only checkable
548/// without spawning a real run.
549fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
550 match last_run {
551 Some(state) => {
552 let verdict = Verdict {
553 status: state.status,
554 left_pr: state.pr.is_some(),
555 quota_hit: !state.quota.is_empty(),
556 parked: state.parked,
557 };
558 let detail = format!(
559 "recovered a `running` task whose daemon never recorded the outcome: {}",
560 describe(&state)
561 );
562 settle(task, verdict, &detail, max_attempts);
563 }
564 None => {
565 let why = "task was `running` with no live daemon and no readable \
566 run to recover; held for a human to check what happened";
567 task.last_error = Some(why.to_owned());
568 // The phone shows `hold_reason`, so a task held by the machine
569 // says why there too and not only in `last_error`.
570 task.hold(Some(why.to_owned()));
571 }
572 }
573}
574
575/// Find every task left at `running` that no live process is actually
576/// driving, and settle each one against whatever its last run became.
577///
578/// # Why a claim is proof, not a guess
579///
580/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
581/// `running`, and the guard is held for the task's whole time in that status:
582/// `attempt` does not return, and the loop does not move past the scope
583/// holding the claim, until the run has settled. So a `running` task whose
584/// lock is gone cannot have a live owner — this process or any other —
585/// without needing a staleness threshold or a pid check the way
586/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
587/// task that never got as far as `running` at all. Taking the claim here is
588/// the whole test: it either fails, because something really does hold it
589/// and the task is left alone, or it succeeds, which is the proof — and it is
590/// kept for the rest of the decision so nothing else can start a competing
591/// run while this one is being written.
592///
593/// Called on every poll, not only at startup, for the reason
594/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
595/// keep noticing this, not only on the one morning it happened to restart.
596fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
597 let mut reclaimed = Vec::new();
598 for listed in queue.list() {
599 if listed.status != TaskStatus::Running {
600 continue;
601 }
602 let Ok(_claim) = queue.claim(&listed.id) else {
603 continue;
604 };
605 // Re-read under the claim: a release or an edit landed by a human
606 // between the listing above and the claim just taken must not be
607 // clobbered by a decision based on the stale copy.
608 let Ok(mut task) = queue.get(&listed.id) else {
609 continue;
610 };
611 if task.status != TaskStatus::Running {
612 continue;
613 }
614 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
615 reclaim(&mut task, last_run, max_attempts);
616 record(queue, &mut task);
617 reclaimed.push(task.id.clone());
618 }
619 reclaimed
620}
621
622/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
623///
624/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
625/// sets, so there is one loop body rather than two that drift apart the first
626/// time the retry policy changes on only one of them.
627pub async fn serve(opts: Opts) -> Result<()> {
628 serve_until(opts, Stop::new()).await
629}
630
631/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
632///
633/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
634/// mid-node leaves worktrees, branches and agent sessions behind, and every
635/// agent call already paid for is lost; finishing the run costs the operator a
636/// wait and saves them a cleanup. A stop therefore only sets a flag: the
637/// current `execute` runs to its terminal status, the task's outcome is
638/// recorded, and only then does the loop return. That window is what
639/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
640/// still has a second Ctrl-C, which the runtime turns into a process kill —
641/// and the task left `Running` then tells the next daemon, and the next human,
642/// where to look.
643///
644/// While the queue is empty the stop is honoured within one wakeup rather than
645/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
646/// caller that taps stop does not sit through the remainder of a sleep.
647pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
648 let signal = {
649 let stop = stop.clone();
650 tokio::spawn(async move {
651 if tokio::signal::ctrl_c().await.is_ok() {
652 stop.stop();
653 tracing::info!("shutdown requested; a run in flight will be finished first");
654 }
655 })
656 };
657
658 let outcome = drive(
659 &opts,
660 &Queue::open(),
661 &status_path(),
662 &crate::run::home(),
663 &stop,
664 )
665 .await;
666
667 signal.abort();
668 outcome
669}
670
671/// The loop proper: setup, poll, teardown, with the queue and the status file
672/// supplied rather than discovered.
673///
674/// Both are parameters because [`crate::run::home`] is process-global and its
675/// override is a `OnceLock`, so a unit test that pinned it would fight every
676/// other test in the binary — and a loop that resolved the home itself could
677/// only be exercised against the operator's real one, publishing over a live
678/// daemon's status file and claiming tasks out of a live backlog.
679async fn drive(
680 opts: &Opts,
681 queue: &Queue,
682 status_file: &Path,
683 home: &Path,
684 stop: &Stop,
685) -> Result<()> {
686 janitor(&opts.repo, opts, home).await;
687
688 // The status file is a *snapshot*, not a stream of events: a reader only
689 // ever wants the latest values, and every tick rewrites the whole file
690 // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
691 // while an mpsc channel would force the loop to re-send unchanged fields on
692 // every heartbeat — or the heartbeat to keep its own shadow copy of them —
693 // for no gain. The lock is only ever held across a field assignment, never
694 // across an await.
695 let status = Arc::new(Mutex::new(Status::new()));
696 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
697 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
698
699 tracing::info!(
700 "magi serve: queue {} (poll {}s, {} attempts per task, one run at a time)",
701 queue.root().display(),
702 opts.poll.as_secs(),
703 opts.max_attempts
704 );
705
706 let outcome = poll(opts, queue, &status, home, stop).await;
707
708 beat.abort();
709 clear_status_at(status_file);
710 outcome
711}
712
713/// Refresh the status file on a fixed tick.
714///
715/// Separate from the loop because a run takes tens of minutes: a status file
716/// written only between tasks would look stale for the whole of every run, and
717/// a reader would report the daemon dead exactly while it was busiest.
718async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
719 loop {
720 tokio::time::sleep(HEARTBEAT).await;
721 let snapshot = {
722 let mut guard = lock(&status);
723 guard.updated_at = Timestamp::now();
724 guard.clone()
725 };
726 if let Err(e) = write_status_to(&path, &snapshot) {
727 // A failed heartbeat must not take the daemon down: the loop is the
728 // product, the status file is only the window onto it.
729 tracing::warn!("could not refresh the daemon status file: {e:#}");
730 }
731 }
732}
733
734/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
735/// teardown and cannot skip the teardown on an early return.
736async fn poll(
737 opts: &Opts,
738 queue: &Queue,
739 status: &Arc<Mutex<Status>>,
740 home: &Path,
741 stop: &Stop,
742) -> Result<()> {
743 // Only consulted by `once`, where a task that just failed is still
744 // `runnable` and would otherwise be picked up again inside the same drain.
745 // In the long-running mode a later poll retrying a failed task is the point,
746 // and the attempt counter is what bounds it.
747 let mut attempted: Vec<String> = Vec::new();
748
749 while !stop.stopped() {
750 lock(status).polls += 1;
751
752 let swept = sweep_stale_claims(queue, STALE_CLAIM);
753 if !swept.is_empty() {
754 tracing::warn!(
755 "swept {} stale claim(s) left behind by an earlier daemon: {}",
756 swept.len(),
757 swept.join(", ")
758 );
759 }
760 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
761 if !reclaimed.is_empty() {
762 tracing::warn!(
763 "reclaimed {} task(s) left `running` by a daemon that never \
764 recorded the outcome: {}",
765 reclaimed.len(),
766 reclaimed.join(", ")
767 );
768 }
769
770 let candidates: Vec<Task> = runnable(queue)
771 .into_iter()
772 .filter(|t| !opts.once || !attempted.contains(&t.id))
773 .collect();
774
775 let mut ran = false;
776 for candidate in candidates {
777 if stop.stopped() {
778 break;
779 }
780 // A claim we cannot take means another daemon, or a human running
781 // `magi run`, got there first. That is not the task's fault and
782 // must not spend one of its attempts: move to the next candidate
783 // rather than recording a failure.
784 let Ok(_claim) = queue.claim(&candidate.id) else {
785 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
786 continue;
787 };
788 // Re-read under the claim: the task on disk may have been held or
789 // edited between the listing and the lock.
790 let mut task = match queue.get(&candidate.id) {
791 Ok(t) if t.status.runnable() => t,
792 Ok(_) => continue,
793 Err(e) => {
794 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
795 continue;
796 }
797 };
798 attempted.push(task.id.clone());
799 lock(status).idle = false;
800 // A stop asked for from here on is "finishing", not "stopped": the
801 // run gets to reach a terminal status before the loop returns.
802 stop.busy(true);
803 attempt(opts, queue, status, stop, &mut task).await;
804 stop.busy(false);
805 // A task just ended: the disk is quiet, so it is the idle point for
806 // the janitor. Folding worktrees and pruning a cache mid-build
807 // would race the very compile the prune exists to keep.
808 janitor(&opts.repo, opts, home).await;
809 {
810 let mut guard = lock(status);
811 guard.current = None;
812 guard.completed += 1;
813 }
814 ran = true;
815 break;
816 }
817
818 if ran {
819 continue;
820 }
821
822 lock(status).idle = true;
823 if opts.once {
824 return Ok(());
825 }
826 stop.idle(opts.poll).await;
827 }
828 Ok(())
829}
830
831/// Run one claimed task to a terminal status and record the outcome.
832///
833/// Every transition is flushed to the queue as it happens, so the state on disk
834/// is what actually occurred rather than what this process still intends to
835/// write.
836async fn attempt(
837 opts: &Opts,
838 queue: &Queue,
839 status: &Arc<Mutex<Status>>,
840 stop: &Stop,
841 task: &mut Task,
842) {
843 let repo = repo_for(task, &opts.repo);
844 tracing::info!(
845 "task {} — {} (repo {})",
846 task.short(),
847 task.title,
848 repo.display()
849 );
850
851 let mut config = match prepare(&repo, opts) {
852 Ok(c) => c,
853 Err(e) => {
854 // A setup failure spends an attempt even though no run was minted.
855 // Without that, a task naming a repository that does not exist
856 // would be retried at every poll for as long as the daemon lives.
857 task.attempts += 1;
858 task.fail(format!("config: {e:#}"), opts.max_attempts);
859 record(queue, task);
860 return;
861 }
862 };
863 apply_solo(&mut config, task);
864
865 // The free-space gate, checked *before* anything is minted: a task that
866 // waits out a full disk costs nothing yet, and must not spend an attempt
867 // or start a run the machine cannot finish. Held tasks stay in the list
868 // for the human to see, and `magi task release` re-queues them when space
869 // comes back - the same recovery as any other hold. A volume whose free
870 // space cannot be measured closes the gate too: starting a run blind on a
871 // disk that may be full is how the machine ends up with 6.7 GB free.
872 if let Some(reason) = disk_gate(&repo, &config) {
873 task.last_error = Some(reason.clone());
874 task.hold(Some(reason.clone()));
875 record(queue, task);
876 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
877 return;
878 }
879
880 // A resumable run of this task is carried on, never re-competed. The
881 // candidates are built and paid for, and a fresh competition races a
882 // second implementation against them.
883 //
884 // Two runs paid for that lesson. Run 01c2 was blocked and the loop
885 // started 3cbf on the same task a moment later, duplicating two and a
886 // half hours of agent work. Then b25f stalled on a judge that timed out
887 // and one that answered with no JSON - `quota: 0`, so nothing the machine
888 // was to blame for - and 4043 started **one second** later, buying three
889 // fresh implementations to reach the same panel. `RunStatus::resumable`
890 // rather than `!done()` is what catches the second case: a stall is
891 // terminal, and its cheap recovery re-asks only the absent seats.
892 let unfinished = task
893 .runs
894 .iter()
895 .rev()
896 .find(|id| {
897 RunState::load(id)
898 .map(|s| s.status.resumable())
899 .unwrap_or(false)
900 })
901 .cloned();
902 let started = match &unfinished {
903 Some(id) => {
904 tracing::info!("resuming run {id} rather than competing again");
905 Runner::resume(id)
906 }
907 None => Runner::start(&repo, task.instruction.clone(), config).await,
908 };
909 let mut runner = match started {
910 Ok(r) => r,
911 Err(e) => {
912 task.attempts += 1;
913 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
914 record(queue, task);
915 return;
916 }
917 };
918 // A stop that means "park" reaches the graph through this handle.
919 runner.on_pause(stop.pause());
920
921 // `start` has minted the run, so the task can now point at it. Persisting
922 // `Running` before `execute` is what makes a crash mid-run legible.
923 let run = runner.state.id.clone();
924 task.start(run.clone());
925 record(queue, task);
926 lock(status).current = Some(Current {
927 task: task.id.clone(),
928 run,
929 });
930
931 let detail = match runner.execute().await {
932 Ok(()) => describe(&runner.state),
933 Err(e) => format!("{e:#}"),
934 };
935 let verdict = Verdict {
936 status: runner.state.status,
937 // A run that opened a pull request handed its work over, whatever the
938 // gate then decided about merging it.
939 left_pr: runner.state.pr.is_some(),
940 // Only a rate limit earns the task its attempt back.
941 quota_hit: !runner.state.quota.is_empty(),
942 // A run that parked was asked to stop; that is not a failure and must
943 // not spend an attempt, or replacing the binary a few times would
944 // exhaust a task's budget without an agent ever misbehaving.
945 parked: runner.state.parked,
946 };
947 settle(task, verdict, &detail, opts.max_attempts);
948 record(queue, task);
949 tracing::info!(
950 "task {} is {} after run {} ({})",
951 task.short(),
952 task.status.as_str(),
953 runner.state.short(),
954 label(runner.state.status)
955 );
956}
957
958/// Cut this attempt's candidate count to one when the task asked to run
959/// alone.
960///
961/// Pure and separate from [`attempt`] so the one thing this feature changes -
962/// which `candidates` a `solo` task's run is built with - can be asserted
963/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
964/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
965/// value from the caller's own copy, so a repository's `magi.toml` on disk is
966/// never touched - only the `Config` this one attempt hands to `Runner::start`.
967fn apply_solo(config: &mut Config, task: &Task) {
968 if task.solo {
969 config.graph.candidates = 1;
970 }
971}
972
973/// Load the config for a task's repository, with the merge override applied.
974fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
975 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
976 if let Some(mode) = &opts.merge {
977 config.merge.mode = merge_mode(mode)?;
978 }
979 Ok(config)
980}
981
982/// The disk janitor, with its housekeeping logged rather than fatal.
983///
984/// Called only at the loop's idle points, for the reason the caller documents:
985/// a prune racing a live compile would delete files mid-build. The config is
986/// re-read on every call because the repository that just ran may not be the
987/// daemon's own default, and the cache directory is a repository fact.
988///
989/// `home` is a parameter rather than [`crate::run::home`] read here, for the
990/// same reason [`drive`] takes its queue and status file rather than
991/// resolving them: a test driving the loop must not reach through to the
992/// operator's real home just because the janitor runs on every idle tick.
993async fn janitor(repo: &Path, opts: &Opts, home: &Path) {
994 let cfg = match prepare(repo, opts) {
995 Ok(cfg) => cfg,
996 Err(e) => {
997 tracing::warn!("housekeep: no config: {e:#}");
998 return;
999 }
1000 };
1001 let out = clean::housekeep(
1002 &cfg,
1003 home,
1004 &crate::run::default_worktree_root(),
1005 Timestamp::now(),
1006 )
1007 .await;
1008 if out.folded > 0 {
1009 let unreadable = if out.unreadable > 0 {
1010 format!(" ({} unreadable)", out.unreadable)
1011 } else {
1012 String::new()
1013 };
1014 tracing::info!("housekeep: folded {} run(s){unreadable}", out.folded);
1015 }
1016 if out.cache_files > 0 {
1017 tracing::info!(
1018 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
1019 out.cache_files,
1020 out.cache_freed
1021 );
1022 }
1023}
1024
1025/// The free-space gate: what stands between this task and a new run, if
1026/// anything. `Some(reason)` holds the task; `None` lets it start.
1027///
1028/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
1029/// the operator opted out. A measurement failure is a gate, not a pass: both
1030/// sides of "cannot tell" are served by not starting.
1031fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
1032 let min = config.disk.min_free_bytes;
1033 if min == 0 {
1034 return None;
1035 }
1036 match crate::disk::free_bytes(repo) {
1037 Ok(free) => crate::disk::gate(free, min),
1038 Err(e) => Some(format!(
1039 "could not measure free space on {} ({e}); the disk gate refuses \
1040 to let a run start blind",
1041 repo.display()
1042 )),
1043 }
1044}
1045
1046/// Which repository a task runs in. A task that names none — the normal case
1047/// for one filed from a phone — runs in the daemon's own default.
1048fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
1049 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
1050 return fallback.to_path_buf();
1051 }
1052 task.repo.clone()
1053}
1054
1055/// Persist a transition. A queue write failure is logged rather than fatal: the
1056/// run already happened, and taking the daemon down would only add a lost
1057/// backlog to a full disk.
1058fn record(queue: &Queue, task: &mut Task) {
1059 if let Err(e) = queue.put(task) {
1060 tracing::error!("could not record task {}: {e:#}", task.short());
1061 }
1062}
1063
1064/// Every runnable task, in the order the loop should try them.
1065///
1066/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
1067/// tail exists so that a claim somebody else holds costs the loop the next
1068/// candidate rather than a whole poll interval of idleness.
1069fn runnable(queue: &Queue) -> Vec<Task> {
1070 let mut tasks: Vec<Task> = queue
1071 .list()
1072 .into_iter()
1073 .filter(|t| t.status.runnable())
1074 .collect();
1075 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
1076 tasks
1077}
1078
1079/// Why a run ended where it did, in one line, for [`Task::last_error`].
1080///
1081/// A stalled run names the seats the quota took out: "out of quota" is not
1082/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
1083/// agent to replace or which plan to top up.
1084fn describe(state: &RunState) -> String {
1085 let mut detail = if state.status == RunStatus::Stalled {
1086 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
1087 seats.sort_unstable();
1088 seats.dedup();
1089 if seats.is_empty() {
1090 "the judging panel lost its quorum".to_owned()
1091 } else {
1092 format!(
1093 "the judging panel lost its quorum; quota took out {}",
1094 seats.join(", ")
1095 )
1096 }
1097 } else {
1098 format!("run ended {}", label(state.status))
1099 };
1100 if let Some(last) = state.events.last() {
1101 detail.push_str(&format!(" ({}: {})", last.node, last.message));
1102 }
1103 detail.push_str(&format!(" [run {}]", state.id));
1104 detail
1105}
1106
1107/// Stable lower-case name for a run status, for logs and task errors.
1108/// One definition of a status's name, on the type that owns it: this table
1109/// used to live here as a second copy, and a status renamed in one place would
1110/// have gone on reading correctly in the other.
1111fn label(status: RunStatus) -> &'static str {
1112 status.as_str()
1113}
1114
1115/// Parse a merge mode override.
1116fn merge_mode(mode: &str) -> Result<MergeMode> {
1117 match mode {
1118 "none" => Ok(MergeMode::None),
1119 "local" => Ok(MergeMode::Local),
1120 "pr" => Ok(MergeMode::Pr),
1121 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
1122 }
1123}
1124
1125/// Take the status lock, recovering from a poisoned one.
1126///
1127/// A panic elsewhere must not silently stop the heartbeat: the status is plain
1128/// data, and the worst a poisoned lock can hold is a stale timestamp.
1129fn lock(status: &Mutex<Status>) -> MutexGuard<'_, Status> {
1130 status
1131 .lock()
1132 .unwrap_or_else(std::sync::PoisonError::into_inner)
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use super::*;
1138 use crate::queue::{Source, TaskStatus};
1139 use pretty_assertions::assert_eq;
1140
1141 fn task() -> Task {
1142 Task::new(
1143 "add retries".to_owned(),
1144 "add retries".to_owned(),
1145 PathBuf::from("/repo"),
1146 Source::Human,
1147 )
1148 }
1149
1150 #[test]
1151 fn every_run_status_settles_the_task_it_came_from() {
1152 // run status, resulting task status, attempts still standing after one
1153 let table = [
1154 (RunStatus::Merged, TaskStatus::Done, 1),
1155 (RunStatus::Ready, TaskStatus::Done, 1),
1156 (RunStatus::Stalled, TaskStatus::Failed, 0),
1157 (RunStatus::Blocked, TaskStatus::Failed, 1),
1158 (RunStatus::Failed, TaskStatus::Failed, 1),
1159 (RunStatus::Prep, TaskStatus::Failed, 1),
1160 (RunStatus::Implementing, TaskStatus::Failed, 1),
1161 (RunStatus::Judging, TaskStatus::Failed, 1),
1162 (RunStatus::Deliberating, TaskStatus::Failed, 1),
1163 (RunStatus::Voting, TaskStatus::Failed, 1),
1164 (RunStatus::Reviewing, TaskStatus::Failed, 1),
1165 (RunStatus::Gating, TaskStatus::Failed, 1),
1166 ];
1167 for (run, want, attempts) in table {
1168 let mut t = task();
1169 t.start("20260902-000000-aaaa".to_owned());
1170 settle(
1171 &mut t,
1172 Verdict {
1173 status: run,
1174 left_pr: false,
1175 parked: false,
1176 quota_hit: matches!(run, RunStatus::Stalled),
1177 },
1178 "why",
1179 2,
1180 );
1181 assert_eq!(t.status, want, "task status after {}", label(run));
1182 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
1183 }
1184 }
1185
1186 #[test]
1187 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
1188 let mut stalled = task();
1189 stalled.start("20260902-000000-aaaa".to_owned());
1190 settle(
1191 &mut stalled,
1192 Verdict {
1193 status: RunStatus::Stalled,
1194 left_pr: false,
1195 parked: false,
1196 quota_hit: true,
1197 },
1198 "quota",
1199 1,
1200 );
1201 assert_eq!(stalled.attempts, 0);
1202 assert!(
1203 stalled.status.runnable(),
1204 "a machine problem must leave the task in line"
1205 );
1206
1207 let mut blocked = task();
1208 blocked.start("20260902-000000-aaaa".to_owned());
1209 settle(
1210 &mut blocked,
1211 Verdict {
1212 status: RunStatus::Blocked,
1213 left_pr: false,
1214 parked: false,
1215 quota_hit: false,
1216 },
1217 "findings open",
1218 1,
1219 );
1220 assert_eq!(blocked.attempts, 1);
1221 assert_eq!(
1222 blocked.status,
1223 TaskStatus::Held,
1224 "the last attempt hands the task to a human"
1225 );
1226 }
1227
1228 #[test]
1229 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
1230 // Attempts to spare: without the pull request this task would go
1231 // straight back in line and run the whole competition again.
1232 let mut delivered = task();
1233 delivered.start("20260903-080619-01c2".to_owned());
1234 settle(
1235 &mut delivered,
1236 Verdict {
1237 status: RunStatus::Blocked,
1238 left_pr: true,
1239 parked: false,
1240 quota_hit: false,
1241 },
1242 "no check status",
1243 4,
1244 );
1245 assert_eq!(
1246 delivered.status,
1247 TaskStatus::Held,
1248 "a pull request waiting on CI or a person is not a retryable failure"
1249 );
1250 assert!(
1251 !delivered.status.runnable(),
1252 "the loop must not pick this task up again"
1253 );
1254 assert_eq!(
1255 delivered.last_error.as_deref(),
1256 Some("no check status"),
1257 "the operator needs to be told what the gate was waiting for"
1258 );
1259
1260 // The same status without a pull request is a plain failure, and with
1261 // attempts left it is retried.
1262 let mut empty_handed = task();
1263 empty_handed.start("20260903-080619-01c2".to_owned());
1264 settle(
1265 &mut empty_handed,
1266 Verdict {
1267 status: RunStatus::Blocked,
1268 left_pr: false,
1269 parked: false,
1270 quota_hit: false,
1271 },
1272 "findings open",
1273 4,
1274 );
1275 assert_eq!(empty_handed.status, TaskStatus::Failed);
1276 assert!(empty_handed.status.runnable());
1277 }
1278
1279 #[test]
1280 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
1281 // Parking is the operator asking for the process back - to replace the
1282 // binary, most of all. The run's work is intact on disk, so this is
1283 // not a failed attempt, and charging for it would mean a few upgrades
1284 // could exhaust a budget meant for agents that misbehaved.
1285 let mut parked = task();
1286 parked.start("20260903-183634-2d98".to_owned());
1287 settle(
1288 &mut parked,
1289 Verdict {
1290 status: RunStatus::Implementing,
1291 left_pr: false,
1292 quota_hit: false,
1293 parked: true,
1294 },
1295 "parked after `implementing`",
1296 2,
1297 );
1298 assert_eq!(parked.attempts, 0, "a park is refunded");
1299 assert!(
1300 parked.status.runnable(),
1301 "and the task stays in line so the next loop resumes its run"
1302 );
1303 assert_eq!(
1304 parked.last_error.as_deref(),
1305 Some("parked after `implementing`"),
1306 "the card says where it stopped"
1307 );
1308
1309 // Without the park flag the same non-terminal status is what it always
1310 // was: `execute` returning mid-flight, which is a bug and spends an
1311 // attempt so a task cannot loop on it forever.
1312 let mut broken = task();
1313 broken.start("20260903-183634-2d98".to_owned());
1314 settle(
1315 &mut broken,
1316 Verdict {
1317 status: RunStatus::Implementing,
1318 left_pr: false,
1319 quota_hit: false,
1320 parked: false,
1321 },
1322 "returned mid-flight",
1323 2,
1324 );
1325 assert_eq!(broken.attempts, 1);
1326 }
1327
1328 #[test]
1329 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
1330 // Run e633: quorum lost because two judges answered with the wrong
1331 // JSON shape, `quota: []`. Refunding that takes the bound off the
1332 // retry loop, and each retry pays for a fresh hour-long implement
1333 // wave before it can fail the same way.
1334 let mut flaky = task();
1335 flaky.start("20260903-123023-e633".to_owned());
1336 settle(
1337 &mut flaky,
1338 Verdict {
1339 status: RunStatus::Stalled,
1340 left_pr: false,
1341 parked: false,
1342 quota_hit: false,
1343 },
1344 "verdict rests on 1 of 3 judges",
1345 2,
1346 );
1347 assert_eq!(
1348 flaky.attempts, 1,
1349 "flakiness spends an attempt, so `max_attempts` still bounds it"
1350 );
1351 assert!(flaky.status.runnable(), "and it is still worth retrying");
1352
1353 // The same status, lost to a rate limit, is the machine's fault.
1354 let mut limited = task();
1355 limited.start("20260903-123023-e633".to_owned());
1356 settle(
1357 &mut limited,
1358 Verdict {
1359 status: RunStatus::Stalled,
1360 left_pr: false,
1361 parked: false,
1362 quota_hit: true,
1363 },
1364 "judge-2, judge-3 out of quota",
1365 2,
1366 );
1367 assert_eq!(limited.attempts, 0, "a quota window is refunded");
1368 assert!(limited.status.runnable());
1369
1370 // And the bound really binds: a task that keeps stalling on flakiness
1371 // reaches a human instead of running the roster forever.
1372 let mut worn = task();
1373 for _ in 0..2 {
1374 worn.release();
1375 }
1376 worn.start("20260903-123023-e633".to_owned());
1377 worn.attempts = 2;
1378 settle(
1379 &mut worn,
1380 Verdict {
1381 status: RunStatus::Stalled,
1382 left_pr: false,
1383 parked: false,
1384 quota_hit: false,
1385 },
1386 "no quorum again",
1387 2,
1388 );
1389 assert_eq!(worn.status, TaskStatus::Held);
1390 assert!(!worn.status.runnable());
1391 }
1392
1393 #[test]
1394 fn a_held_task_is_never_offered_to_the_loop() {
1395 let dir = tempfile::tempdir().unwrap();
1396 let queue = Queue::at(dir.path().to_path_buf());
1397 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
1398 let mut t = task();
1399 t.id = format!("2026090{n}-000000-000{n}");
1400 t.priority = priority;
1401 queue.put(&mut t).unwrap();
1402 }
1403 let mut held = task();
1404 held.id = "20260909-000000-9999".to_owned();
1405 held.priority = 99;
1406 held.hold(None);
1407 queue.put(&mut held).unwrap();
1408
1409 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
1410 assert_eq!(order.len(), 3);
1411 assert!(!order.contains(&held.id));
1412 assert_eq!(
1413 order.first().cloned(),
1414 queue.next_runnable().map(|t| t.id),
1415 "the loop's first candidate is exactly what the queue offers"
1416 );
1417 assert_eq!(
1418 order,
1419 vec![
1420 "20260902-000000-0002".to_owned(),
1421 "20260903-000000-0003".to_owned(),
1422 "20260901-000000-0001".to_owned(),
1423 ],
1424 "priority first, then oldest, so nothing starves"
1425 );
1426 }
1427
1428 #[test]
1429 fn sweep_removes_an_abandoned_lock_and_keeps_a_live_one() {
1430 let dir = tempfile::tempdir().unwrap();
1431 let queue = Queue::at(dir.path().to_path_buf());
1432 let mut old = task();
1433 old.id = "20260101-000000-old0".to_owned();
1434 queue.put(&mut old).unwrap();
1435 let mut fresh = task();
1436 fresh.id = "20260101-000000-new0".to_owned();
1437 queue.put(&mut fresh).unwrap();
1438
1439 let abandoned = queue.claim(&old.id).unwrap();
1440 std::thread::sleep(Duration::from_millis(60));
1441 let live = queue.claim(&fresh.id).unwrap();
1442
1443 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
1444 assert_eq!(swept, vec![old.id.clone()]);
1445 assert!(
1446 queue.claim(&old.id).is_ok(),
1447 "a swept task is claimable again"
1448 );
1449 assert!(
1450 queue.claim(&fresh.id).is_err(),
1451 "a lock younger than the threshold still protects its task"
1452 );
1453 drop((abandoned, live));
1454 }
1455
1456 fn run_state(status: RunStatus) -> RunState {
1457 let mut state = RunState::new(
1458 PathBuf::from("/repo"),
1459 "main".to_owned(),
1460 "abc1234def".to_owned(),
1461 "add retries".to_owned(),
1462 Config::default(),
1463 );
1464 state.status = status;
1465 state
1466 }
1467
1468 #[test]
1469 fn reclaim_settles_a_running_task_against_its_last_run() {
1470 let mut t = task();
1471 t.start("20260904-000000-4043".to_owned());
1472 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
1473 assert_eq!(
1474 t.status,
1475 TaskStatus::Done,
1476 "a run that actually finished must not stay `running` forever"
1477 );
1478 }
1479
1480 #[test]
1481 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
1482 // A blocked run with attempts left goes back to `Failed`, exactly as
1483 // it would from `attempt` itself - `reclaim` must not invent a second
1484 // policy for a task a daemon merely stopped without reporting.
1485 let mut t = task();
1486 t.start("20260904-000000-4043".to_owned());
1487 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
1488 assert_eq!(t.status, TaskStatus::Failed);
1489 assert!(t.status.runnable());
1490 }
1491
1492 #[test]
1493 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
1494 let mut t = task();
1495 t.start("20260904-000000-4043".to_owned());
1496 reclaim(&mut t, None, 2);
1497 assert_eq!(t.status, TaskStatus::Held);
1498 assert!(
1499 t.last_error
1500 .as_deref()
1501 .is_some_and(|e| e.contains("running")),
1502 "the operator needs to know why this task was held"
1503 );
1504 }
1505
1506 #[test]
1507 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
1508 let dir = tempfile::tempdir().unwrap();
1509 let queue = Queue::at(dir.path().to_path_buf());
1510
1511 // No run recorded, so this never has to touch `RunState::load`.
1512 let mut orphaned = task();
1513 orphaned.id = "20260904-000000-orph".to_owned();
1514 orphaned.status = TaskStatus::Running;
1515 orphaned.attempts = 1;
1516 queue.put(&mut orphaned).unwrap();
1517
1518 let mut alive = task();
1519 alive.id = "20260904-000000-live".to_owned();
1520 alive.status = TaskStatus::Running;
1521 alive.attempts = 1;
1522 queue.put(&mut alive).unwrap();
1523 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
1524
1525 let mut queued = task();
1526 queued.id = "20260904-000000-wait".to_owned();
1527 queue.put(&mut queued).unwrap();
1528
1529 let reclaimed = reclaim_orphaned_running(&queue, 2);
1530 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
1531
1532 assert_eq!(
1533 queue.get(&orphaned.id).unwrap().status,
1534 TaskStatus::Held,
1535 "nothing was driving it and there was no run to recover"
1536 );
1537 assert_eq!(
1538 queue.get(&alive.id).unwrap().status,
1539 TaskStatus::Running,
1540 "a live claim must protect the task it belongs to"
1541 );
1542 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
1543 }
1544
1545 #[test]
1546 fn an_already_claimed_task_is_skipped_rather_than_failed() {
1547 let dir = tempfile::tempdir().unwrap();
1548 let queue = Queue::at(dir.path().to_path_buf());
1549 let mut only = task();
1550 queue.put(&mut only).unwrap();
1551
1552 let _elsewhere = queue.claim(&only.id).unwrap();
1553 let candidates = runnable(&queue);
1554 assert_eq!(candidates.len(), 1, "the task is still runnable");
1555 assert!(
1556 queue.claim(&candidates[0].id).is_err(),
1557 "the loop cannot take a claim somebody else holds"
1558 );
1559
1560 let after = queue.get(&only.id).unwrap();
1561 assert_eq!(after.status, TaskStatus::Queued);
1562 assert_eq!(
1563 after.attempts, 0,
1564 "losing the race is not an attempt at the task"
1565 );
1566 assert_eq!(after.last_error, None);
1567 }
1568
1569 #[test]
1570 fn the_status_file_round_trips_and_its_heartbeat_advances() {
1571 let dir = tempfile::tempdir().unwrap();
1572 let path = dir.path().join("daemon.json");
1573
1574 let mut status = Status::new();
1575 status.idle = false;
1576 status.completed = 7;
1577 status.current = Some(Current {
1578 task: "20260902-000000-t111".to_owned(),
1579 run: "20260902-000001-r111".to_owned(),
1580 });
1581 write_status_to(&path, &status).unwrap();
1582 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1583 assert_eq!(first.schema, SCHEMA);
1584 assert_eq!(first.pid, std::process::id());
1585 assert!(!first.idle);
1586 assert_eq!(first.completed, 7);
1587 assert_eq!(first.current, status.current);
1588 assert!(
1589 !path.with_extension("json.tmp").exists(),
1590 "the temp file is renamed, not left behind"
1591 );
1592
1593 std::thread::sleep(Duration::from_millis(5));
1594 status.updated_at = Timestamp::now();
1595 status.polls = 3;
1596 write_status_to(&path, &status).unwrap();
1597 let second: Status =
1598 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1599 assert!(
1600 second.updated_at > first.updated_at,
1601 "a reader can only detect staleness if the heartbeat moves"
1602 );
1603 assert_eq!(
1604 second.started_at, first.started_at,
1605 "the start time is not a heartbeat"
1606 );
1607 assert_eq!(second.polls, 3);
1608 }
1609
1610 #[test]
1611 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
1612 let dir = tempfile::tempdir().unwrap();
1613
1614 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
1615
1616 let mut status = Status::new();
1617 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
1618 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1619 let stale = read_status(dir.path()).unwrap();
1620 assert!(
1621 !stale.running(Timestamp::now()),
1622 "a minute without a heartbeat is a dead daemon, not a busy one"
1623 );
1624 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
1625
1626 status.updated_at = Timestamp::now();
1627 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1628 let fresh = read_status(dir.path()).unwrap();
1629 assert!(fresh.running(Timestamp::now()));
1630 }
1631
1632 #[test]
1633 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
1634 let dir = tempfile::tempdir().unwrap();
1635 let now = Timestamp::now();
1636 let mine = "20260903-080619-01c2";
1637
1638 assert!(
1639 !is_working_on(dir.path(), mine, now),
1640 "no status file means nobody is working on anything"
1641 );
1642
1643 let mut status = Status::new();
1644 status.current = Some(Current {
1645 task: "20260903-080340-0167".to_owned(),
1646 run: mine.to_owned(),
1647 });
1648 status.updated_at = now;
1649 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1650 assert!(is_working_on(dir.path(), mine, now));
1651 assert!(
1652 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
1653 "a daemon busy with one run is not working on another"
1654 );
1655
1656 // A killed daemon stops writing heartbeats but leaves the file behind
1657 // naming the run it died in. That run must not be undeletable forever.
1658 status.updated_at = now - jiff::SignedDuration::from_secs(600);
1659 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1660 assert!(
1661 !is_working_on(dir.path(), mine, now),
1662 "a stale heartbeat is a dead daemon, so its run is a leftover"
1663 );
1664 }
1665
1666 #[test]
1667 fn a_newer_status_file_still_yields_a_reading() {
1668 let dir = tempfile::tempdir().unwrap();
1669 // A field this build has never heard of must not turn the reading into
1670 // nothing at all; that is the whole reason the reader is permissive.
1671 std::fs::write(
1672 dir.path().join("daemon.json"),
1673 serde_json::json!({
1674 "schema": 2,
1675 "updated_at": Timestamp::now().to_string(),
1676 "idle": true,
1677 "surprise": { "nested": [1, 2, 3] },
1678 })
1679 .to_string(),
1680 )
1681 .unwrap();
1682
1683 let reading = read_status(dir.path()).expect("a forward-compatible read");
1684 assert!(reading.running(Timestamp::now()));
1685 assert!(reading.idle);
1686 assert_eq!(reading.current, None);
1687 }
1688
1689 #[test]
1690 fn a_task_without_a_repository_runs_in_the_daemons_default() {
1691 let fallback = Path::new("/default");
1692 let mut blank = task();
1693 blank.repo = PathBuf::new();
1694 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
1695 let mut dot = task();
1696 dot.repo = PathBuf::from(".");
1697 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
1698 assert_eq!(
1699 repo_for(&task(), fallback),
1700 PathBuf::from("/repo"),
1701 "a task that names a repository keeps it"
1702 );
1703 }
1704
1705 #[test]
1706 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
1707 // Three seats said out loud. What `solo` promises is one candidate
1708 // *whatever the config asks for*, so the contrast has to be a number
1709 // this test owns - it used to be `Config::default()`'s, which became
1710 // 1 when one implementation became the default and left the two
1711 // halves of this test asserting the same thing.
1712 let mut solo_cfg = Config::default();
1713 solo_cfg.graph.candidates = 3;
1714 let mut solo_task = task();
1715 solo_task.solo = true;
1716 apply_solo(&mut solo_cfg, &solo_task);
1717 assert_eq!(solo_cfg.graph.candidates, 1);
1718
1719 let mut plain_cfg = Config::default();
1720 plain_cfg.graph.candidates = 3;
1721 let plain_task = task();
1722 assert!(!plain_task.solo);
1723 apply_solo(&mut plain_cfg, &plain_task);
1724 assert_eq!(
1725 plain_cfg.graph.candidates, 3,
1726 "a task that did not ask to run alone keeps the config's candidates"
1727 );
1728 }
1729
1730 #[test]
1731 fn merge_overrides_are_parsed_or_refused() {
1732 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
1733 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
1734 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
1735 assert!(merge_mode("squash").is_err());
1736 }
1737
1738 /// A loop whose queue lives in a temp tree and whose poll interval is far
1739 /// longer than the test's patience, so anything that waits out a poll
1740 /// instead of noticing the stop fails rather than merely being slow.
1741 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf) {
1742 let opts = Opts {
1743 poll: Duration::from_secs(30),
1744 ..Opts::default()
1745 };
1746 // The status file goes in a directory that does not exist yet, so its
1747 // creation is itself evidence the loop published one.
1748 let home = dir.join("home");
1749 (
1750 opts,
1751 Queue::at(dir.join("queue")),
1752 home.join("daemon.json"),
1753 home,
1754 )
1755 }
1756
1757 #[test]
1758 fn a_stop_is_idempotent_and_once_set_stays_set() {
1759 let stop = Stop::new();
1760 assert!(!stop.stopped());
1761
1762 stop.stop();
1763 assert!(stop.stopped());
1764 stop.stop();
1765 assert!(stop.stopped(), "a second stop is not a toggle");
1766
1767 let shared = stop.clone();
1768 assert!(
1769 shared.stopped(),
1770 "a clone is the same stop; that is how the loop and its caller share one"
1771 );
1772 }
1773
1774 #[test]
1775 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
1776 let stop = Stop::new();
1777 stop.busy(true);
1778 assert!(
1779 !stop.finishing(),
1780 "a busy loop nobody has asked to stop is just running"
1781 );
1782
1783 stop.stop();
1784 assert!(
1785 stop.finishing(),
1786 "a stop asked for mid-run has not landed until the run is settled"
1787 );
1788
1789 stop.busy(false);
1790 assert!(
1791 !stop.finishing(),
1792 "once the run is settled the stop has landed and there is nothing to finish"
1793 );
1794 }
1795
1796 #[tokio::test]
1797 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
1798 let dir = tempfile::tempdir().unwrap();
1799 let (opts, queue, status_file, home) = idle_loop(dir.path());
1800 let stop = Stop::new();
1801 stop.stop();
1802
1803 let began = std::time::Instant::now();
1804 tokio::time::timeout(
1805 Duration::from_secs(2),
1806 drive(&opts, &queue, &status_file, &home, &stop),
1807 )
1808 .await
1809 .expect("a stopped loop must return, not sit out its poll interval")
1810 .expect("the loop's own setup and teardown must not fail");
1811 assert!(
1812 began.elapsed() < opts.poll,
1813 "returned only after {:?}, which is a poll interval, not a stop",
1814 began.elapsed()
1815 );
1816 }
1817
1818 #[tokio::test]
1819 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
1820 let dir = tempfile::tempdir().unwrap();
1821 let (opts, queue, status_file, home) = idle_loop(dir.path());
1822 let stop = Stop::new();
1823
1824 // Asked for after the loop is already parked on its empty queue, which
1825 // is the case an operator tapping stop on a phone actually hits.
1826 let asker = {
1827 let stop = stop.clone();
1828 tokio::spawn(async move {
1829 tokio::time::sleep(Duration::from_millis(20)).await;
1830 stop.stop();
1831 })
1832 };
1833
1834 let began = std::time::Instant::now();
1835 tokio::time::timeout(
1836 Duration::from_secs(2),
1837 drive(&opts, &queue, &status_file, &home, &stop),
1838 )
1839 .await
1840 .expect("a stop asked for while idle must wake the wait")
1841 .expect("the loop's own setup and teardown must not fail");
1842 asker.await.unwrap();
1843 assert!(
1844 began.elapsed() < opts.poll,
1845 "returned only after {:?}, so the stop waited on the sleep",
1846 began.elapsed()
1847 );
1848 }
1849
1850 #[tokio::test]
1851 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
1852 let dir = tempfile::tempdir().unwrap();
1853 let (opts, queue, status_file, home) = idle_loop(dir.path());
1854 let stop = Stop::new();
1855 stop.stop();
1856
1857 tokio::time::timeout(
1858 Duration::from_secs(2),
1859 drive(&opts, &queue, &status_file, &home, &stop),
1860 )
1861 .await
1862 .expect("a stopped loop must return")
1863 .expect("the loop's own setup and teardown must not fail");
1864
1865 assert!(
1866 home.is_dir(),
1867 "the loop did publish a status file, so its removal is the teardown and not an absence"
1868 );
1869 assert!(
1870 !status_file.exists(),
1871 "a stopped loop clears its status file"
1872 );
1873 assert!(
1874 read_status(&home).is_none(),
1875 "a reader must see no daemon at all, not a heartbeat that merely stopped"
1876 );
1877 }
1878}