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 Stop {
35 pub attempts: usize,
37 pub limit: usize,
39 pub head: String,
41 pub pr_head: String,
43 pub pr_url: String,
45 pub pr_number: u64,
47 pub tip: String,
49 pub detail: String,
51 pub at: Timestamp,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Scope {
58 pub tip: String,
60 pub instruction: String,
62 pub assignment: usize,
64 pub pr_head: String,
66 pub pr_url: String,
68 pub pr_number: u64,
70 pub grant_index: usize,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ArchivedVerification {
77 pub archived_at: Timestamp,
79 pub head: String,
81 pub gate_head: Option<String>,
83 pub gate_ran: bool,
85 pub gate: Vec<CommandOutcome>,
87 pub head_e2e: Option<GateRepairE2e>,
89 pub gate_repair_e2e: Option<GateRepairE2e>,
91 #[serde(default)]
93 pub review_verified_heads: Vec<(usize, Option<String>)>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Authorization {
99 pub request: String,
101 pub task: String,
103 pub run: String,
105 pub stop: Stop,
107 pub scope: Scope,
109 #[serde(default)]
111 pub decision: Option<Timestamp>,
112 #[serde(default)]
114 pub generation: Option<u64>,
115 pub granted_attempts: usize,
117 pub at: Timestamp,
119 pub consumed: bool,
121 #[serde(default)]
123 pub consumed_at: Option<Timestamp>,
124 #[serde(default)]
126 pub invalidated: Option<String>,
127 #[serde(default)]
129 pub archived_verification: Option<ArchivedVerification>,
130}
131
132impl Authorization {
133 pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
135 self.invalidated = Some(reason.into());
136 self.consumed = true;
137 if self.consumed_at.is_none() {
138 self.consumed_at = Some(Timestamp::now());
139 }
140 }
141}
142
143#[derive(Debug, Clone, Default, Serialize, Deserialize)]
145pub struct Recovery {
146 #[serde(default)]
148 pub extra_attempts: usize,
149 #[serde(default)]
151 pub stops: Vec<Stop>,
152 #[serde(default)]
154 pub stop: Option<Stop>,
155 #[serde(default)]
157 pub authorizations: Vec<Authorization>,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct ObservedPr {
163 pub url: String,
165 pub number: u64,
167 pub open: bool,
169 pub head: String,
171 pub base_branch: Option<String>,
173}
174
175pub trait PrObserver {
177 fn observe_pr(
179 &self,
180 repo: &Path,
181 pr_url: &str,
182 ) -> impl std::future::Future<Output = Result<ObservedPr>> + Send;
183}
184
185#[derive(Debug, Default, Clone, Copy)]
187pub struct GhPrObserver;
188
189impl PrObserver for GhPrObserver {
190 async fn observe_pr(&self, repo: &Path, pr_url: &str) -> Result<ObservedPr> {
191 crate::land::observe_pr_summary(repo, pr_url).await
192 }
193}
194
195fn matches_exhausted_detail(detail: &str) -> bool {
196 let trimmed = detail.trim();
197 trimmed == EXHAUSTED_DETAIL
198 || trimmed == format!("could not synchronize landing base: {EXHAUSTED_DETAIL}")
199}
200
201fn matches_exhausted_event(message: &str) -> bool {
202 let trimmed = message.trim();
203 trimmed == format!("stopped: could not synchronize landing base: {EXHAUSTED_DETAIL}")
204 || trimmed == format!("stopped: {EXHAUSTED_DETAIL}")
205 || trimmed == format!("gave up: {EXHAUSTED_DETAIL}")
206 || trimmed == format!("gave up: could not synchronize landing base: {EXHAUSTED_DETAIL}")
207}
208
209fn legacy_exhausted_diagnostic(state: &RunState) -> bool {
210 if let Some(last_land) = state.events.iter().rev().find(|e| e.node == "land") {
211 matches_exhausted_event(&last_land.message)
212 } else {
213 state
214 .merge
215 .as_ref()
216 .is_some_and(|m| !m.ok && matches_exhausted_detail(&m.detail))
217 }
218}
219
220fn exhausted_stop_timestamp(state: &RunState) -> Timestamp {
221 state
222 .events
223 .iter()
224 .rev()
225 .find(|e| e.node == "land" && matches_exhausted_event(&e.message))
226 .map_or(state.updated_at, |e| e.at)
227}
228
229impl RunState {
230 pub fn land_sync_budget(&self) -> usize {
232 self.config
233 .graph
234 .land_rounds
235 .saturating_add(self.land_sync_recovery.extra_attempts)
236 .saturating_sub(
237 self.land_sync_recovery
238 .authorizations
239 .iter()
240 .filter(|a| a.invalidated.is_some() && a.archived_verification.is_some())
241 .count(),
242 )
243 }
244
245 pub fn land_sync_grants_remaining(&self) -> usize {
247 MAX_GRANTS.saturating_sub(self.land_sync_recovery.extra_attempts)
248 }
249
250 pub fn land_sync_exhausted(&self) -> bool {
253 if self.status != RunStatus::Blocked {
254 return false;
255 }
256 if self.released_to.is_some()
257 || self.retired_to.is_some()
258 || self.pr_taken_over_by.is_some()
259 {
260 return false;
261 }
262 if !crate::handover::landing_checkpoint(self)
263 || self.base_sync_blocked()
264 || self.pr_publication_pending
265 {
266 return false;
267 }
268 if self.merge_decision.is_some()
269 || self.resource_block.is_some()
270 || self.sequencer_stop.is_some()
271 || self.land_rebase_from.is_some()
272 || self.land_sync_target.is_some()
273 {
274 return false;
275 }
276 if self.merge_repairs.last().is_some_and(|r| {
277 matches!(
278 r.phase,
279 MergeRepairPhase::Requested
280 | MergeRepairPhase::Fixing
281 | MergeRepairPhase::Reviewing
282 )
283 }) || self
284 .repair_grants
285 .last()
286 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
287 || self
288 .rebase_fixes
289 .iter()
290 .any(|r| r.stop.is_none() && !r.finished)
291 {
292 return false;
293 }
294 if !self.land_sync_pending
295 || self.land_sync_attempts == 0
296 || self.land_sync_attempts < self.land_sync_budget()
297 {
298 return false;
299 }
300 if let Some(stop) = &self.land_sync_recovery.stop {
301 stop.detail == EXHAUSTED_DETAIL
302 && stop.attempts == self.land_sync_attempts
303 && stop.limit == self.land_sync_budget()
304 && self
305 .pr
306 .as_ref()
307 .is_some_and(|pr| pr.url == stop.pr_url && pr.number == stop.pr_number)
308 && self.land_sync_recovery.stops.contains(stop)
309 } else {
310 self.land_sync_recovery
311 .authorizations
312 .last()
313 .is_some_and(|a| {
314 a.invalidated.is_some()
315 && a.archived_verification.is_some()
316 && a.stop.attempts == self.land_sync_attempts
317 })
318 || (self.land_sync_recovery.stops.is_empty()
319 && self.land_sync_recovery.authorizations.is_empty()
320 && legacy_exhausted_diagnostic(self))
321 }
322 }
323
324 pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
326 self.land_sync_recovery
327 .authorizations
328 .iter()
329 .any(|a| !a.consumed && a.invalidated.is_none())
330 }
331
332 pub fn land_sync_recovery_pending(&self) -> bool {
334 self.land_sync_exhausted()
335 && self
336 .land_sync_recovery
337 .authorizations
338 .last()
339 .is_some_and(|a| {
340 !a.consumed
341 && a.invalidated.is_none()
342 && a.run == self.id
343 && a.granted_attempts == GRANT_ATTEMPTS
344 && a.scope.grant_index == self.land_sync_recovery.extra_attempts
345 && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
346 })
347 }
348
349 pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
352 self.status.resumable()
353 && self
354 .land_sync_recovery
355 .authorizations
356 .last()
357 .is_some_and(|a| {
358 a.consumed
359 && a.invalidated.is_none()
360 && a.archived_verification.is_some()
361 && self.land_sync_attempts == a.stop.attempts
362 && self.land_sync_recovery.extra_attempts
363 == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
364 })
365 }
366
367 pub fn land_sync_next_action(&self) -> String {
369 let attempts = self.land_sync_attempts;
370 let limit = self.land_sync_budget();
371 let grants = self.land_sync_recovery.extra_attempts;
372 let head = self
373 .land_sync_recovery
374 .stop
375 .as_ref()
376 .map(|s| s.head.as_str())
377 .or(self.pr_pushed_head.as_deref())
378 .unwrap_or("<full-head-sha>");
379 if let Some(reason) = self
380 .land_sync_recovery
381 .authorizations
382 .last()
383 .and_then(|a| a.invalidated.as_ref())
384 && !self.land_sync_recovery_pending()
385 {
386 if self.land_sync_grants_remaining() == 0 {
387 return format!(
388 "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
389 );
390 }
391 return format!(
392 "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)",
393 self.id
394 );
395 }
396 if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
397 return format!(
398 "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)"
399 );
400 }
401 if self.land_sync_grants_remaining() == 0 {
402 return format!(
403 "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
404 );
405 }
406 format!(
407 "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)",
408 self.id
409 )
410 }
411
412 pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
414 let Some(pr) = self.pr.as_ref() else {
415 return;
416 };
417 let limit = self.land_sync_budget();
418 if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
419 s.attempts == self.land_sync_attempts
420 && s.limit == limit
421 && s.head.eq_ignore_ascii_case(head)
422 && s.pr_head.eq_ignore_ascii_case(pr_head)
423 && s.pr_url == pr.url
424 && s.pr_number == pr.number
425 && s.detail == EXHAUSTED_DETAIL
426 }) {
427 return;
428 }
429 let at = exhausted_stop_timestamp(self);
430 let stop = Stop {
431 attempts: self.land_sync_attempts,
432 limit,
433 head: head.to_ascii_lowercase(),
434 pr_head: pr_head.to_ascii_lowercase(),
435 pr_url: pr.url.clone(),
436 pr_number: pr.number,
437 tip: tip.to_ascii_lowercase(),
438 detail: EXHAUSTED_DETAIL.to_owned(),
439 at,
440 };
441 if !self.land_sync_recovery.stops.contains(&stop) {
442 self.land_sync_recovery.stops.push(stop.clone());
443 }
444 self.land_sync_recovery.stop = Some(stop);
445 }
446
447 pub(crate) fn consume_land_sync_recovery(
453 &mut self,
454 head: &str,
455 pr_head: &str,
456 ) -> std::result::Result<(), String> {
457 if !self.land_sync_recovery_pending() {
458 return Err("no matching pending landing base-sync recovery authorization".into());
459 }
460 let now = Timestamp::now();
461 let granted = self
462 .land_sync_recovery
463 .authorizations
464 .last()
465 .map(|a| a.granted_attempts)
466 .unwrap_or(0);
467 let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
468 return Err("landing base-sync grant counter overflow".into());
469 };
470 if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
471 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
472 auth.refuse(format!(
473 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
474 self.land_sync_recovery.extra_attempts
475 ));
476 }
477 return Err("lifetime landing base-sync recovery limit reached".into());
478 }
479 let head_mismatch = self
480 .land_sync_recovery
481 .authorizations
482 .last()
483 .is_some_and(|a| {
484 !a.stop.head.eq_ignore_ascii_case(head)
485 || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
486 });
487 if head_mismatch {
488 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
489 auth.refuse(format!(
490 "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
491 auth.stop.head, auth.stop.pr_head
492 ));
493 }
494 return Err("retained or published HEAD changed before consumption".into());
495 }
496
497 let gate = std::mem::take(&mut self.gate);
500 let gate_head = self.gate_head.take();
501 let gate_ran = std::mem::replace(&mut self.gate_ran, false);
502 let head_e2e = self.head_e2e.take();
503 let gate_repair_e2e = self.gate_repair_e2e.take();
504 self.pre_gate.clear();
505 self.pre_gate_commit = None;
506
507 let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
508 for review in &mut self.reviews {
509 review_verified_heads.push((review.round, review.verified_head.take()));
510 }
511
512 if gate_ran || !gate.is_empty() || head_e2e.is_some() {
513 self.verification_history.push(VerificationEvidence {
514 superseded_by: None,
515 archived_at: Some(now),
516 fixes_spent: Some(self.gate_fixes.len()),
517 gate_head: gate_head.clone(),
518 gate_ran,
519 gate: gate.clone(),
520 e2e: head_e2e.clone(),
521 });
522 }
523 if let Some(repair_e2e) = &gate_repair_e2e {
524 self.verification_history.push(VerificationEvidence {
525 superseded_by: None,
526 archived_at: Some(now),
527 fixes_spent: Some(self.gate_fixes.len()),
528 gate_head: None,
529 gate_ran: false,
530 gate: Vec::new(),
531 e2e: Some(repair_e2e.clone()),
532 });
533 }
534
535 let archived = ArchivedVerification {
536 archived_at: now,
537 head: head.to_ascii_lowercase(),
538 gate_head,
539 gate_ran,
540 gate,
541 head_e2e,
542 gate_repair_e2e,
543 review_verified_heads,
544 };
545
546 let auth = self
547 .land_sync_recovery
548 .authorizations
549 .last_mut()
550 .expect("pending authorization exists");
551 auth.consumed = true;
552 auth.consumed_at = Some(now);
553 auth.archived_verification = Some(archived);
554
555 self.land_sync_recovery.extra_attempts = next_extra;
556 self.land_sync_recovery.stop = None;
557 Ok(())
558 }
559}
560
561pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
563 let Some(state) = latest_exhausted_run(queue, task) else {
564 return false;
565 };
566 if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
567 {
568 return false;
569 }
570 let Some(auth) = state.land_sync_recovery.authorizations.last() else {
571 return false;
572 };
573 if task.id != auth.task
574 || !task.assignment_accepts(&state)
575 || task.instruction != auth.scope.instruction
576 || task.operator_decided_at != auth.decision
577 || auth
578 .generation
579 .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
580 || !task.land_sync_recovery_requests.contains(&auth.request)
581 || task.fresh_start
582 || task.review_branch.is_some()
583 || task.pr_recovery.is_some()
584 || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
585 {
586 return false;
587 }
588 task.status = TaskStatus::Queued;
589 task.hold_source = None;
590 task.hold_reason = None;
591 task.held_at = None;
592 true
593}
594
595pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
598 held_run(queue, task).is_some()
599}
600
601pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
604 latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
605}
606
607pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
610 let home = queue.root().parent()?;
611 task.execution_runs()
612 .last()
613 .and_then(|id| RunState::load_under(id, home).ok())
614 .filter(|state| {
615 state.land_sync_exhausted()
616 || state.has_unconsumed_land_sync_authorization()
617 || state.land_sync_unstarted_grant()
618 })
619}
620
621#[derive(Debug)]
628pub(crate) struct ValidationFailure {
629 pub reason: String,
630 pub observation_failed: bool,
631}
632
633impl ValidationFailure {
634 fn observation(reason: String) -> Self {
635 Self {
636 reason,
637 observation_failed: true,
638 }
639 }
640}
641
642impl From<String> for ValidationFailure {
643 fn from(reason: String) -> Self {
644 Self {
645 reason,
646 observation_failed: false,
647 }
648 }
649}
650
651impl From<&str> for ValidationFailure {
652 fn from(reason: &str) -> Self {
653 reason.to_owned().into()
654 }
655}
656
657pub(crate) async fn validate_pending_authorization<O: PrObserver>(
658 home: &Path,
659 state: &RunState,
660 task_override: Option<&Task>,
661 observed_override: Option<&ObservedPr>,
662 observer: &O,
663) -> std::result::Result<(String, String), ValidationFailure> {
664 let unstarted = state.land_sync_unstarted_grant();
665 if !state.land_sync_recovery_pending() && !unstarted {
666 return Err("landing base-sync stop or pending authorization state changed".into());
667 }
668 if let Err(error) = crate::pr_head::ensure_owner(state) {
669 return Err(format!("run ownership check failed: {error:#}").into());
670 }
671 let auth = state
672 .land_sync_recovery
673 .authorizations
674 .last()
675 .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
676 if auth.invalidated.is_some() {
677 return Err("landing base-sync recovery authorization was invalidated".into());
678 }
679 if auth.granted_attempts != GRANT_ATTEMPTS
680 || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
681 {
682 return Err(format!(
683 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
684 state.land_sync_recovery.extra_attempts
685 )
686 .into());
687 }
688
689 if !auth.task.is_empty() {
690 let loaded_task;
691 let task = match task_override {
692 Some(task) => task,
693 None => {
694 loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
695 ValidationFailure::observation(format!(
696 "owning task {} unreadable: {e:#}",
697 auth.task
698 ))
699 })?;
700 &loaded_task
701 }
702 };
703 if task.id != auth.task {
704 return Err("authorization targets a different task".into());
705 }
706 if state
707 .origin
708 .as_ref()
709 .and_then(|o| o.task.as_deref())
710 .is_some_and(|owner| owner != task.id)
711 {
712 return Err("run belongs to another task".into());
713 }
714 if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
715 return Err("run is no longer the task's latest execution".into());
716 }
717 if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
718 return Err("task repository assignment changed since authorization".into());
719 }
720 if task.status == TaskStatus::Done
721 || task.fresh_start
722 || task.review_branch.is_some()
723 || task.pr_recovery.is_some()
724 {
725 return Err("task queue state changed since authorization".into());
726 }
727 if task.instruction != auth.scope.instruction
728 || !crate::daemon::compatible_run_instruction(state, task)
729 {
730 return Err("task instruction changed since authorization".into());
731 }
732 if task.operator_decided_at != auth.decision {
733 return Err("a newer owner decision superseded this recovery authorization".into());
734 }
735 if let Some(generation) = auth.generation
736 && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
737 {
738 return Err("task resumption generation changed since authorization".into());
739 }
740 if task_override.is_some()
741 && !task
742 .resume_override
743 .as_ref()
744 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
745 && !(task.resume_override.is_none()
746 && task.land_sync_recovery_requests.contains(&auth.request))
747 {
748 return Err("task exact-run pin is missing or targets another run".into());
749 }
750 }
751
752 let winner = state
753 .winner()
754 .ok_or_else(|| "run has no retained winner".to_owned())?;
755 let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
756 ValidationFailure::observation(format!(
757 "could not inspect retained worktree cleanliness: {e:#}"
758 ))
759 })?;
760 if !clean {
761 return Err("retained worktree has uncommitted changes".into());
762 }
763 let scratch = home.join("runs").join(&state.id).join("rebase");
764 let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
765 .await
766 .map_err(|e| {
767 ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
768 })?;
769 if rebase_in_progress {
770 return Err("landing rebase is already in progress in scratch worktree".into());
771 }
772 let local_head = git::rev_parse(&winner.worktree, "HEAD")
773 .await
774 .map_err(|e| {
775 ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
776 })?;
777 let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
778 .await
779 .map_err(|e| {
780 ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
781 })?;
782 if local_head != branch_head {
783 return Err("retained worktree HEAD does not match the winner branch ref".into());
784 }
785 if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
786 return Err(format!(
787 "retained HEAD changed from {} to {local_head}",
788 auth.stop.head
789 )
790 .into());
791 }
792 if !state
793 .pr_pushed_head
794 .as_deref()
795 .is_some_and(|h| h.eq_ignore_ascii_case(&local_head))
796 {
797 return Err("saved pr_pushed_head no longer matches the retained HEAD".into());
798 }
799 if !auth.stop.pr_head.eq_ignore_ascii_case(&local_head)
800 || !auth.scope.pr_head.eq_ignore_ascii_case(&local_head)
801 {
802 return Err("authorized PR head does not match the retained HEAD".into());
803 }
804 if !state.pr.as_ref().is_some_and(|pr| {
805 pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
806 }) {
807 return Err("recorded pull request metadata changed since authorization".into());
808 }
809
810 let fetched_pr;
811 let observed = match observed_override {
812 Some(observed) => observed,
813 None => {
814 fetched_pr = observer
815 .observe_pr(&state.repo, &auth.scope.pr_url)
816 .await
817 .map_err(|e| {
818 ValidationFailure::observation(format!(
819 "could not verify open pull request state: {e:#}"
820 ))
821 })?;
822 &fetched_pr
823 }
824 };
825 if !observed.open {
826 return Err("pull request is no longer open".into());
827 }
828 if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
829 return Err("observed pull request does not match authorized pull request".into());
830 }
831 if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
832 return Err(ValidationFailure::observation(
833 "observed pull request head is unreadable".into(),
834 ));
835 }
836 if !observed.head.eq_ignore_ascii_case(&local_head) {
837 return Err(format!(
838 "published PR head changed from {} to {}",
839 auth.scope.pr_head, observed.head
840 )
841 .into());
842 }
843 if observed
844 .base_branch
845 .as_deref()
846 .is_some_and(|b| !b.is_empty() && b != state.base_branch)
847 {
848 return Err("pull request base branch changed since authorization".into());
849 }
850
851 let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
852 .await
853 .map_err(|e| {
854 ValidationFailure::observation(format!(
855 "could not fetch base branch for revalidation: {e:#}"
856 ))
857 })?;
858 if !fetched.ok() {
859 return Err(ValidationFailure::observation(format!(
860 "could not fetch base branch for revalidation: {}",
861 fetched.stderr
862 )));
863 }
864 let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
865 let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
866 ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
867 })?;
868 let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, ¤t_tip)
869 .await
870 .map_err(|e| {
871 ValidationFailure::observation(format!(
872 "could not verify base tip lineage against authorized tip: {e:#}"
873 ))
874 })?;
875 if !descends_scope {
876 return Err(format!(
877 "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
878 auth.scope.tip
879 )
880 .into());
881 }
882 let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, ¤t_tip)
883 .await
884 .map_err(|e| {
885 ValidationFailure::observation(format!(
886 "could not verify base tip lineage against stopped tip: {e:#}"
887 ))
888 })?;
889 if !descends_stop {
890 return Err(format!(
891 "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
892 auth.stop.tip
893 )
894 .into());
895 }
896
897 Ok((local_head, observed.head.clone()))
898}
899
900pub(crate) enum DispatchDecision {
902 Proceed,
904 Hold {
906 reason: String,
907 state: Box<RunState>,
908 },
909}
910
911pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
913 dispatch_check_with(queue, home, task, &GhPrObserver).await
914}
915
916pub(crate) async fn dispatch_check_with<O: PrObserver>(
918 queue: &Queue,
919 home: &Path,
920 task: &Task,
921 observer: &O,
922) -> DispatchDecision {
923 let Some(state) = latest_exhausted_run(queue, task) else {
924 return DispatchDecision::Proceed;
925 };
926 if task
929 .resume_override
930 .as_ref()
931 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
932 && let Some(pr) = &state.pr
933 && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
934 && !observed.open
935 && observed.url == pr.url
936 && observed.number == pr.number
937 {
938 return DispatchDecision::Proceed;
939 }
940 if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
941 return DispatchDecision::Hold {
942 reason: format!(
943 "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
944 state.land_sync_next_action()
945 ),
946 state: Box::new(state),
947 };
948 }
949 match validate_pending_authorization(home, &state, Some(task), None, observer).await {
950 Ok(_) => DispatchDecision::Proceed,
951 Err(failure) => {
952 let reason = failure.reason;
953 let mut updated = state;
954 if !failure.observation_failed
955 && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
956 && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
957 && let Ok(claimed) =
958 crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
959 && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
960 && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
961 && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
962 && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
963 && auth.invalidated.is_none()
964 && updated
965 .land_sync_recovery
966 .authorizations
967 .last()
968 .is_some_and(|prior| prior.request == auth.request)
969 {
970 auth.refuse(&reason);
971 reloaded.event(
972 "land-sync-recovery",
973 format!("dispatch revalidation refused: {reason}"),
974 );
975 let _ = reloaded.save_under(home);
976 updated = reloaded;
977 }
978 DispatchDecision::Hold {
979 reason: format!(
980 "Landing base-sync recovery refused at dispatch: {reason}. {}",
981 updated.land_sync_next_action()
982 ),
983 state: Box::new(updated),
984 }
985 }
986 }
987}
988
989impl Task {
990 pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
992 if !state.land_sync_exhausted() {
993 return;
994 }
995 let stop = state.land_sync_recovery.stop.as_ref();
996 self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
997 self.notice_cause("land-sync-exhausted", Some(&state.id), None);
998 if let Some(cause) = &mut self.hold_notice_cause {
999 cause.target = Some(match stop {
1000 Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
1001 None => format!(
1002 "legacy:{}:{}:{}",
1003 state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1004 state.land_sync_attempts,
1005 state.land_sync_budget()
1006 ),
1007 });
1008 }
1009 }
1010}