1use std::path::{Path, PathBuf};
19use std::time::{Duration, Instant};
20
21use anyhow::{Context, Result, bail};
22use jiff::Timestamp;
23
24use crate::config::Config;
25use crate::queue::{Claim, Queue, RunOverrides, Source, Task, TaskStatus};
26
27#[derive(Debug, Clone)]
31pub struct Filing {
32 pub instruction: String,
34 pub title: String,
36 pub repo: PathBuf,
38 pub source: Source,
40 pub issue: Option<crate::queue::IssueRef>,
42 pub solo: bool,
44 pub overrides: RunOverrides,
46 pub review_of: Option<String>,
48 pub sources: crate::refs::Sources,
50}
51
52impl Filing {
53 fn into_task(self) -> Task {
54 let mut task = Task::new(self.title, self.instruction, self.repo, self.source);
55 task.issue = self.issue;
56 task.sources = self.sources;
57 task.solo = self.solo;
58 task.review_of = self.review_of;
59 let mut overrides = self.overrides;
60 overrides.inherit_daemon_options = false;
61 task.overrides = Some(overrides);
62 task
63 }
64}
65
66#[derive(Debug)]
68pub enum Filed {
69 Daemon {
72 task: Task,
74 pid: Option<u32>,
76 },
77 Standalone {
80 task: Task,
82 claim: Claim,
84 },
85}
86
87pub fn file(
92 queue: &Queue,
93 home: &Path,
94 now: Timestamp,
95 own_pid: u32,
96 filing: Filing,
97 force_local: bool,
98) -> Result<Filed> {
99 let mut task = filing.into_task();
100 let owner = if force_local {
101 None
102 } else {
103 crate::daemon::foreign_loop(crate::daemon::read_status(home).as_ref(), now, own_pid)
104 };
105 match owner {
106 Some(pid) => {
107 task.urgent = true;
108 queue.put(&mut task).context("file the task")?;
109 Ok(Filed::Daemon { task, pid })
110 }
111 None => {
112 let claim = queue.file_claimed(&mut task).context("file the task")?;
115 Ok(Filed::Standalone { task, claim })
116 }
117 }
118}
119
120pub fn config_for(task: &Task, repo: &Path) -> Result<Config> {
123 let path = task.overrides.as_ref().and_then(|o| o.config.as_deref());
124 let (mut cfg, _) = Config::discover(repo, path)?;
125 if let Some(o) = &task.overrides {
126 o.apply(&mut cfg);
127 }
128 if let Some((mode, _)) = task.build_cache_override(&cfg) {
129 cfg.verify.build_cache = mode;
130 }
131 if task.solo {
132 cfg.graph.implementers = 1;
133 }
134 Ok(cfg)
135}
136
137#[derive(Debug)]
139pub struct Followed {
140 pub task: Task,
142 pub finished: bool,
145}
146
147impl Followed {
148 pub fn unfinished(&self) -> Option<anyhow::Error> {
152 if self.finished {
153 return None;
154 }
155 Some(anyhow::anyhow!(
156 "task {id} has not finished: it is still running under the loop. \
157 This is not a success; the outcome is not known yet. Read it with \
158 `magi task show {id}`. The loop keeps the task, so do not run it again.",
159 id = self.task.short()
160 ))
161 }
162}
163
164pub async fn follow(
175 queue: &Queue,
176 home: &Path,
177 id: &str,
178 poll: Duration,
179 max_wait: Option<Duration>,
180 mut seen: impl FnMut(&str),
181 mut progress: impl FnMut(&str),
182) -> Result<Followed> {
183 let began = Instant::now();
184 let mut announced = 0usize;
185 let mut last_status = String::new();
186 loop {
187 let task = queue.get(id)?;
188 for run in task.runs.iter().skip(announced) {
189 seen(run);
190 }
191 announced = task.runs.len();
192 if let Some(run) = task.runs.last()
193 && crate::run::try_home().is_some()
194 && let Ok(state) = crate::run::RunState::load(run)
195 {
196 let line = format!("run {}: {}", state.short(), state.status.as_str());
197 if line != last_status {
198 progress(&line);
199 last_status = line;
200 }
201 }
202 if matches!(
203 task.status,
204 TaskStatus::Done | TaskStatus::Held | TaskStatus::Blocked
205 ) {
206 return Ok(Followed {
207 task,
208 finished: true,
209 });
210 }
211 let reading = crate::daemon::read_status(home);
212 if crate::daemon::foreign_loop(reading.as_ref(), Timestamp::now(), std::process::id())
213 .is_none()
214 && !crate::daemon::is_working_on_task(home, id, Timestamp::now())
215 {
216 bail!(
217 "no magi loop is serving the queue any more, and task {} is still {}; it was \
218 not taken over here (the loop may only be slow to heartbeat). Start `magi \
219 serve` to carry on, or follow it with `magi task show {}`",
220 task.short(),
221 task.status.as_str(),
222 task.short()
223 );
224 }
225 if max_wait.is_some_and(|m| began.elapsed() >= m) {
226 return Ok(Followed {
227 task,
228 finished: false,
229 });
230 }
231 tokio::time::sleep(poll).await;
232 }
233}
234
235#[must_use]
237pub fn resume_owner(queue: &Queue, run: &str) -> Option<Task> {
238 queue
239 .list()
240 .into_iter()
241 .find(|task| task.runs.iter().any(|id| id == run))
242}
243
244pub fn claim_resume_owner(
248 queue: &Queue,
249 run: &str,
250 instruction: &str,
251 repo: &Path,
252 source: Source,
253 sources: &crate::refs::Sources,
254) -> Result<(Task, Claim)> {
255 if let Some(listed) = resume_owner(queue, run) {
256 let claim = queue.claim(&listed.id)?;
257 let task = queue.get(&listed.id)?;
258 anyhow::ensure!(task.execution_run(run), "run queue owner changed");
259 return Ok((task, claim));
260 }
261 let mut task = Task::new(
262 crate::queue::title_from(instruction, 72),
263 instruction.to_owned(),
264 repo.to_path_buf(),
265 source,
266 );
267 task.sources = sources.clone();
268 task.link_run(run);
269 let claim = queue.file_claimed(&mut task)?;
270 Ok((task, claim))
271}
272
273#[derive(Debug)]
276pub struct Adopted {
277 queue: Queue,
278 task: Option<Task>,
281 claim: Option<Claim>,
282 quota_before: Vec<crate::run::QuotaLoss>,
283}
284
285pub fn adopt(
294 state: &crate::run::RunState,
295 parent_task: Option<&str>,
296) -> anyhow::Result<Option<Adopted>> {
297 if crate::run::try_home().is_none() {
298 return Ok(None);
299 }
300 adopt_in(Queue::open(), state, parent_task)
301}
302
303fn adopt_in(
304 queue: Queue,
305 state: &crate::run::RunState,
306 parent_task: Option<&str>,
307) -> anyhow::Result<Option<Adopted>> {
308 use anyhow::Context as _;
309 if let Some(parent) = parent_task
310 && let Ok(id) = queue.resolve_id(parent)
311 {
312 return Ok(match queue.claim(&id) {
314 Ok(claim) => {
315 let started = queue.get(&id).and_then(|mut task| {
316 if !(task.status.runnable() || task.status == TaskStatus::Held) {
324 return Ok(None);
325 }
326 task.start(state.id.clone());
327 queue.put(&mut task)?;
328 Ok(Some(task))
329 });
330 match started {
331 Ok(None) => {
332 drop(claim);
333 let _ = queue.link_run(&id, &state.id);
334 None
335 }
336 Ok(Some(task)) => Some(Adopted {
337 queue,
338 task: Some(task),
339 claim: Some(claim),
340 quota_before: state.quota.clone(),
341 }),
342 Err(e) => {
343 tracing::warn!("could not start task {id} for run {}: {e:#}", state.id);
344 drop(claim);
345 let _ = queue.link_run(&id, &state.id);
346 None
347 }
348 }
349 }
350 Err(e) => {
351 tracing::warn!("task {id} is claimed elsewhere ({e:#}); linking run only");
353 let _ = queue.link_run(&id, &state.id);
354 None
355 }
356 });
357 }
358 let mut task = Task::new(
359 crate::queue::title_from(&state.instruction, 72),
360 state.instruction.clone(),
361 state.repo.clone(),
362 Source::Human,
363 );
364 task.start(state.id.clone());
365 let claim = queue
366 .file_claimed(&mut task)
367 .with_context(|| format!("could not file a new task for run {}", state.id))?;
368 Ok(Some(Adopted {
369 queue,
370 task: Some(task),
371 claim: Some(claim),
372 quota_before: state.quota.clone(),
373 }))
374}
375
376impl Adopted {
377 pub fn finish(mut self, state: &crate::run::RunState, result: Result<()>) {
379 if let Some(task) = &mut self.task {
380 crate::daemon::finish_attempt(
381 crate::daemon::Opts::default().max_attempts,
382 &self.queue,
383 task,
384 state,
385 &self.quota_before,
386 result,
387 );
388 crate::daemon::hold_if_runnable(&self.queue, task);
389 }
390 drop(self.claim.take());
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397 use crate::daemon::Status;
398
399 fn filing(repo: &Path) -> Filing {
400 Filing {
401 instruction: "review the branch".to_owned(),
402 title: "review x".to_owned(),
403 repo: repo.to_path_buf(),
404 source: Source::Human,
405 issue: None,
406 solo: false,
407 overrides: RunOverrides {
408 merge: Some("none".to_owned()),
409 ..RunOverrides::default()
410 },
411 sources: Default::default(),
412 review_of: Some("feat/x".to_owned()),
413 }
414 }
415
416 fn heartbeat(home: &Path, pid: u32, age_secs: i64) {
417 let mut status = Status::new();
418 status.pid = pid;
419 status.updated_at = Timestamp::now()
420 .checked_sub(jiff::SignedDuration::from_secs(age_secs))
421 .unwrap();
422 crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
423 }
424
425 #[test]
426 fn explicit_sources_survive_filing_queue_storage_and_release() {
427 let dir = tempfile::tempdir().unwrap();
428 let queue = Queue::at(dir.path().join("queue"));
429 let mut direct = filing(dir.path());
430 direct.review_of = None;
431 direct.instruction = "Do not import the historical example abc1234".into();
432 direct.sources = crate::refs::Sources {
433 start_from: Some(crate::refs::Input {
434 token: "feature/selected".into(),
435 sha: "1".repeat(40),
436 provenance: crate::refs::Provenance::ExplicitCli,
437 }),
438 pick_commits: vec![crate::refs::Input {
439 token: "abc5678".into(),
440 sha: "2".repeat(40),
441 provenance: crate::refs::Provenance::ExplicitCli,
442 }],
443 };
444 let selected = direct.sources.clone();
445 let mut task = direct.into_task();
446 queue.put(&mut task).unwrap();
447 let mut restored = queue.get(&task.id).unwrap();
448 assert_eq!(restored.sources, selected);
449 restored.hold_manual(Some("retry preparation".into()));
450 restored.release_operator("test", None);
451 queue.put(&mut restored).unwrap();
452 assert_eq!(queue.get(&task.id).unwrap().sources, selected);
453 assert_eq!(restored.instruction, task.instruction);
454 }
455
456 #[test]
457 fn task_implementers_direct_filing_keeps_options_isolated() {
458 let dir = tempfile::tempdir().unwrap();
459 let mut direct = filing(dir.path());
460 direct.overrides.inherit_daemon_options = true;
461 let task = direct.into_task();
462 assert!(!task.overrides.unwrap().inherit_daemon_options);
463 }
464
465 #[test]
466 fn without_a_loop_the_task_is_claimed_before_anyone_else_can_take_it() {
467 let dir = tempfile::tempdir().unwrap();
468 let q = Queue::at(dir.path().join("queue"));
469 let filed = file(
470 &q,
471 dir.path(),
472 Timestamp::now(),
473 1,
474 filing(dir.path()),
475 false,
476 )
477 .unwrap();
478 let Filed::Standalone { task, claim } = filed else {
479 panic!("no loop is alive");
480 };
481 assert!(!task.urgent);
482 assert_eq!(task.review_of.as_deref(), Some("feat/x"));
483 assert_eq!(
484 task.overrides.as_ref().unwrap().merge.as_deref(),
485 Some("none")
486 );
487 assert!(
488 q.claim(&task.id).is_err(),
489 "a second process must not be able to claim a standalone run's task"
490 );
491 drop(claim);
492 assert!(q.claim(&task.id).is_ok(), "released with the claim");
493 }
494
495 #[test]
496 fn a_live_foreign_loop_gets_an_urgent_unclaimed_task() {
497 let dir = tempfile::tempdir().unwrap();
498 let q = Queue::at(dir.path().join("queue"));
499 heartbeat(dir.path(), 4242, 0);
500 let filed = file(
501 &q,
502 dir.path(),
503 Timestamp::now(),
504 1,
505 filing(dir.path()),
506 false,
507 )
508 .unwrap();
509 let Filed::Daemon { task, pid } = filed else {
510 panic!("a loop is alive");
511 };
512 assert_eq!(pid, Some(4242));
513 assert!(task.urgent);
514 let stored = q.get(&task.id).unwrap();
515 assert_eq!(stored.status, TaskStatus::Queued);
516 assert!(stored.runs.is_empty(), "nothing ran in this process");
517 assert!(q.claim(&task.id).is_ok(), "and this process holds no claim");
518 }
519
520 #[test]
521 fn a_stale_heartbeat_our_own_pid_and_a_dry_run_do_not_count_as_a_loop() {
522 let dir = tempfile::tempdir().unwrap();
523 let q = Queue::at(dir.path().join("queue"));
524 heartbeat(dir.path(), 4242, 3600);
525 assert!(matches!(
526 file(
527 &q,
528 dir.path(),
529 Timestamp::now(),
530 1,
531 filing(dir.path()),
532 false
533 )
534 .unwrap(),
535 Filed::Standalone { .. }
536 ));
537 heartbeat(dir.path(), 7, 0);
538 assert!(matches!(
539 file(
540 &q,
541 dir.path(),
542 Timestamp::now(),
543 7,
544 filing(dir.path()),
545 false
546 )
547 .unwrap(),
548 Filed::Standalone { .. }
549 ));
550 heartbeat(dir.path(), 4242, 0);
551 assert!(matches!(
552 file(
553 &q,
554 dir.path(),
555 Timestamp::now(),
556 1,
557 filing(dir.path()),
558 true
559 )
560 .unwrap(),
561 Filed::Standalone { .. }
562 ));
563 }
564
565 #[tokio::test]
566 async fn following_gives_up_on_a_task_nobody_is_serving() {
567 let dir = tempfile::tempdir().unwrap();
568 let q = Queue::at(dir.path().join("queue"));
569 let mut t = filing(dir.path()).into_task();
570 q.put(&mut t).unwrap();
571 let err = follow(
572 &q,
573 dir.path(),
574 &t.id,
575 Duration::from_millis(5),
576 None,
577 |_| {},
578 |_| {},
579 )
580 .await
581 .unwrap_err();
582 assert!(format!("{err}").contains("no magi loop"), "{err}");
583 assert!(q.claim(&t.id).is_ok(), "never taken over");
584 }
585
586 #[tokio::test]
587 async fn following_returns_when_the_loop_finishes_the_task_and_times_out_otherwise() {
588 let dir = tempfile::tempdir().unwrap();
589 let q = Queue::at(dir.path().join("queue"));
590 heartbeat(dir.path(), 4242, 0);
591 let mut t = filing(dir.path()).into_task();
592 q.put(&mut t).unwrap();
593 let waited = follow(
594 &q,
595 dir.path(),
596 &t.id,
597 Duration::from_millis(5),
598 Some(Duration::from_millis(30)),
599 |_| {},
600 |_| {},
601 )
602 .await
603 .unwrap();
604 assert!(!waited.finished, "the wait ran out, the loop still owns it");
605 let err = waited
606 .unfinished()
607 .expect("an unfinished wait is an error")
608 .to_string();
609 assert!(err.contains(t.short()), "{err}");
610 assert!(
611 err.contains("not finished") || err.contains("not a success"),
612 "{err}"
613 );
614 assert!(err.contains("magi task show"), "{err}");
615 assert_eq!(
616 q.get(&t.id).unwrap().status,
617 TaskStatus::Queued,
618 "the queue is untouched"
619 );
620 t.link_run("20260101-000000-abcd");
621 t.succeed(crate::queue::CompletionContext::new(
622 crate::queue::CompletionActor::DaemonSettle,
623 None,
624 dir.path(),
625 &t,
626 ));
627 q.put(&mut t).unwrap();
628 let mut runs = Vec::new();
629 let done = follow(
630 &q,
631 dir.path(),
632 &t.id,
633 Duration::from_millis(5),
634 Some(Duration::from_secs(5)),
635 |r| runs.push(r.to_owned()),
636 |_| {},
637 )
638 .await
639 .unwrap();
640 assert_eq!(done.task.status, TaskStatus::Done);
641 assert!(done.unfinished().is_none());
642 assert_eq!(runs, ["20260101-000000-abcd"]);
643 }
644
645 fn parent_in(q: &Queue, dir: &Path) -> Task {
646 let mut t = filing(dir).into_task();
647 q.put(&mut t).unwrap();
648 t
649 }
650
651 fn follow_up_state(dir: &Path) -> crate::run::RunState {
652 crate::run::RunState::new(
653 dir.to_path_buf(),
654 "main".to_owned(),
655 "abc1234".to_owned(),
656 "review the branch".to_owned(),
657 Config::default(),
658 )
659 }
660
661 #[test]
662 fn an_adopted_review_claims_starts_and_settles_a_runnable_task() {
663 let dir = tempfile::tempdir().unwrap();
664 let q = Queue::at(dir.path().join("queue"));
665 let parent = parent_in(&q, dir.path());
666 let state = follow_up_state(dir.path());
667 let adopted = adopt_in(q.clone(), &state, Some(&parent.id))
668 .unwrap()
669 .expect("adopted");
670 let running = q.get(&parent.id).unwrap();
671 assert_eq!(running.status, TaskStatus::Running);
672 assert_eq!(running.attempts, parent.attempts + 1);
673 assert_eq!(running.runs, std::slice::from_ref(&state.id));
674 assert!(q.claim(&parent.id).is_err(), "exclusive while it runs");
675 adopted.finish(&state, Err(anyhow::anyhow!("boom")));
676 let settled = q.get(&parent.id).unwrap();
677 assert_eq!(settled.status, TaskStatus::Held, "{settled:?}");
678 assert_eq!(
679 settled.runs,
680 std::slice::from_ref(&state.id),
681 "no duplicate run"
682 );
683 assert!(q.claim(&parent.id).is_ok(), "claim released");
684 assert_eq!(q.list().len(), 1, "no second owner was filed");
685 }
686
687 #[test]
688 fn an_ownerless_run_whose_task_cannot_be_filed_is_an_error() {
689 let dir = tempfile::tempdir().unwrap();
690 let blocker = dir.path().join("blocker");
692 std::fs::write(&blocker, "x").unwrap();
693 let q = Queue::at(blocker.join("q"));
694 let state = follow_up_state(dir.path());
695 let err = adopt_in(q, &state, None).expect_err("must not be swallowed");
696 assert!(format!("{err:#}").contains(&state.id), "{err:#}");
697 }
698
699 #[test]
700 fn a_task_claimed_elsewhere_only_gains_the_run() {
701 let dir = tempfile::tempdir().unwrap();
702 let q = Queue::at(dir.path().join("queue"));
703 let parent = parent_in(&q, dir.path());
704 let _theirs = q.claim(&parent.id).unwrap();
705 let state = follow_up_state(dir.path());
706 assert!(
707 adopt_in(q.clone(), &state, Some(&parent.id))
708 .unwrap()
709 .is_none()
710 );
711 let after = q.get(&parent.id).unwrap();
712 assert_eq!(after.status, parent.status);
713 assert_eq!(after.attempts, parent.attempts);
714 assert_eq!(after.runs, std::slice::from_ref(&state.id));
715 assert_eq!(q.list().len(), 1, "no second owner was filed");
716 }
717
718 #[test]
719 fn a_done_task_only_gains_the_run() {
720 let dir = tempfile::tempdir().unwrap();
721 let q = Queue::at(dir.path().join("queue"));
722 let mut parent = parent_in(&q, dir.path());
723 parent.succeed(crate::queue::CompletionContext::new(
724 crate::queue::CompletionActor::Cli,
725 None,
726 dir.path(),
727 &parent,
728 ));
729 q.put(&mut parent).unwrap();
730 let state = follow_up_state(dir.path());
731 assert!(
732 adopt_in(q.clone(), &state, Some(&parent.id))
733 .unwrap()
734 .is_none()
735 );
736 let after = q.get(&parent.id).unwrap();
737 assert_eq!(after.status, TaskStatus::Done);
738 assert_eq!(after.attempts, parent.attempts);
739 assert_eq!(after.runs, std::slice::from_ref(&state.id));
740 assert!(q.claim(&parent.id).is_ok(), "claim released");
741 }
742
743 #[test]
744 fn a_held_task_is_claimed_and_settled_by_its_follow_up_review() {
745 let dir = tempfile::tempdir().unwrap();
746 let q = Queue::at(dir.path().join("queue"));
747 let mut parent = parent_in(&q, dir.path());
748 parent.hold_manual(Some("the run did not finish: stale".to_owned()));
749 q.put(&mut parent).unwrap();
750 let state = follow_up_state(dir.path());
751 let adopted = adopt_in(q.clone(), &state, Some(&parent.id))
752 .unwrap()
753 .expect("adopted");
754 assert_eq!(q.get(&parent.id).unwrap().status, TaskStatus::Running);
755 assert!(q.claim(&parent.id).is_err(), "claimed while it runs");
756 adopted.finish(&state, Err(anyhow::anyhow!("fresh failure")));
757 let after = q.get(&parent.id).unwrap();
758 assert_eq!(after.status, TaskStatus::Held);
759 assert!(
760 after
761 .hold_reason
762 .as_deref()
763 .unwrap()
764 .contains("fresh failure"),
765 "{after:?}"
766 );
767 assert_eq!(after.runs, std::slice::from_ref(&state.id));
768 assert!(q.claim(&parent.id).is_ok(), "claim released");
769 }
770}