1use anyhow::Result;
18
19use crate::queue::{FollowUp, Queue, Source, Task};
20use crate::run::{FollowupRecord, RunState};
21use crate::verdict::{Finding, ReviewVote};
22
23pub const NODE: &str = "followup";
25
26pub const MAX_FOLLOWUP_GENERATION: u32 = 2;
28
29const LINE_WINDOW: u32 = 5;
31
32#[derive(Debug, Default, PartialEq, Eq)]
34pub struct Outcome {
35 pub filed: Vec<String>,
37 pub capped: Vec<String>,
39 pub unfiled: Vec<String>,
41 pub covered: Vec<(String, String)>,
44}
45
46pub async fn after_merge(state: &mut RunState, pr_url: &str) {
49 let queue = Queue::open();
50 let release = state.config.graph.release_deputy_followups;
51 settle_deputy_tasks(state, pr_url, &queue, release);
54 let outcome = if state.config.graph.file_followups {
55 match file(state, pr_url, &queue) {
56 Ok(o) => o,
57 Err(e) => {
58 state.event(NODE, format!("follow-up filing failed: {e:#}"));
59 return;
60 }
61 }
62 } else {
63 Outcome::default()
64 };
65 if state.config.graph.file_followups && !release {
66 settle_deputy_tasks(state, pr_url, &queue, false);
67 }
68 if outcome.filed.is_empty()
69 && (state.followup_commented
70 || (state.followups.is_empty()
71 && outcome.covered.is_empty()
72 && state.deputy_followups.is_empty()))
73 {
74 return;
75 }
76 let body = comment_body(state, &outcome);
77 match crate::bump::gh_pr_comment(state, pr_url, &body).await {
78 Ok(()) => state.followup_commented = true,
79 Err(e) => state.event(NODE, format!("follow-up comment not posted: {e:#}")),
80 }
81}
82
83const SUPERSEDED: &str = "[superseded] ";
86const CAPPED: &str = "[generation cap] ";
87
88fn is_deputy_candidate(t: &Task, run: &str, pr_url: &str) -> bool {
93 t.status == crate::queue::TaskStatus::Held
94 && t.followup.is_none()
95 && matches!(&t.source, Source::Agent { run: r, node }
96 if r == run && node == crate::deputy::NODE)
97 && t.hold_reason.as_deref().is_some_and(|r| {
98 !r.starts_with(SUPERSEDED) && !r.starts_with(CAPPED) && names_pr(r, pr_url)
99 })
100}
101
102fn task_matches_finding(t: &Task, f: &Finding) -> bool {
106 let text = format!("{}\n{}", t.title, t.instruction);
107 if names_word(&text, &f.id) {
108 return true;
109 }
110 if let (Some(file), Some(line)) = (&f.file, f.line)
111 && text.match_indices(file.as_str()).any(|(i, _)| {
112 text[i + file.len()..]
113 .strip_prefix(':')
114 .map(|r| {
115 r.chars()
116 .take_while(char::is_ascii_digit)
117 .collect::<String>()
118 })
119 .and_then(|d| d.parse::<u32>().ok())
120 .is_some_and(|n| n.abs_diff(line) <= LINE_WINDOW)
121 })
122 {
123 return true;
124 }
125 let (nt, nf) = (normalize(&t.title), normalize(&f.title));
126 !nf.is_empty() && (nt == nf || (nf.split(' ').count() >= 3 && nt.contains(&nf)))
127}
128
129fn parent_generation(state: &mut RunState, queue: &Queue, origin_task: Option<&str>) -> u32 {
131 match state.followup_generation {
132 Some(g) => g,
133 None => match origin_task.map(|t| queue.get(t)) {
134 Some(Ok(t)) => {
135 let g = t.followup.map_or(0, |f| f.generation);
136 state.followup_generation = Some(g);
137 g
138 }
139 Some(Err(_)) => MAX_FOLLOWUP_GENERATION,
140 None => 0,
141 },
142 }
143}
144
145pub fn settle_deputy_tasks(state: &mut RunState, pr_url: &str, queue: &Queue, release: bool) {
165 let tasks = queue.list();
166 for t in &tasks {
168 if t.followup.as_ref().is_some_and(|f| f.run == state.id)
169 && matches!(&t.source, Source::Agent { node, .. } if node == crate::deputy::NODE)
170 && !state.deputy_followups.contains(&t.id)
171 {
172 state.deputy_followups.push(t.id.clone());
173 }
174 }
175 let cands: Vec<&Task> = tasks
176 .iter()
177 .filter(|t| is_deputy_candidate(t, &state.id, pr_url))
178 .collect();
179 if cands.is_empty() {
180 return;
181 }
182 let chosen = state
183 .reviews
184 .last()
185 .map(|r| select(r).0)
186 .unwrap_or_default();
187 let groups = group_findings(chosen);
188 let autos: Vec<&Task> = tasks
189 .iter()
190 .filter(|t| {
191 t.followup.as_ref().is_some_and(|f| f.run == state.id)
192 && matches!(&t.source, Source::Agent { node, .. } if node == NODE)
193 })
194 .collect();
195 let origin_task = state.origin.as_ref().and_then(|o| o.task.clone());
196 let mut gen_of_parent = None;
197 for cand in cands {
198 let matched: Vec<String> = groups
200 .iter()
201 .filter(|g| g.iter().any(|f| task_matches_finding(cand, f)))
202 .flat_map(|g| g.iter().map(|f| f.id.clone()))
203 .collect();
204 let rivals: Vec<&&Task> = autos
205 .iter()
206 .filter(|a| {
207 a.followup
208 .as_ref()
209 .is_some_and(|f| f.findings.iter().any(|x| matched.contains(x)))
210 })
211 .collect();
212 if release {
213 let parent_gen = *gen_of_parent
214 .get_or_insert_with(|| parent_generation(state, queue, origin_task.as_deref()));
215 if parent_gen >= MAX_FOLLOWUP_GENERATION {
216 let why = format!(
217 "{CAPPED}generation {parent_gen} reached, not released after {pr_url} merged; was: {}",
218 cand.hold_reason.as_deref().unwrap_or_default()
219 );
220 mark_held(state, queue, cand, why, pr_url, "generation cap");
221 continue;
222 }
223 }
224 if !rivals.is_empty() {
225 let mut guards = Vec::new();
230 let mut blocker: Option<&Task> = None;
231 let takeover = format!(
232 "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {pr_url}",
233 cand.id
234 );
235 let mut carried: Vec<String> = Vec::new();
238 if release {
239 for a in &rivals {
240 let ours = a.status == crate::queue::TaskStatus::Held
241 && a.hold_reason.as_deref() == Some(takeover.as_str());
242 if a.status == crate::queue::TaskStatus::Held && !ours {
243 continue;
244 }
245 match queue.claim(&a.id) {
246 Ok(g) => {
247 if ours {
248 carried.push(a.id.clone());
249 }
250 guards.push((a.id.clone(), g));
251 }
252 Err(_) => {
253 blocker = Some(a);
254 break;
255 }
256 }
257 }
258 if blocker.is_none() {
259 blocker = rivals.iter().map(|a| &***a).find(|a| {
260 !matches!(
261 queue.get(&a.id).map(|t| t.status),
262 Ok(crate::queue::TaskStatus::Queued | crate::queue::TaskStatus::Held)
263 )
264 });
265 }
266 } else {
267 blocker = Some(&***rivals.first().expect("non-empty"));
268 }
269 if let Some(a) = blocker {
270 let mut stuck = false;
273 for r in &rivals {
274 let held_by_us = queue.get(&r.id).is_ok_and(|t| {
275 t.status == crate::queue::TaskStatus::Held
276 && t.hold_reason.as_deref() == Some(takeover.as_str())
277 });
278 if !held_by_us {
279 continue;
280 }
281 let _own;
282 if !guards.iter().any(|(g, _)| g == &r.id) {
283 match queue.claim(&r.id) {
284 Ok(g) => _own = g,
285 Err(_) => {
286 stuck = true;
287 continue;
288 }
289 }
290 }
291 stuck |= !restore_takeover_hold(state, queue, &r.id, &takeover, &cand.id);
292 }
293 drop(guards);
294 if stuck {
295 continue;
296 }
297 let why = format!(
298 "{SUPERSEDED}follow-up task {} ({:?}) already covers {} of {pr_url}; was: {}",
299 a.id,
300 a.status,
301 matched.join(", "),
302 cand.hold_reason.as_deref().unwrap_or_default()
303 );
304 mark_held(state, queue, cand, why, pr_url, "superseded");
305 continue;
306 }
307 let mut failed: Option<String> = None;
310 let mut done: Vec<(String, Task, String)> = Vec::new();
312 for (id, _guard) in &guards {
313 if carried.contains(id) {
314 continue;
315 }
316 let why = takeover.clone();
317 let mut before: Option<Task> = None;
318 let held = queue.modify(id, |t| {
319 if t.status != crate::queue::TaskStatus::Queued {
320 return false;
321 }
322 before = Some(t.clone());
323 t.hold_manual(Some(why.clone()));
324 true
325 });
326 match held {
327 Ok(true) => {
328 done.extend(before.map(|b| (id.clone(), b, why)));
329 state.event(
330 NODE,
331 format!(
332 "follow-up task {id} held: superseded by deputy task {}",
333 cand.id
334 ),
335 );
336 }
337 Ok(false) => {
338 failed = Some(id.clone());
339 break;
340 }
341 Err(e) => {
342 state.event(NODE, format!("could not hold follow-up {id}: {e:#}"));
343 failed = Some(id.clone());
344 break;
345 }
346 }
347 }
348 if let Some(id) = failed {
349 let mut stuck = false;
353 for tid in &carried {
354 stuck |= !restore_takeover_hold(state, queue, tid, &takeover, &cand.id);
355 }
356 for (tid, before, why) in done.into_iter().rev() {
357 let back = queue.modify(&tid, |t| {
358 if t.status != crate::queue::TaskStatus::Held
359 || t.hold_reason.as_deref() != Some(why.as_str())
360 {
361 return false;
362 }
363 *t = before;
364 true
365 });
366 match back {
367 Ok(true) => state.event(
368 NODE,
369 format!(
370 "follow-up task {tid} restored: deputy task {} could not take it over",
371 cand.id
372 ),
373 ),
374 Ok(false) => {}
375 Err(e) => {
376 stuck = true;
377 state.event(
378 NODE,
379 format!(
380 "rollback of {tid} failed, deputy task {} left as a candidate for the next settle: {e:#}",
381 cand.id
382 ),
383 );
384 }
385 }
386 }
387 drop(guards);
388 if stuck {
389 continue;
390 }
391 let why = format!(
392 "{SUPERSEDED}follow-up task {id} could not be held, so it may still run for {} of {pr_url}; was: {}",
393 matched.join(", "),
394 cand.hold_reason.as_deref().unwrap_or_default()
395 );
396 mark_held(state, queue, cand, why, pr_url, "superseded");
397 continue;
398 }
399 } else if !release {
400 continue;
401 }
402 let parent_gen = gen_of_parent.expect("computed when releasing");
403 let stamp = FollowUp {
404 run: state.id.clone(),
405 origin_task: origin_task.clone(),
406 pr: pr_url.to_owned(),
407 findings: matched,
408 generation: parent_gen + 1,
409 };
410 let id = cand.id.clone();
411 let run = state.id.clone();
412 let result = queue.modify(&id, |t| {
413 if !is_deputy_candidate(t, &run, pr_url) {
414 return false;
415 }
416 t.release();
417 t.followup = Some(stamp);
418 true
419 });
420 match result {
421 Ok(true) => {
422 if !state.deputy_followups.contains(&id) {
423 state.deputy_followups.push(id.clone());
424 }
425 state.event(
426 NODE,
427 format!("released deputy follow-up task {id} after {pr_url} merged"),
428 );
429 }
430 Ok(false) => {}
431 Err(e) => state.event(NODE, format!("could not release deputy task {id}: {e:#}")),
432 }
433 }
434}
435
436fn restore_takeover_hold(
440 state: &mut RunState,
441 queue: &Queue,
442 tid: &str,
443 takeover: &str,
444 cand_id: &str,
445) -> bool {
446 let back = queue.modify(tid, |t| {
447 if t.status != crate::queue::TaskStatus::Held || t.hold_reason.as_deref() != Some(takeover)
448 {
449 return false;
450 }
451 t.status = crate::queue::TaskStatus::Queued;
454 t.held_at = None;
455 t.hold_reason = None;
456 t.hold_source = None;
457 true
458 });
459 match back {
460 Ok(true) => {
461 state.event(
462 NODE,
463 format!(
464 "follow-up task {tid} restored: deputy task {cand_id} could not take it over"
465 ),
466 );
467 true
468 }
469 Ok(false) => true,
470 Err(e) => {
471 state.event(
472 NODE,
473 format!(
474 "rollback of {tid} failed, deputy task {cand_id} left as a candidate for the next settle: {e:#}"
475 ),
476 );
477 false
478 }
479 }
480}
481
482pub(crate) fn supersede_deputy_tasks(
484 state: &mut RunState,
485 pr_url: &str,
486 queue: &Queue,
487 successor: &str,
488) {
489 for task in queue.list() {
490 if is_deputy_candidate(&task, &state.id, pr_url) {
491 mark_held(
492 state,
493 queue,
494 &task,
495 format!(
496 "{SUPERSEDED}pull request ownership moved to run {}",
497 crate::run::short_of(successor)
498 ),
499 pr_url,
500 "superseded",
501 );
502 }
503 }
504}
505
506fn mark_held(
508 state: &mut RunState,
509 queue: &Queue,
510 cand: &Task,
511 why: String,
512 pr_url: &str,
513 kind: &str,
514) {
515 let run = state.id.clone();
516 let reason = why.clone();
517 match queue.modify(&cand.id, |t| {
518 if !is_deputy_candidate(t, &run, pr_url) {
519 return false;
520 }
521 t.hold_reason = Some(reason);
522 true
523 }) {
524 Ok(true) => state.event(
525 NODE,
526 format!("deputy task {} left held ({kind}): {why}", cand.id),
527 ),
528 Ok(false) => {}
529 Err(e) => state.event(
530 NODE,
531 format!("could not mark deputy task {}: {e:#}", cand.id),
532 ),
533 }
534}
535
536fn select(round: &crate::run::ReviewRound) -> (Vec<Finding>, Vec<String>) {
540 let rejecters: Vec<usize> = round
541 .final_votes()
542 .into_iter()
543 .filter(|(_, _, v)| *v == ReviewVote::Reject)
544 .map(|(seat, _, _)| seat)
545 .collect();
546 let (mut chosen, mut unfiled) = (Vec::new(), Vec::new());
547 for rec in &round.reviews {
548 let rejected = rejecters.contains(&rec.reviewer);
549 for f in &rec.findings {
550 if f.severity.blocks() || rejected {
551 chosen.push(f.clone());
552 } else {
553 unfiled.push(f.id.clone());
554 }
555 }
556 }
557 (chosen, unfiled)
558}
559
560pub fn file(state: &mut RunState, pr_url: &str, queue: &Queue) -> Result<Outcome> {
564 let mut out = Outcome::default();
565 let Some(round) = state.reviews.last().cloned() else {
566 return Ok(out);
567 };
568 let (chosen, unfiled) = select(&round);
569 out.unfiled = unfiled;
570 if chosen.is_empty() {
571 return Ok(out);
572 }
573
574 let origin_task = state.origin.as_ref().and_then(|o| o.task.clone());
575 let parent_gen = parent_generation(state, queue, origin_task.as_deref());
579 if parent_gen >= MAX_FOLLOWUP_GENERATION {
580 out.capped = chosen.iter().map(|f| f.id.clone()).collect();
581 state.event(
582 NODE,
583 format!(
584 "generation cap reached ({parent_gen}); not filing follow-ups for open finding(s): {}",
585 out.capped.join(", ")
586 ),
587 );
588 return Ok(out);
589 }
590
591 let mut done: Vec<String> = state
592 .followups
593 .iter()
594 .flat_map(|r| r.findings.iter().cloned())
595 .collect();
596 for t in queue.list() {
597 if let Some(f) = t.followup
598 && f.run == state.id
599 {
600 done.extend(f.findings.iter().cloned());
601 let by_deputy =
602 matches!(&t.source, Source::Agent { node, .. } if node == crate::deputy::NODE);
603 if !by_deputy && !state.followups.iter().any(|r| r.task == t.id) {
604 state.followups.push(FollowupRecord {
605 task: t.id,
606 findings: f.findings,
607 });
608 }
609 }
610 }
611
612 let tasks = queue.list();
613 let origin_chat = state.origin_chat.clone().or_else(|| {
614 let tasks = queue.list();
615 let parent = origin_task
616 .as_deref()
617 .and_then(|id| tasks.iter().find(|t| t.id == id))?;
618 crate::consult::chat_talk_of(&tasks, parent)
619 });
620 let mut failure = None;
621 for group in group_findings(chosen) {
622 let ids: Vec<String> = group.iter().map(|f| f.id.clone()).collect();
623 let own = task_id(&state.id, &ids);
624 let covers: Vec<Option<String>> = ids
625 .iter()
626 .map(|id| covering_task(&tasks, &own, &state.id, pr_url, id))
627 .collect();
628 if covers.iter().all(Option::is_some) {
629 for (id, by) in ids.iter().zip(covers.into_iter().flatten()) {
630 state.event(
631 NODE,
632 format!("not filing follow-up for {id}: already covered by task {by}"),
633 );
634 out.covered.push((id.clone(), by));
635 }
636 continue;
637 }
638 if ids.iter().any(|id| done.contains(id)) {
639 continue;
640 }
641 let mut task = build_task(state, pr_url, origin_task.clone(), &group, parent_gen + 1);
642 task.origin_chat = origin_chat.clone();
643 let chat_cfg = crate::task_chat::prepare_filing(queue, &mut task);
644 match queue.create_new(&mut task) {
645 Ok(created) => {
646 if created {
647 crate::task_chat::finish_filing(queue, &mut task, chat_cfg.as_ref());
648 out.filed.push(task.id.clone());
649 }
650 state.followups.push(FollowupRecord {
651 task: task.id,
652 findings: ids,
653 });
654 }
655 Err(e) => {
656 failure = Some(e);
657 break;
658 }
659 }
660 }
661 if !out.filed.is_empty() {
662 state.event(
663 NODE,
664 format!(
665 "filed {} follow-up task(s): ids {}",
666 out.filed.len(),
667 out.filed.join(", ")
668 ),
669 );
670 }
671 if let Some(e) = failure {
672 state.event(NODE, format!("follow-up filing stopped: {e:#}"));
673 }
674 Ok(out)
675}
676
677fn covering_task(tasks: &[Task], own: &str, run: &str, pr_url: &str, id: &str) -> Option<String> {
682 tasks
683 .iter()
684 .find(|t| {
685 t.id != own
686 && (t
687 .followup
688 .as_ref()
689 .is_some_and(|f| f.run == run && f.findings.iter().any(|x| x == id))
690 || (names_word(&t.instruction, id) && names_pr(&t.instruction, pr_url)))
691 })
692 .map(|t| t.id.clone())
693}
694
695fn is_name_char(c: char) -> bool {
698 c.is_ascii_alphanumeric() || matches!(c, '_' | '-')
699}
700
701fn names_word(text: &str, needle: &str) -> bool {
703 !needle.is_empty()
704 && text.match_indices(needle).any(|(i, _)| {
705 let before = text[..i].chars().next_back();
706 let after = text[i + needle.len()..].chars().next();
707 before.is_none_or(|c| !is_name_char(c)) && after.is_none_or(|c| !is_name_char(c))
708 })
709}
710
711fn names_pr(text: &str, pr_url: &str) -> bool {
714 let url = pr_url.trim_end_matches('/');
715 let digit_after = |rest: &str| rest.chars().next().is_some_and(|c| c.is_ascii_digit());
716 if !url.is_empty()
717 && text
718 .match_indices(url)
719 .any(|(i, _)| !digit_after(&text[i + url.len()..]))
720 {
721 return true;
722 }
723 let Some(n) = url
724 .rsplit('/')
725 .next()
726 .filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
727 else {
728 return false;
729 };
730 let tag = format!("#{n}");
731 text.match_indices(&tag).any(|(i, _)| {
732 let before = text[..i].chars().next_back();
733 before.is_none_or(|c| !is_name_char(c)) && !digit_after(&text[i + tag.len()..])
734 })
735}
736
737fn group_findings(mut findings: Vec<Finding>) -> Vec<Vec<Finding>> {
741 findings.sort_by(|a, b| (&a.file, a.line, &a.id).cmp(&(&b.file, b.line, &b.id)));
742 let mut groups: Vec<Vec<Finding>> = Vec::new();
743 for f in findings {
744 let hit = groups
745 .iter()
746 .position(|g| g.iter().any(|o| same_defect(o, &f)));
747 match hit {
748 Some(i) => groups[i].push(f),
749 None => groups.push(vec![f]),
750 }
751 }
752 for g in &mut groups {
753 g.sort_by(|a, b| a.id.cmp(&b.id));
754 }
755 groups
756}
757
758fn same_defect(a: &Finding, b: &Finding) -> bool {
759 match (&a.file, &b.file) {
760 (Some(x), Some(y)) => {
761 x == y
762 && match (a.line, b.line) {
763 (Some(l), Some(m)) => l.abs_diff(m) <= LINE_WINDOW,
764 (None, None) => true,
765 _ => false,
766 }
767 }
768 (None, None) => normalize(&a.title) == normalize(&b.title),
769 _ => false,
770 }
771}
772
773fn normalize(title: &str) -> String {
774 title
775 .to_lowercase()
776 .split(|c: char| !c.is_alphanumeric())
777 .filter(|w| !w.is_empty())
778 .collect::<Vec<_>>()
779 .join(" ")
780}
781
782fn task_id(run: &str, ids: &[String]) -> String {
786 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
787 for b in ids.join("+").bytes() {
788 h ^= u64::from(b);
789 h = h.wrapping_mul(0x0100_0000_01b3);
790 }
791 format!("{run}-f{:05x}", h & 0xf_ffff)
792}
793
794fn location(f: &Finding) -> String {
795 match (&f.file, f.line) {
796 (Some(p), Some(l)) => format!("{p}:{l}"),
797 (Some(p), None) => p.clone(),
798 _ => "(no location)".to_owned(),
799 }
800}
801
802fn build_task(
803 state: &RunState,
804 pr_url: &str,
805 origin_task: Option<String>,
806 group: &[Finding],
807 generation: u32,
808) -> Task {
809 let ids: Vec<String> = group.iter().map(|f| f.id.clone()).collect();
810 let first = &group[0];
811 let title = format!(
812 "follow-up: {} ({})",
813 crate::queue::title_from(&first.title, 80),
814 location(first)
815 );
816 let mut s = format!(
817 "This is a follow-up to a change that was already merged: run {run} merged \
818 {pr_url} while the review finding(s) below were still open. Branch from the \
819 current main - do not use the merged branch - and fix the defect described, \
820 keeping the change small. If a finding no longer applies to current main, say so \
821 and change nothing for it.\n\n\
822 Merged run: {run}\nPull request: {pr_url}\n",
823 run = state.id,
824 );
825 if let Some(t) = &origin_task {
826 s.push_str(&format!("Original task: {t}\n"));
827 }
828 s.push_str("\n## Findings\n");
829 for f in group {
830 s.push_str(&format!(
831 "\n### {} [{:?}] {}\n\nLocation: {}\n\n{}\n",
832 f.id,
833 f.severity,
834 f.title,
835 location(f),
836 f.detail.trim()
837 ));
838 }
839 let mut task = Task::new(
840 title,
841 s,
842 state.repo.clone(),
843 Source::Agent {
844 run: state.id.clone(),
845 node: NODE.to_owned(),
846 },
847 );
848 task.id = task_id(&state.id, &ids);
849 task.solo = true;
850 task.followup = Some(FollowUp {
851 run: state.id.clone(),
852 origin_task,
853 pr: pr_url.to_owned(),
854 findings: ids,
855 generation,
856 });
857 task
858}
859
860fn comment_body(state: &RunState, out: &Outcome) -> String {
861 let mut s = format!(
862 "<!-- magi-followup run={} -->\nThis pull request merged with review findings still open.",
863 state.id
864 );
865 if state.followups.is_empty() {
866 if !out.covered.is_empty() || state.deputy_followups.is_empty() {
867 s.push_str(" Each is already covered by another task:\n");
868 }
869 } else {
870 s.push_str(" They were filed as follow-up tasks:\n\n");
871 for r in &state.followups {
872 s.push_str(&format!("- `{}`: {}\n", r.task, r.findings.join(", ")));
873 }
874 if !out.covered.is_empty() {
875 s.push_str("\nNot filed, already covered:\n");
876 }
877 }
878 if !out.covered.is_empty() {
879 s.push('\n');
880 }
881 for (id, by) in &out.covered {
882 s.push_str(&format!("- {id}: already covered by task `{by}`\n"));
883 }
884 if !state.deputy_followups.is_empty() {
885 s.push_str(
886 "\nFollow-up tasks filed by the approval deputy and released after the merge:\n\n",
887 );
888 for id in &state.deputy_followups {
889 s.push_str(&format!("- `{id}`\n"));
890 }
891 }
892 if !out.unfiled.is_empty() {
893 s.push_str(&format!(
894 "\nMinor/nit findings that were only listed, not filed: {}\n",
895 out.unfiled.join(", ")
896 ));
897 }
898 s
899}
900
901#[cfg(test)]
902mod tests {
903 use super::*;
904 use crate::config::Config;
905 use crate::queue::Queue;
906 use crate::run::ReviewRecord;
907 use crate::run::{Origin, ReviewRound, RunState};
908 use crate::verdict::{Finding, ReviewVote, Severity};
909 use std::path::PathBuf;
910
911 fn finding(id: &str, sev: Severity, file: &str, line: u32) -> Finding {
912 Finding {
913 id: id.to_owned(),
914 severity: sev,
915 file: Some(file.to_owned()),
916 line: Some(line),
917 title: format!("title {id}"),
918 detail: format!("detail of {id}"),
919 }
920 }
921
922 fn record(seat: usize, findings: Vec<Finding>, vote: ReviewVote) -> ReviewRecord {
923 ReviewRecord {
924 attempts: 0,
925 reviewer: seat,
926 agent: "alpha".to_owned(),
927 summary: String::new(),
928 findings,
929 vote: Some(vote),
930 failed: None,
931 duration_ms: 0,
932 }
933 }
934
935 fn round(reviews: Vec<ReviewRecord>) -> ReviewRound {
936 ReviewRound {
937 round: 3,
938 head: "deadbee".to_owned(),
939 verified_head: None,
940 verified_at: None,
941 reviews,
942 e2e: Vec::new(),
943 verify_retried: false,
944 e2e_deferred: false,
945 e2e_defer_reason: None,
946 fix: None,
947 blocking: 0,
948 answered: 2,
949 expected: 2,
950 clean: false,
951 progressed: false,
952 vote_split: false,
953 reconsideration: Vec::new(),
954 verdict: None,
955 }
956 }
957
958 fn merged(reviews: Vec<ReviewRecord>) -> RunState {
959 let mut s = RunState::new(
960 PathBuf::from("/repo"),
961 "main".to_owned(),
962 "abc1234".to_owned(),
963 "do it".to_owned(),
964 Config::default(),
965 );
966 s.reviews.push(round(reviews));
967 s
968 }
969
970 fn two_seats() -> Vec<ReviewRecord> {
971 vec![
972 record(
973 1,
974 vec![
975 finding("R3-1-1", Severity::Major, "src/waiter.rs", 211),
976 finding("R3-1-2", Severity::Minor, "src/a.rs", 1),
977 ],
978 ReviewVote::Reject,
979 ),
980 record(
981 2,
982 vec![
983 finding("R3-2-1", Severity::Major, "src/waiter.rs", 213),
984 finding("R3-2-2", Severity::Nit, "src/b.rs", 9),
985 ],
986 ReviewVote::Approve,
987 ),
988 ]
989 }
990
991 #[test]
992 fn one_task_per_distinct_defect_with_the_findings_in_full() {
993 let dir = tempfile::tempdir().unwrap();
994 let q = Queue::at(dir.path().join("queue"));
995 let mut s = merged(two_seats());
996 let out = file(&mut s, "https://example.invalid/o/r/pull/9", &q).unwrap();
997 assert_eq!(out.filed.len(), 2, "{out:?}");
1000 assert_eq!(out.unfiled, vec!["R3-2-2".to_owned()]);
1001 let tasks = q.list();
1002 let t = tasks
1003 .iter()
1004 .find(|t| t.followup.as_ref().unwrap().findings.len() == 2)
1005 .unwrap();
1006 assert!(t.solo);
1007 assert_eq!(t.followup.as_ref().unwrap().generation, 1);
1008 assert_eq!(
1009 t.source,
1010 Source::Agent {
1011 run: s.id.clone(),
1012 node: NODE.to_owned()
1013 }
1014 );
1015 for needle in [
1016 "R3-1-1",
1017 "R3-2-1",
1018 "src/waiter.rs:211",
1019 "detail of R3-2-1",
1020 "pull/9",
1021 &s.id,
1022 "current main",
1023 ] {
1024 assert!(
1025 t.instruction.contains(needle),
1026 "{needle}: {}",
1027 t.instruction
1028 );
1029 }
1030 assert!(
1031 s.events
1032 .iter()
1033 .any(|e| e.message.contains("filed 2 follow-up"))
1034 );
1035 assert_eq!(s.followups.len(), 2);
1036 }
1037
1038 #[test]
1039 fn filing_twice_does_not_duplicate() {
1040 let dir = tempfile::tempdir().unwrap();
1041 let q = Queue::at(dir.path().join("queue"));
1042 let mut s = merged(two_seats());
1043 file(&mut s, "u", &q).unwrap();
1044 let again = file(&mut s, "u", &q).unwrap();
1045 assert!(again.filed.is_empty());
1046 assert_eq!(q.list().len(), 2);
1047 s.followups.clear();
1049 let third = file(&mut s, "u", &q).unwrap();
1050 assert!(third.filed.is_empty());
1051 assert_eq!(q.list().len(), 2);
1052 assert_eq!(s.followups.len(), 2, "records are restored from the queue");
1053 }
1054
1055 #[test]
1056 fn a_clean_merge_files_nothing() {
1057 let dir = tempfile::tempdir().unwrap();
1058 let q = Queue::at(dir.path().join("queue"));
1059 let mut s = merged(vec![record(
1060 1,
1061 vec![finding("R1-1-1", Severity::Minor, "a.rs", 1)],
1062 ReviewVote::Approve,
1063 )]);
1064 let out = file(&mut s, "u", &q).unwrap();
1065 assert!(out.filed.is_empty());
1066 assert!(q.list().is_empty());
1067 assert!(s.followups.is_empty());
1068 }
1069
1070 #[test]
1071 fn a_failing_queue_is_an_error_event_not_a_status_change() {
1072 let dir = tempfile::tempdir().unwrap();
1073 let root = dir.path().join("queue");
1074 std::fs::write(&root, "not a directory").unwrap();
1075 let q = Queue::at(root);
1076 let mut s = merged(two_seats());
1077 s.status = crate::run::RunStatus::Merged;
1078 let _ = file(&mut s, "u", &q);
1079 assert_eq!(s.status, crate::run::RunStatus::Merged);
1080 assert!(
1081 s.events
1082 .iter()
1083 .any(|e| e.node == NODE && e.message.contains("stopped"))
1084 );
1085 assert!(s.followups.is_empty());
1086 }
1087
1088 #[test]
1089 fn the_generation_cap_stops_the_chain() {
1090 let dir = tempfile::tempdir().unwrap();
1091 let q = Queue::at(dir.path().join("queue"));
1092 let mut parent = Task::new(
1093 "p".to_owned(),
1094 "i".to_owned(),
1095 PathBuf::from("/repo"),
1096 Source::Human,
1097 );
1098 parent.followup = Some(FollowUp {
1099 run: "r0".to_owned(),
1100 origin_task: None,
1101 pr: "u".to_owned(),
1102 findings: vec!["R1-1-1".to_owned()],
1103 generation: MAX_FOLLOWUP_GENERATION,
1104 });
1105 q.put(&mut parent).unwrap();
1106 let mut s = merged(two_seats());
1107 s.origin = Some(Origin {
1108 by: crate::run::StartedBy::Operator,
1109 task: Some(parent.id.clone()),
1110 });
1111 s.origin = Some(Origin {
1112 by: crate::run::StartedBy::Operator,
1113 task: Some("gone".to_owned()),
1114 });
1115 s.followup_generation = Some(MAX_FOLLOWUP_GENERATION);
1116 let out = file(&mut s, "u", &q).unwrap();
1117 assert!(out.filed.is_empty());
1118 assert!(!out.capped.is_empty());
1119 assert_eq!(q.list().len(), 1);
1120 assert!(
1121 s.events
1122 .iter()
1123 .any(|e| e.message.contains("generation cap"))
1124 );
1125 }
1126
1127 #[test]
1128 fn a_deeper_task_files_one_generation_further() {
1129 let dir = tempfile::tempdir().unwrap();
1130 let q = Queue::at(dir.path().join("queue"));
1131 let mut parent = Task::new(
1132 "p".to_owned(),
1133 "i".to_owned(),
1134 PathBuf::from("/repo"),
1135 Source::Human,
1136 );
1137 q.put(&mut parent).unwrap();
1138 let mut s = merged(two_seats());
1139 s.origin = Some(Origin {
1140 by: crate::run::StartedBy::Operator,
1141 task: Some(parent.id.clone()),
1142 });
1143 file(&mut s, "u", &q).unwrap();
1144 let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
1145 assert_eq!(t.followup.unwrap().origin_task, Some(parent.id));
1146 }
1147
1148 #[test]
1149 fn the_chat_is_inherited_from_the_run_even_when_the_parent_is_gone() {
1150 let dir = tempfile::tempdir().unwrap();
1151 let q = Queue::at(dir.path().join("queue"));
1152 let mut s = merged(two_seats());
1153 s.origin = Some(Origin {
1154 by: crate::run::StartedBy::Operator,
1155 task: Some("gone".to_owned()),
1156 });
1157 s.followup_generation = Some(1);
1158 s.origin_chat = Some("talk-1".to_owned());
1159 file(&mut s, "u", &q).unwrap();
1160 let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
1161 assert_eq!(t.origin_chat.as_deref(), Some("talk-1"));
1162 }
1163
1164 #[test]
1165 fn a_parent_without_the_field_passes_on_what_its_ancestry_resolves() {
1166 let dir = tempfile::tempdir().unwrap();
1167 let q = Queue::at(dir.path().join("queue"));
1168 let mut parent = Task::new(
1169 "p".to_owned(),
1170 "i".to_owned(),
1171 PathBuf::from("/repo"),
1172 Source::Agent {
1173 run: "talk-2".to_owned(),
1174 node: crate::queue::CHAT_NODE.to_owned(),
1175 },
1176 );
1177 parent.origin_chat = None;
1178 q.put(&mut parent).unwrap();
1179 let mut s = merged(two_seats());
1180 s.origin = Some(Origin {
1181 by: crate::run::StartedBy::Operator,
1182 task: Some(parent.id.clone()),
1183 });
1184 file(&mut s, "u", &q).unwrap();
1185 let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
1186 assert_eq!(t.origin_chat.as_deref(), Some("talk-2"));
1187 }
1188
1189 const PR: &str = "https://github.com/o/r/pull/473";
1190
1191 fn manual(text: &str) -> Task {
1192 Task::new(
1193 "manual".to_owned(),
1194 text.to_owned(),
1195 PathBuf::from("/repo"),
1196 Source::Human,
1197 )
1198 }
1199
1200 fn filed_with(text: &str) -> (Outcome, RunState, Queue, String, tempfile::TempDir) {
1202 let dir = tempfile::tempdir().unwrap();
1203 let q = Queue::at(dir.path().join("queue"));
1204 let mut t = manual(text);
1205 t.status = crate::queue::TaskStatus::Done;
1206 q.put(&mut t).unwrap();
1207 let mut s = merged(two_seats());
1208 let out = file(&mut s, PR, &q).unwrap();
1209 (out, s, q, t.id, dir)
1210 }
1211
1212 #[test]
1213 fn a_task_naming_the_pr_url_and_ids_covers_the_group() {
1214 let (out, s, _q, id, _d) = filed_with(&format!("Fix R3-1-1 and R3-2-1 from {PR}"));
1215 assert_eq!(out.filed.len(), 1, "{out:?}");
1217 assert_eq!(
1218 out.covered,
1219 vec![
1220 ("R3-1-1".to_owned(), id.clone()),
1221 ("R3-2-1".to_owned(), id.clone())
1222 ]
1223 );
1224 assert!(out.capped.is_empty());
1225 assert!(
1226 s.events
1227 .iter()
1228 .any(|e| e.message.contains("already covered"))
1229 );
1230 let body = comment_body(&s, &out);
1231 assert!(body.contains(&format!("R3-1-1: already covered by task `{id}`")));
1232 }
1233
1234 #[test]
1235 fn the_hash_form_covers_but_a_prefix_number_does_not() {
1236 let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in PR #473");
1237 assert_eq!(out.covered.len(), 2);
1238 let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in #47");
1239 assert!(out.covered.is_empty());
1240 assert_eq!(out.filed.len(), 2);
1241 let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in #4731");
1242 assert!(out.covered.is_empty());
1243 }
1244
1245 #[test]
1246 fn an_id_without_the_pr_does_not_cover() {
1247 let (out, ..) = filed_with("R3-1-1 and R3-2-1 are bad");
1248 assert!(out.covered.is_empty());
1249 assert_eq!(out.filed.len(), 2);
1250 }
1251
1252 #[test]
1253 fn an_id_prefix_does_not_cover() {
1254 let (out, ..) = filed_with(&format!("R3-1-10 R3-2-10 in {PR}"));
1255 assert!(out.covered.is_empty());
1256 }
1257
1258 #[test]
1259 fn partial_coverage_still_files() {
1260 let (out, ..) = filed_with(&format!("R3-1-1 in {PR}"));
1261 assert!(out.covered.is_empty());
1262 assert_eq!(out.filed.len(), 2);
1263 }
1264
1265 #[test]
1266 fn another_followups_findings_cover() {
1267 let dir = tempfile::tempdir().unwrap();
1268 let q = Queue::at(dir.path().join("queue"));
1269 let mut s = merged(two_seats());
1270 let mut other = manual("x");
1271 other.followup = Some(FollowUp {
1272 run: s.id.clone(),
1273 origin_task: None,
1274 pr: PR.to_owned(),
1275 findings: vec!["R3-1-1".to_owned(), "R3-2-1".to_owned()],
1276 generation: 1,
1277 });
1278 q.put(&mut other).unwrap();
1279 let out = file(&mut s, PR, &q).unwrap();
1280 assert_eq!(out.covered.len(), 2, "{out:?}");
1281 assert_eq!(out.filed.len(), 1);
1282 }
1283
1284 #[test]
1285 fn github_text_fixed_followup_comment_passes() {
1286 let state = merged(two_seats());
1287 let body = comment_body(&state, &Outcome::default());
1288 assert!(crate::github_text::check("", &body).is_empty());
1289 }
1290
1291 #[test]
1292 fn a_fully_covered_comment_lists_only_the_covered() {
1293 let (out, mut s, ..) = filed_with(&format!("R3-1-1 R3-2-1 {PR}"));
1294 s.followups.clear();
1295 let body = comment_body(&s, &out);
1296 assert!(body.contains("already covered by task"));
1297 assert!(!body.contains("filed as follow-up"));
1298 }
1299
1300 #[test]
1301 fn an_id_next_to_japanese_prose_still_covers() {
1302 let (out, ..) = filed_with("PR #473 の R3-1-1を修正、R3-2-1も対応");
1303 assert_eq!(out.covered.len(), 2, "{out:?}");
1304 }
1305
1306 fn deputy_task(run: &str, title: &str, text: &str, reason: &str) -> Task {
1309 let mut t = Task::new(
1310 title.to_owned(),
1311 text.to_owned(),
1312 PathBuf::from("/repo"),
1313 Source::Agent {
1314 run: run.to_owned(),
1315 node: crate::deputy::NODE.to_owned(),
1316 },
1317 );
1318 t.hold_manual(Some(reason.to_owned()));
1319 t
1320 }
1321
1322 fn status_of(q: &Queue, id: &str) -> crate::queue::TaskStatus {
1323 q.get(id).unwrap().status
1324 }
1325
1326 #[test]
1327 fn a_deputy_task_is_released_once_and_stamped() {
1328 let dir = tempfile::tempdir().unwrap();
1329 let q = Queue::at(dir.path().join("queue"));
1330 let mut s = merged(two_seats());
1331 s.followup_generation = Some(0);
1332 let mut t = deputy_task(
1333 &s.id,
1334 "Unrelated work",
1335 "do the thing",
1336 &format!("after {PR}"),
1337 );
1338 q.put(&mut t).unwrap();
1339 settle_deputy_tasks(&mut s, PR, &q, true);
1340 let got = q.get(&t.id).unwrap();
1341 assert_eq!(got.status, crate::queue::TaskStatus::Queued);
1342 assert!(got.hold_reason.is_none());
1343 let f = got.followup.unwrap();
1344 assert_eq!((f.run.as_str(), f.generation), (s.id.as_str(), 1));
1345 assert_eq!(s.deputy_followups, vec![t.id.clone()]);
1346 let events = s.events.len();
1347 settle_deputy_tasks(&mut s, PR, &q, true);
1349 assert_eq!(s.events.len(), events);
1350 s.deputy_followups.clear();
1351 settle_deputy_tasks(&mut s, PR, &q, true);
1352 assert_eq!(
1353 s.deputy_followups,
1354 vec![t.id.clone()],
1355 "rebuilt from the queue"
1356 );
1357 assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Queued);
1358 }
1359
1360 #[test]
1361 fn unrelated_held_tasks_are_never_released() {
1362 let dir = tempfile::tempdir().unwrap();
1363 let q = Queue::at(dir.path().join("queue"));
1364 let mut s = merged(two_seats());
1365 s.followup_generation = Some(0);
1366 let mut other_run = deputy_task("someone-else", "a", "b", &format!("after {PR}"));
1367 let mut other_pr = deputy_task(&s.id, "c", "d", "after https://github.com/o/r/pull/4731");
1368 let mut no_reason = deputy_task(&s.id, "e", "f", "x");
1369 no_reason.hold_reason = None;
1370 let mut human = manual("g");
1371 human.hold_manual(Some(format!("waiting for {PR}")));
1372 let mut queued = deputy_task(&s.id, "h", "i", &format!("after {PR}"));
1373 queued.release();
1374 let ids: Vec<String> = [
1375 &mut other_run,
1376 &mut other_pr,
1377 &mut no_reason,
1378 &mut human,
1379 &mut queued,
1380 ]
1381 .into_iter()
1382 .map(|t| {
1383 q.put(t).unwrap();
1384 t.id.clone()
1385 })
1386 .collect();
1387 settle_deputy_tasks(&mut s, PR, &q, true);
1388 for id in &ids[..4] {
1389 assert_eq!(status_of(&q, id), crate::queue::TaskStatus::Held, "{id}");
1390 assert!(q.get(id).unwrap().followup.is_none());
1391 }
1392 assert!(s.deputy_followups.is_empty());
1393 }
1394
1395 #[test]
1396 fn the_switch_off_leaves_the_task_held() {
1397 let dir = tempfile::tempdir().unwrap();
1398 let q = Queue::at(dir.path().join("queue"));
1399 let mut s = merged(two_seats());
1400 s.followup_generation = Some(0);
1401 let mut t = deputy_task(&s.id, "x", "y", &format!("after {PR}"));
1402 q.put(&mut t).unwrap();
1403 settle_deputy_tasks(&mut s, PR, &q, false);
1404 assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Held);
1405 }
1406
1407 #[test]
1408 fn the_generation_cap_applies_to_released_tasks() {
1409 let dir = tempfile::tempdir().unwrap();
1410 let q = Queue::at(dir.path().join("queue"));
1411 let mut s = merged(two_seats());
1412 s.followup_generation = Some(MAX_FOLLOWUP_GENERATION);
1413 let mut t = deputy_task(&s.id, "x", "y", &format!("after {PR}"));
1414 q.put(&mut t).unwrap();
1415 settle_deputy_tasks(&mut s, PR, &q, true);
1416 let got = q.get(&t.id).unwrap();
1417 assert_eq!(got.status, crate::queue::TaskStatus::Held);
1418 assert!(got.hold_reason.unwrap().starts_with(CAPPED));
1419 let events = s.events.len();
1420 settle_deputy_tasks(&mut s, PR, &q, true);
1421 assert_eq!(s.events.len(), events, "marked once");
1422 let mut s2 = merged(two_seats());
1423 s2.followup_generation = Some(MAX_FOLLOWUP_GENERATION - 1);
1424 let mut t2 = deputy_task(&s2.id, "x", "y", &format!("after {PR}"));
1425 q.put(&mut t2).unwrap();
1426 settle_deputy_tasks(&mut s2, PR, &q, true);
1427 assert_eq!(
1428 q.get(&t2.id).unwrap().followup.unwrap().generation,
1429 MAX_FOLLOWUP_GENERATION
1430 );
1431 }
1432
1433 #[test]
1434 fn deputy_first_the_owners_task_runs_and_the_automatic_one_is_not_filed() {
1435 let dir = tempfile::tempdir().unwrap();
1436 let q = Queue::at(dir.path().join("queue"));
1437 let mut s = merged(two_seats());
1438 s.followup_generation = Some(0);
1439 let mut t = deputy_task(
1440 &s.id,
1441 "Fix the waiter",
1442 "R3-1-1 at src/waiter.rs:212 loses replies",
1443 &format!("after {PR}"),
1444 );
1445 q.put(&mut t).unwrap();
1446 settle_deputy_tasks(&mut s, PR, &q, true);
1447 let out = file(&mut s, PR, &q).unwrap();
1448 assert_eq!(out.covered.len(), 2, "{out:?}");
1449 assert_eq!(out.filed.len(), 1, "{out:?}");
1451 let runnable: Vec<_> = q
1452 .list()
1453 .into_iter()
1454 .filter(|t| {
1455 t.status == crate::queue::TaskStatus::Queued
1456 && t.followup
1457 .as_ref()
1458 .is_some_and(|f| f.findings.iter().any(|x| x == "R3-1-1"))
1459 })
1460 .collect();
1461 assert_eq!(runnable.len(), 1);
1462 assert_eq!(runnable[0].id, t.id);
1463 }
1464
1465 #[test]
1466 fn followup_first_a_queued_automatic_task_gives_way_to_the_owners() {
1467 let dir = tempfile::tempdir().unwrap();
1468 let q = Queue::at(dir.path().join("queue"));
1469 let mut s = merged(two_seats());
1470 s.followup_generation = Some(0);
1471 file(&mut s, PR, &q).unwrap();
1472 let mut t = deputy_task(
1473 &s.id,
1474 "Waiter replies",
1475 "see R3-2-1",
1476 &format!("after {PR}"),
1477 );
1478 q.put(&mut t).unwrap();
1479 settle_deputy_tasks(&mut s, PR, &q, true);
1480 let all = q.list();
1481 let live: Vec<_> = all
1482 .iter()
1483 .filter(|t| {
1484 t.status == crate::queue::TaskStatus::Queued
1485 && t.followup
1486 .as_ref()
1487 .is_some_and(|f| f.findings.iter().any(|x| x == "R3-2-1"))
1488 })
1489 .collect();
1490 assert_eq!(live.len(), 1);
1491 assert_eq!(live[0].id, t.id);
1492 let dropped = all
1493 .iter()
1494 .find(|a| {
1495 a.id != t.id
1496 && a.followup
1497 .as_ref()
1498 .is_some_and(|f| f.findings.iter().any(|x| x == "R3-2-1"))
1499 })
1500 .unwrap();
1501 assert_eq!(dropped.status, crate::queue::TaskStatus::Held);
1502 assert!(
1503 dropped
1504 .hold_reason
1505 .as_ref()
1506 .unwrap()
1507 .starts_with(SUPERSEDED)
1508 );
1509 }
1510
1511 #[test]
1512 fn followup_first_a_finished_automatic_task_supersedes_the_deputys() {
1513 let dir = tempfile::tempdir().unwrap();
1514 let q = Queue::at(dir.path().join("queue"));
1515 let mut s = merged(two_seats());
1516 s.followup_generation = Some(0);
1517 file(&mut s, PR, &q).unwrap();
1518 for mut a in q.list() {
1519 a.status = crate::queue::TaskStatus::Done;
1520 q.put(&mut a).unwrap();
1521 }
1522 let mut t = deputy_task(&s.id, "title R3-1-1", "no ids here", &format!("after {PR}"));
1524 t.instruction = "nothing".to_owned();
1525 q.put(&mut t).unwrap();
1526 settle_deputy_tasks(&mut s, PR, &q, true);
1527 let got = q.get(&t.id).unwrap();
1528 assert_eq!(got.status, crate::queue::TaskStatus::Held);
1529 assert!(got.followup.is_none());
1530 let reason = got.hold_reason.unwrap();
1531 assert!(reason.starts_with(SUPERSEDED), "{reason}");
1532 assert!(reason.contains(PR));
1533 let events = s.events.len();
1534 settle_deputy_tasks(&mut s, PR, &q, true);
1535 assert_eq!(s.events.len(), events, "judged once");
1536 }
1537
1538 #[test]
1539 fn a_held_deputy_task_is_superseded_by_a_later_filing_when_the_switch_is_off() {
1540 let dir = tempfile::tempdir().unwrap();
1541 let q = Queue::at(dir.path().join("queue"));
1542 let mut s = merged(two_seats());
1543 s.followup_generation = Some(0);
1544 let mut t = deputy_task(&s.id, "x", "R3-1-1 here", &format!("after {PR}"));
1545 q.put(&mut t).unwrap();
1546 settle_deputy_tasks(&mut s, PR, &q, false);
1547 assert!(
1548 !q.get(&t.id)
1549 .unwrap()
1550 .hold_reason
1551 .unwrap()
1552 .starts_with(SUPERSEDED)
1553 );
1554 file(&mut s, PR, &q).unwrap();
1555 settle_deputy_tasks(&mut s, PR, &q, false);
1556 let got = q.get(&t.id).unwrap();
1557 assert_eq!(got.status, crate::queue::TaskStatus::Held);
1558 assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
1559 }
1560
1561 #[test]
1562 fn the_comment_lists_released_deputy_tasks() {
1563 let mut s = merged(two_seats());
1564 s.deputy_followups.push("abcd-1".to_owned());
1565 let body = comment_body(&s, &Outcome::default());
1566 assert!(body.contains("`abcd-1`"));
1567 assert!(!body.contains("already covered"));
1568 assert!(crate::github_text::check("", &body).is_empty());
1569 }
1570
1571 #[test]
1572 fn a_deputy_task_over_two_automatic_ones_holds_both() {
1573 let dir = tempfile::tempdir().unwrap();
1574 let q = Queue::at(dir.path().join("queue"));
1575 let mut s = merged(two_seats());
1576 s.followup_generation = Some(0);
1577 file(&mut s, PR, &q).unwrap();
1578 let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
1579 q.put(&mut t).unwrap();
1580 settle_deputy_tasks(&mut s, PR, &q, true);
1581 assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Queued);
1582 let live = q
1583 .list()
1584 .into_iter()
1585 .filter(|x| x.status == crate::queue::TaskStatus::Queued)
1586 .count();
1587 assert_eq!(live, 1, "only the owner's task still runs");
1588 }
1589
1590 #[test]
1591 fn a_claimed_automatic_task_is_not_touched_and_the_deputys_stays_held() {
1592 let dir = tempfile::tempdir().unwrap();
1593 let q = Queue::at(dir.path().join("queue"));
1594 let mut s = merged(two_seats());
1595 s.followup_generation = Some(0);
1596 file(&mut s, PR, &q).unwrap();
1597 let auto = q
1598 .list()
1599 .into_iter()
1600 .find(|x| {
1601 x.followup
1602 .as_ref()
1603 .is_some_and(|f| f.findings.iter().any(|i| i == "R3-1-1"))
1604 })
1605 .unwrap();
1606 let _claim = q.claim(&auto.id).unwrap();
1607 let mut t = deputy_task(&s.id, "x", "R3-1-1", &format!("after {PR}"));
1608 q.put(&mut t).unwrap();
1609 settle_deputy_tasks(&mut s, PR, &q, true);
1610 assert_eq!(status_of(&q, &auto.id), crate::queue::TaskStatus::Queued);
1611 let got = q.get(&t.id).unwrap();
1612 assert_eq!(got.status, crate::queue::TaskStatus::Held);
1613 assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
1614 }
1615
1616 #[test]
1617 fn a_failed_hold_restores_the_automatic_tasks_already_held() {
1618 let dir = tempfile::tempdir().unwrap();
1619 let q = Queue::at(dir.path().join("queue"));
1620 let mut s = merged(two_seats());
1621 s.followup_generation = Some(0);
1622 file(&mut s, PR, &q).unwrap();
1623 let autos = q.list();
1624 assert_eq!(autos.len(), 2);
1625 let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
1626 q.put(&mut t).unwrap();
1627 let last = autos.last().unwrap().id.clone();
1629 let tmp = dir.path().join("queue").join(format!("{last}.json.tmp"));
1630 std::fs::create_dir_all(&tmp).unwrap();
1631 settle_deputy_tasks(&mut s, PR, &q, true);
1632 for a in &autos {
1633 let got = q.get(&a.id).unwrap();
1634 assert_eq!(got.status, crate::queue::TaskStatus::Queued, "{}", a.id);
1635 assert_eq!(got.attempts, a.attempts);
1636 }
1637 let got = q.get(&t.id).unwrap();
1638 assert_eq!(got.status, crate::queue::TaskStatus::Held);
1639 assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
1640 }
1641
1642 #[test]
1643 fn a_hold_left_by_an_earlier_failed_pass_is_restored_on_the_next_failure() {
1644 let dir = tempfile::tempdir().unwrap();
1645 let q = Queue::at(dir.path().join("queue"));
1646 let mut s = merged(two_seats());
1647 s.followup_generation = Some(0);
1648 file(&mut s, PR, &q).unwrap();
1649 let autos = q.list();
1650 let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
1651 q.put(&mut t).unwrap();
1652 let why = format!(
1654 "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {PR}",
1655 t.id
1656 );
1657 q.modify(&autos[0].id, |x| {
1658 x.hold_manual(Some(why));
1659 true
1660 })
1661 .unwrap();
1662 let tmp = dir
1663 .path()
1664 .join("queue")
1665 .join(format!("{}.json.tmp", autos[1].id));
1666 std::fs::create_dir_all(&tmp).unwrap();
1667 settle_deputy_tasks(&mut s, PR, &q, true);
1668 for a in &autos {
1669 let got = q.get(&a.id).unwrap();
1670 assert_eq!(got.status, crate::queue::TaskStatus::Queued, "{}", a.id);
1671 assert!(got.hold_reason.is_none());
1672 }
1673 assert!(
1674 q.get(&t.id)
1675 .unwrap()
1676 .hold_reason
1677 .unwrap()
1678 .starts_with(SUPERSEDED)
1679 );
1680 }
1681
1682 #[test]
1683 fn a_blocked_takeover_restores_a_hold_left_by_an_earlier_pass() {
1684 let dir = tempfile::tempdir().unwrap();
1685 let q = Queue::at(dir.path().join("queue"));
1686 let mut s = merged(two_seats());
1687 s.followup_generation = Some(0);
1688 file(&mut s, PR, &q).unwrap();
1689 let autos = q.list();
1690 let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
1691 q.put(&mut t).unwrap();
1692 let why = format!(
1693 "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {PR}",
1694 t.id
1695 );
1696 q.modify(&autos[0].id, |x| {
1697 x.hold_manual(Some(why));
1698 true
1699 })
1700 .unwrap();
1701 let _claim = q.claim(&autos[1].id).unwrap();
1702 settle_deputy_tasks(&mut s, PR, &q, true);
1703 assert_eq!(
1704 status_of(&q, &autos[0].id),
1705 crate::queue::TaskStatus::Queued
1706 );
1707 assert!(
1708 q.get(&t.id)
1709 .unwrap()
1710 .hold_reason
1711 .unwrap()
1712 .starts_with(SUPERSEDED)
1713 );
1714 }
1715}