1use std::path::Path;
10
11use anyhow::Result;
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 git,
17 queue::{Queue, Task, TaskStatus},
18 run::{
19 CommandOutcome, GateRepairE2e, MergeRepairPhase, RunState, RunStatus, VerificationEvidence,
20 },
21};
22
23pub const GRANT_ATTEMPTS: usize = 1;
25
26pub const MAX_GRANTS: usize = 4;
28
29pub const EXHAUSTED_DETAIL: &str = "landing base synchronization budget exhausted";
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Checkpoint {
35 pub published: String,
37 pub from: String,
39 pub base: String,
41 pub head: String,
43 pub attempt: usize,
45 pub at: Timestamp,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub previous: Option<Box<Checkpoint>>,
50}
51
52pub(crate) async fn validate_heads(
54 state: &RunState,
55 stop: Option<&Stop>,
56 local: &str,
57 published: &str,
58) -> anyhow::Result<()> {
59 if let Some(stop) = stop {
60 anyhow::ensure!(
61 stop.head == local && stop.pr_head == published,
62 "retained or published HEAD differs from the recorded stop"
63 );
64 }
65 if local == published {
66 return Ok(());
67 }
68 let stop = stop.ok_or_else(|| {
69 anyhow::anyhow!(
70 "retained HEAD differs from published PR head without a recorded checkpoint stop"
71 )
72 })?;
73 let checkpoint = state
74 .land_sync_checkpoint
75 .as_ref()
76 .filter(|c| stop.checkpoint.as_ref() == Some(*c))
77 .ok_or_else(|| anyhow::anyhow!("retained HEAD differs from published PR head without launcher checkpoint provenance"))?;
78 anyhow::ensure!(
79 checkpoint.head == local
80 && checkpoint.attempt == state.land_sync_attempts
81 && state.land_rebase_from.is_none()
82 && state.land_sync_target.is_none(),
83 "retained HEAD does not match launcher checkpoint provenance"
84 );
85 let mut current = checkpoint;
86 loop {
87 anyhow::ensure!(
88 current.published == published
89 && current.attempt > 0
90 && git::ancestry(&state.repo, ¤t.base, ¤t.head).await?
91 && git::ancestry(&state.repo, ¤t.base, &stop.tip).await?,
92 "retained HEAD does not match launcher checkpoint provenance"
93 );
94 match current.previous.as_deref() {
95 Some(previous) => {
96 anyhow::ensure!(
97 previous.head == current.from && previous.attempt < current.attempt,
98 "landing checkpoint source does not match the previous launcher result"
99 );
100 current = previous;
101 }
102 None => {
103 anyhow::ensure!(
104 current.from == published,
105 "landing checkpoint source does not match the published head"
106 );
107 break;
108 }
109 }
110 }
111 Ok(())
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct Stop {
117 pub attempts: usize,
119 pub limit: usize,
121 pub head: String,
123 pub pr_head: String,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub checkpoint: Option<Checkpoint>,
128 pub pr_url: String,
130 pub pr_number: u64,
132 pub tip: String,
134 pub detail: String,
136 pub at: Timestamp,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct Scope {
143 pub tip: String,
145 pub instruction: String,
147 pub assignment: usize,
149 pub pr_head: String,
151 pub pr_url: String,
153 pub pr_number: u64,
155 pub grant_index: usize,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct ArchivedVerification {
162 pub archived_at: Timestamp,
164 pub head: String,
166 pub gate_head: Option<String>,
168 pub gate_ran: bool,
170 pub gate: Vec<CommandOutcome>,
172 #[serde(default)]
174 pub pre_gate: Vec<CommandOutcome>,
175 #[serde(default)]
177 pub pre_gate_commit: Option<String>,
178 pub head_e2e: Option<GateRepairE2e>,
180 pub gate_repair_e2e: Option<GateRepairE2e>,
182 #[serde(default)]
184 pub review_verified_heads: Vec<(usize, Option<String>)>,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct Authorization {
190 pub request: String,
192 pub task: String,
194 pub run: String,
196 pub stop: Stop,
198 pub scope: Scope,
200 #[serde(default)]
202 pub decision: Option<Timestamp>,
203 #[serde(default)]
205 pub generation: Option<u64>,
206 pub granted_attempts: usize,
208 pub at: Timestamp,
210 pub consumed: bool,
212 #[serde(default)]
214 pub consumed_at: Option<Timestamp>,
215 #[serde(default)]
217 pub invalidated: Option<String>,
218 #[serde(default)]
220 pub archived_verification: Option<ArchivedVerification>,
221}
222
223impl Authorization {
224 pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
226 self.invalidated = Some(reason.into());
227 self.consumed = true;
228 if self.consumed_at.is_none() {
229 self.consumed_at = Some(Timestamp::now());
230 }
231 }
232}
233
234#[derive(Debug, Clone, Default, Serialize, Deserialize)]
236pub struct Recovery {
237 #[serde(default)]
239 pub extra_attempts: usize,
240 #[serde(default)]
242 pub stops: Vec<Stop>,
243 #[serde(default)]
245 pub stop: Option<Stop>,
246 #[serde(default)]
248 pub authorizations: Vec<Authorization>,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct ObservedPr {
254 pub url: String,
256 pub number: u64,
258 pub open: bool,
260 pub head: String,
262 pub base_branch: Option<String>,
264}
265
266pub trait PrObserver {
268 fn observe_pr(
270 &self,
271 repo: &Path,
272 pr_url: &str,
273 ) -> impl std::future::Future<Output = Result<ObservedPr>> + Send;
274}
275
276#[derive(Debug, Default, Clone, Copy)]
278pub struct GhPrObserver;
279
280impl PrObserver for GhPrObserver {
281 async fn observe_pr(&self, repo: &Path, pr_url: &str) -> Result<ObservedPr> {
282 crate::land::observe_pr_summary(repo, pr_url).await
283 }
284}
285
286fn matches_exhausted_detail(detail: &str) -> bool {
287 let trimmed = detail.trim();
288 trimmed == EXHAUSTED_DETAIL
289 || trimmed == format!("could not synchronize landing base: {EXHAUSTED_DETAIL}")
290}
291
292fn matches_exhausted_event(message: &str) -> bool {
293 let trimmed = message.trim();
294 trimmed == format!("stopped: could not synchronize landing base: {EXHAUSTED_DETAIL}")
295 || trimmed == format!("stopped: {EXHAUSTED_DETAIL}")
296 || trimmed == format!("gave up: {EXHAUSTED_DETAIL}")
297 || trimmed == format!("gave up: could not synchronize landing base: {EXHAUSTED_DETAIL}")
298}
299
300fn legacy_exhausted_diagnostic(state: &RunState) -> bool {
301 if let Some(last_land) = state.events.iter().rev().find(|e| e.node == "land") {
302 matches_exhausted_event(&last_land.message)
303 } else {
304 state
305 .merge
306 .as_ref()
307 .is_some_and(|m| !m.ok && matches_exhausted_detail(&m.detail))
308 }
309}
310
311fn exhausted_stop_timestamp(state: &RunState) -> Timestamp {
312 state
313 .events
314 .iter()
315 .rev()
316 .find(|e| e.node == "land" && matches_exhausted_event(&e.message))
317 .map_or(state.updated_at, |e| e.at)
318}
319
320impl RunState {
321 pub fn land_sync_budget(&self) -> usize {
323 self.config
324 .graph
325 .land_rounds
326 .saturating_add(self.land_sync_recovery.extra_attempts)
327 .saturating_sub(
328 self.land_sync_recovery
329 .authorizations
330 .iter()
331 .filter(|a| a.invalidated.is_some() && a.archived_verification.is_some())
332 .count(),
333 )
334 }
335
336 pub fn land_sync_grants_remaining(&self) -> usize {
338 MAX_GRANTS.saturating_sub(self.land_sync_recovery.extra_attempts)
339 }
340
341 pub fn land_sync_exhausted(&self) -> bool {
344 if self.status != RunStatus::Blocked {
345 return false;
346 }
347 if self.released_to.is_some()
348 || self.retired_to.is_some()
349 || self.pr_taken_over_by.is_some()
350 {
351 return false;
352 }
353 if !crate::handover::landing_checkpoint(self)
354 || self.base_sync_blocked()
355 || self.pr_publication_pending
356 {
357 return false;
358 }
359 if self.merge_decision.is_some()
360 || self.resource_block.is_some()
361 || self.sequencer_stop.is_some()
362 || self.land_rebase_from.is_some()
363 || self.land_sync_target.is_some()
364 {
365 return false;
366 }
367 if self.merge_repairs.last().is_some_and(|r| {
368 matches!(
369 r.phase,
370 MergeRepairPhase::Requested
371 | MergeRepairPhase::Fixing
372 | MergeRepairPhase::Reviewing
373 )
374 }) || self
375 .repair_grants
376 .last()
377 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
378 || self
379 .rebase_fixes
380 .iter()
381 .any(|r| r.stop.is_none() && !r.finished)
382 {
383 return false;
384 }
385 if !self.land_sync_pending
386 || self.land_sync_attempts == 0
387 || self.land_sync_attempts < self.land_sync_budget()
388 {
389 return false;
390 }
391 if let Some(stop) = &self.land_sync_recovery.stop {
392 stop.detail == EXHAUSTED_DETAIL
393 && stop.attempts == self.land_sync_attempts
394 && stop.limit == self.land_sync_budget()
395 && self
396 .pr
397 .as_ref()
398 .is_some_and(|pr| pr.url == stop.pr_url && pr.number == stop.pr_number)
399 && self.land_sync_recovery.stops.contains(stop)
400 } else {
401 self.land_sync_recovery
402 .authorizations
403 .last()
404 .is_some_and(|a| {
405 a.invalidated.is_some()
406 && a.archived_verification.is_some()
407 && a.stop.attempts == self.land_sync_attempts
408 })
409 || (self.land_sync_recovery.stops.is_empty()
410 && self.land_sync_recovery.authorizations.is_empty()
411 && legacy_exhausted_diagnostic(self))
412 }
413 }
414
415 pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
417 self.land_sync_recovery
418 .authorizations
419 .iter()
420 .any(|a| !a.consumed && a.invalidated.is_none())
421 }
422
423 pub fn land_sync_recovery_pending(&self) -> bool {
425 self.land_sync_exhausted()
426 && self
427 .land_sync_recovery
428 .authorizations
429 .last()
430 .is_some_and(|a| {
431 !a.consumed
432 && a.invalidated.is_none()
433 && a.run == self.id
434 && a.granted_attempts == GRANT_ATTEMPTS
435 && a.scope.grant_index == self.land_sync_recovery.extra_attempts
436 && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
437 })
438 }
439
440 pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
443 self.status.resumable()
444 && self
445 .land_sync_recovery
446 .authorizations
447 .last()
448 .is_some_and(|a| {
449 a.consumed
450 && a.invalidated.is_none()
451 && a.archived_verification.is_some()
452 && self.land_sync_attempts == a.stop.attempts
453 && self.land_sync_recovery.extra_attempts
454 == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
455 })
456 }
457
458 pub fn land_sync_next_action(&self) -> String {
460 let attempts = self.land_sync_attempts;
461 let limit = self.land_sync_budget();
462 let grants = self.land_sync_recovery.extra_attempts;
463 let head = self
464 .land_sync_recovery
465 .stop
466 .as_ref()
467 .map(|s| s.head.as_str())
468 .or(self.pr_pushed_head.as_deref())
469 .unwrap_or("<full-head-sha>");
470 if let Some(stop) = &self.land_sync_recovery.stop
471 && stop.head != stop.pr_head
472 && (stop.checkpoint != self.land_sync_checkpoint
473 || stop.checkpoint.as_ref().is_none_or(|c| {
474 c.head != stop.head || c.published != stop.pr_head || c.attempt != stop.attempts
475 }))
476 {
477 return "Retained HEAD differs from the published PR head without matching launcher checkpoint provenance; inspect the retained branch and PR".into();
478 }
479 if let Some(reason) = self
480 .land_sync_recovery
481 .authorizations
482 .last()
483 .and_then(|a| a.invalidated.as_ref())
484 && !self.land_sync_recovery_pending()
485 {
486 if self.land_sync_grants_remaining() == 0 {
487 return format!(
488 "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
489 );
490 }
491 return format!(
492 "Landing base-sync recovery approval invalidated: {reason}. Authorize a new bounded attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} grants used)",
493 self.id
494 );
495 }
496 if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
497 return format!(
498 "Landing base-sync recovery approval recorded; resume the retained run to spend {GRANT_ATTEMPTS} approved synchronization attempt ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)"
499 );
500 }
501 if self.land_sync_grants_remaining() == 0 {
502 return format!(
503 "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
504 );
505 }
506 format!(
507 "Authorize {GRANT_ATTEMPTS} bounded landing base-sync attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)",
508 self.id
509 )
510 }
511
512 pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
514 let Some(pr) = self.pr.as_ref() else {
515 return;
516 };
517 let limit = self.land_sync_budget();
518 let checkpoint = self.land_sync_checkpoint.as_ref().filter(|c| {
519 c.head.eq_ignore_ascii_case(head) && c.published.eq_ignore_ascii_case(pr_head)
520 });
521 if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
522 s.attempts == self.land_sync_attempts
523 && s.limit == limit
524 && s.head.eq_ignore_ascii_case(head)
525 && s.pr_head.eq_ignore_ascii_case(pr_head)
526 && s.checkpoint.as_ref() == checkpoint
527 && s.pr_url == pr.url
528 && s.pr_number == pr.number
529 && s.detail == EXHAUSTED_DETAIL
530 }) {
531 return;
532 }
533 let at = exhausted_stop_timestamp(self);
534 let stop = Stop {
535 attempts: self.land_sync_attempts,
536 limit,
537 head: head.to_ascii_lowercase(),
538 pr_head: pr_head.to_ascii_lowercase(),
539 checkpoint: checkpoint.cloned(),
540 pr_url: pr.url.clone(),
541 pr_number: pr.number,
542 tip: tip.to_ascii_lowercase(),
543 detail: EXHAUSTED_DETAIL.to_owned(),
544 at,
545 };
546 if !self.land_sync_recovery.stops.contains(&stop) {
547 self.land_sync_recovery.stops.push(stop.clone());
548 }
549 self.land_sync_recovery.stop = Some(stop);
550 }
551
552 pub(crate) fn consume_land_sync_recovery(
558 &mut self,
559 head: &str,
560 pr_head: &str,
561 ) -> std::result::Result<(), String> {
562 if !self.land_sync_recovery_pending() {
563 return Err("no matching pending landing base-sync recovery authorization".into());
564 }
565 let now = Timestamp::now();
566 let granted = self
567 .land_sync_recovery
568 .authorizations
569 .last()
570 .map(|a| a.granted_attempts)
571 .unwrap_or(0);
572 let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
573 return Err("landing base-sync grant counter overflow".into());
574 };
575 if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
576 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
577 auth.refuse(format!(
578 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
579 self.land_sync_recovery.extra_attempts
580 ));
581 }
582 return Err("lifetime landing base-sync recovery limit reached".into());
583 }
584 let head_mismatch = self
585 .land_sync_recovery
586 .authorizations
587 .last()
588 .is_some_and(|a| {
589 !a.stop.head.eq_ignore_ascii_case(head)
590 || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
591 });
592 if head_mismatch {
593 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
594 auth.refuse(format!(
595 "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
596 auth.stop.head, auth.stop.pr_head
597 ));
598 }
599 return Err("retained or published HEAD changed before consumption".into());
600 }
601
602 let gate = std::mem::take(&mut self.gate);
605 let gate_head = self.gate_head.take();
606 let gate_ran = std::mem::replace(&mut self.gate_ran, false);
607 let head_e2e = self.head_e2e.take();
608 let gate_repair_e2e = self.gate_repair_e2e.take();
609 let pre_gate = std::mem::take(&mut self.pre_gate);
610 let pre_gate_commit = self.pre_gate_commit.take();
611
612 let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
613 for review in &mut self.reviews {
614 review_verified_heads.push((review.round, review.verified_head.take()));
615 }
616
617 if gate_ran || !gate.is_empty() || head_e2e.is_some() {
618 self.verification_history.push(VerificationEvidence {
619 superseded_by: None,
620 archived_at: Some(now),
621 fixes_spent: Some(self.gate_fixes.len()),
622 gate_head: gate_head.clone(),
623 gate_ran,
624 gate: gate.clone(),
625 e2e: head_e2e.clone(),
626 });
627 }
628 if let Some(repair_e2e) = &gate_repair_e2e {
629 self.verification_history.push(VerificationEvidence {
630 superseded_by: None,
631 archived_at: Some(now),
632 fixes_spent: Some(self.gate_fixes.len()),
633 gate_head: None,
634 gate_ran: false,
635 gate: Vec::new(),
636 e2e: Some(repair_e2e.clone()),
637 });
638 }
639
640 let archived = ArchivedVerification {
641 archived_at: now,
642 head: head.to_ascii_lowercase(),
643 gate_head,
644 gate_ran,
645 gate,
646 pre_gate,
647 pre_gate_commit,
648 head_e2e,
649 gate_repair_e2e,
650 review_verified_heads,
651 };
652
653 let auth = self
654 .land_sync_recovery
655 .authorizations
656 .last_mut()
657 .expect("pending authorization exists");
658 auth.consumed = true;
659 auth.consumed_at = Some(now);
660 auth.archived_verification = Some(archived);
661
662 self.land_sync_recovery.extra_attempts = next_extra;
663 self.land_sync_recovery.stop = None;
664 Ok(())
665 }
666}
667
668pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
670 let Some(state) = latest_exhausted_run(queue, task) else {
671 return false;
672 };
673 if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
674 {
675 return false;
676 }
677 let Some(auth) = state.land_sync_recovery.authorizations.last() else {
678 return false;
679 };
680 if task.id != auth.task
681 || !task.assignment_accepts(&state)
682 || task.instruction != auth.scope.instruction
683 || task.operator_decided_at != auth.decision
684 || auth
685 .generation
686 .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
687 || !task.land_sync_recovery_requests.contains(&auth.request)
688 || task.fresh_start
689 || task.review_branch.is_some()
690 || task.pr_recovery.is_some()
691 || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
692 {
693 return false;
694 }
695 task.status = TaskStatus::Queued;
696 task.hold_source = None;
697 task.hold_reason = None;
698 task.held_at = None;
699 true
700}
701
702pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
705 held_run(queue, task).is_some()
706}
707
708pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
711 latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
712}
713
714pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
717 let home = queue.root().parent()?;
718 task.execution_runs()
719 .last()
720 .and_then(|id| RunState::load_under(id, home).ok())
721 .filter(|state| {
722 state.land_sync_exhausted()
723 || state.has_unconsumed_land_sync_authorization()
724 || state.land_sync_unstarted_grant()
725 })
726}
727
728#[derive(Debug)]
735pub(crate) struct ValidationFailure {
736 pub reason: String,
737 pub observation_failed: bool,
738}
739
740impl ValidationFailure {
741 fn observation(reason: String) -> Self {
742 Self {
743 reason,
744 observation_failed: true,
745 }
746 }
747}
748
749impl From<String> for ValidationFailure {
750 fn from(reason: String) -> Self {
751 Self {
752 reason,
753 observation_failed: false,
754 }
755 }
756}
757
758impl From<&str> for ValidationFailure {
759 fn from(reason: &str) -> Self {
760 reason.to_owned().into()
761 }
762}
763
764pub(crate) async fn validate_pending_authorization<O: PrObserver>(
765 home: &Path,
766 state: &RunState,
767 task_override: Option<&Task>,
768 observed_override: Option<&ObservedPr>,
769 observer: &O,
770) -> std::result::Result<(String, String), ValidationFailure> {
771 let unstarted = state.land_sync_unstarted_grant();
772 if !state.land_sync_recovery_pending() && !unstarted {
773 return Err("landing base-sync stop or pending authorization state changed".into());
774 }
775 if let Err(error) = crate::pr_head::ensure_owner(state) {
776 return Err(format!("run ownership check failed: {error:#}").into());
777 }
778 let auth = state
779 .land_sync_recovery
780 .authorizations
781 .last()
782 .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
783 if auth.invalidated.is_some() {
784 return Err("landing base-sync recovery authorization was invalidated".into());
785 }
786 if auth.granted_attempts != GRANT_ATTEMPTS
787 || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
788 {
789 return Err(format!(
790 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
791 state.land_sync_recovery.extra_attempts
792 )
793 .into());
794 }
795
796 if !auth.task.is_empty() {
797 let loaded_task;
798 let task = match task_override {
799 Some(task) => task,
800 None => {
801 loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
802 ValidationFailure::observation(format!(
803 "owning task {} unreadable: {e:#}",
804 auth.task
805 ))
806 })?;
807 &loaded_task
808 }
809 };
810 if task.id != auth.task {
811 return Err("authorization targets a different task".into());
812 }
813 if state
814 .origin
815 .as_ref()
816 .and_then(|o| o.task.as_deref())
817 .is_some_and(|owner| owner != task.id)
818 {
819 return Err("run belongs to another task".into());
820 }
821 if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
822 return Err("run is no longer the task's latest execution".into());
823 }
824 if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
825 return Err("task repository assignment changed since authorization".into());
826 }
827 if task.status == TaskStatus::Done
828 || task.fresh_start
829 || task.review_branch.is_some()
830 || task.pr_recovery.is_some()
831 {
832 return Err("task queue state changed since authorization".into());
833 }
834 if task.instruction != auth.scope.instruction
835 || !crate::daemon::compatible_run_instruction(state, task)
836 {
837 return Err("task instruction changed since authorization".into());
838 }
839 if task.operator_decided_at != auth.decision {
840 return Err("a newer owner decision superseded this recovery authorization".into());
841 }
842 if let Some(generation) = auth.generation
843 && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
844 {
845 return Err("task resumption generation changed since authorization".into());
846 }
847 if task_override.is_some()
848 && !task
849 .resume_override
850 .as_ref()
851 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
852 && !(task.resume_override.is_none()
853 && task.land_sync_recovery_requests.contains(&auth.request))
854 {
855 return Err("task exact-run pin is missing or targets another run".into());
856 }
857 }
858
859 let winner = state
860 .winner()
861 .ok_or_else(|| "run has no retained winner".to_owned())?;
862 let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
863 ValidationFailure::observation(format!(
864 "could not inspect retained worktree cleanliness: {e:#}"
865 ))
866 })?;
867 if !clean {
868 return Err("retained worktree has uncommitted changes".into());
869 }
870 let scratch = home.join("runs").join(&state.id).join("rebase");
871 let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
872 .await
873 .map_err(|e| {
874 ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
875 })?;
876 if rebase_in_progress {
877 return Err("landing rebase is already in progress in scratch worktree".into());
878 }
879 let local_head = git::rev_parse(&winner.worktree, "HEAD")
880 .await
881 .map_err(|e| {
882 ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
883 })?;
884 let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
885 .await
886 .map_err(|e| {
887 ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
888 })?;
889 if local_head != branch_head {
890 return Err("retained worktree HEAD does not match the winner branch ref".into());
891 }
892 if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
893 return Err(format!(
894 "retained HEAD changed from {} to {local_head}",
895 auth.stop.head
896 )
897 .into());
898 }
899 let published = state
900 .pr_pushed_head
901 .as_deref()
902 .ok_or_else(|| "missing saved pr_pushed_head".to_owned())?;
903 if auth.scope.pr_head != published {
904 return Err("authorized PR head does not match saved pr_pushed_head".into());
905 }
906 validate_heads(state, Some(&auth.stop), &local_head, published)
907 .await
908 .map_err(|e| ValidationFailure::from(e.to_string()))?;
909 if !state.pr.as_ref().is_some_and(|pr| {
910 pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
911 }) {
912 return Err("recorded pull request metadata changed since authorization".into());
913 }
914
915 let fetched_pr;
916 let observed = match observed_override {
917 Some(observed) => observed,
918 None => {
919 fetched_pr = observer
920 .observe_pr(&state.repo, &auth.scope.pr_url)
921 .await
922 .map_err(|e| {
923 ValidationFailure::observation(format!(
924 "could not verify open pull request state: {e:#}"
925 ))
926 })?;
927 &fetched_pr
928 }
929 };
930 if !observed.open {
931 return Err("pull request is no longer open".into());
932 }
933 if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
934 return Err("observed pull request does not match authorized pull request".into());
935 }
936 if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
937 return Err(ValidationFailure::observation(
938 "observed pull request head is unreadable".into(),
939 ));
940 }
941 if !observed.head.eq_ignore_ascii_case(published) {
942 return Err(format!(
943 "published PR head changed from {} to {}",
944 auth.scope.pr_head, observed.head
945 )
946 .into());
947 }
948 if observed
949 .base_branch
950 .as_deref()
951 .is_some_and(|b| !b.is_empty() && b != state.base_branch)
952 {
953 return Err("pull request base branch changed since authorization".into());
954 }
955
956 let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
957 .await
958 .map_err(|e| {
959 ValidationFailure::observation(format!(
960 "could not fetch base branch for revalidation: {e:#}"
961 ))
962 })?;
963 if !fetched.ok() {
964 return Err(ValidationFailure::observation(format!(
965 "could not fetch base branch for revalidation: {}",
966 fetched.stderr
967 )));
968 }
969 let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
970 let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
971 ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
972 })?;
973 let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, ¤t_tip)
974 .await
975 .map_err(|e| {
976 ValidationFailure::observation(format!(
977 "could not verify base tip lineage against authorized tip: {e:#}"
978 ))
979 })?;
980 if !descends_scope {
981 return Err(format!(
982 "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
983 auth.scope.tip
984 )
985 .into());
986 }
987 let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, ¤t_tip)
988 .await
989 .map_err(|e| {
990 ValidationFailure::observation(format!(
991 "could not verify base tip lineage against stopped tip: {e:#}"
992 ))
993 })?;
994 if !descends_stop {
995 return Err(format!(
996 "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
997 auth.stop.tip
998 )
999 .into());
1000 }
1001
1002 Ok((local_head, observed.head.clone()))
1003}
1004
1005pub(crate) enum DispatchDecision {
1007 Proceed,
1009 Hold {
1011 reason: String,
1012 state: Box<RunState>,
1013 },
1014}
1015
1016pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
1018 dispatch_check_with(queue, home, task, &GhPrObserver).await
1019}
1020
1021pub(crate) async fn dispatch_check_with<O: PrObserver>(
1023 queue: &Queue,
1024 home: &Path,
1025 task: &Task,
1026 observer: &O,
1027) -> DispatchDecision {
1028 let Some(state) = latest_exhausted_run(queue, task) else {
1029 return DispatchDecision::Proceed;
1030 };
1031 if task
1034 .resume_override
1035 .as_ref()
1036 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
1037 && let Some(pr) = &state.pr
1038 && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
1039 && !observed.open
1040 && observed.url == pr.url
1041 && observed.number == pr.number
1042 {
1043 return DispatchDecision::Proceed;
1044 }
1045 if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
1046 return DispatchDecision::Hold {
1047 reason: format!(
1048 "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
1049 state.land_sync_next_action()
1050 ),
1051 state: Box::new(state),
1052 };
1053 }
1054 match validate_pending_authorization(home, &state, Some(task), None, observer).await {
1055 Ok(_) => DispatchDecision::Proceed,
1056 Err(failure) => {
1057 let reason = failure.reason;
1058 let mut updated = state;
1059 if !failure.observation_failed
1060 && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
1061 && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
1062 && let Ok(claimed) =
1063 crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
1064 && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
1065 && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
1066 && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
1067 && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
1068 && auth.invalidated.is_none()
1069 && updated
1070 .land_sync_recovery
1071 .authorizations
1072 .last()
1073 .is_some_and(|prior| prior.request == auth.request)
1074 {
1075 auth.refuse(&reason);
1076 reloaded.event(
1077 "land-sync-recovery",
1078 format!("dispatch revalidation refused: {reason}"),
1079 );
1080 let _ = reloaded.save_under(home);
1081 updated = reloaded;
1082 }
1083 DispatchDecision::Hold {
1084 reason: format!(
1085 "Landing base-sync recovery refused at dispatch: {reason}. {}",
1086 updated.land_sync_next_action()
1087 ),
1088 state: Box::new(updated),
1089 }
1090 }
1091 }
1092}
1093
1094impl Task {
1095 pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
1097 if !state.land_sync_exhausted() {
1098 return;
1099 }
1100 let stop = state.land_sync_recovery.stop.as_ref();
1101 self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
1102 self.notice_cause("land-sync-exhausted", Some(&state.id), None);
1103 if let Some(cause) = &mut self.hold_notice_cause {
1104 cause.target = Some(match stop {
1105 Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
1106 None => format!(
1107 "legacy:{}:{}:{}",
1108 state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1109 state.land_sync_attempts,
1110 state.land_sync_budget()
1111 ),
1112 });
1113 }
1114 }
1115}