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